repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
JazzeYoung/VeryDeepAutoEncoder
refs/heads/master
pylearn2/models/differentiable_sparse_coding.py
44
""" An implementation of the model described in "Differentiable Sparse Coding" by Bradley and Bagnell """ __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" import logging import numpy as N from theano.compat.six.moves import xrange import theano.tensor as T import theano from theano import function, shared, config floatX = config.floatX from pylearn2.utils.rng import make_np_rng logger = logging.getLogger(__name__) class DifferentiableSparseCoding(object): """ .. todo:: WRITEME Parameters ---------- nvis : WRITEME nhid : WRITEME init_lambda : WRITEME init_p : WRITEME init_alpha : WRITEME learning_rate : WRITEME """ def __init__(self, nvis, nhid, init_lambda, init_p, init_alpha, learning_rate): self.nvis = int(nvis) self.nhid = int(nhid) self.init_lambda = float(init_lambda) self.init_p = float(init_p) self.init_alpha = N.cast[config.floatX](init_alpha) self.tol = 1e-6 self.time_constant = 1e-2 self.learning_rate = N.cast[config.floatX](learning_rate) self.predictor_learning_rate = self.learning_rate self.rng = make_np_rng(None, [1,2,3], which_method="randn") self.error_record = [] self.ERROR_RECORD_MODE_MONITORING = 0 self.error_record_mode = self.ERROR_RECORD_MODE_MONITORING self.instrumented = False self.redo_everything() def get_output_dim(self): """ .. todo:: WRITEME """ return self.nhid def get_output_channels(self): """ .. todo:: WRITEME """ return self.nhid def normalize_W(self): """ .. todo:: WRITEME """ W = self.W.get_value(borrow=True) norms = N.sqrt(N.square(W).sum(axis=0)) self.W.set_value(W/norms, borrow=True) def redo_everything(self): """ .. todo:: WRITEME """ self.W = shared(N.cast[floatX](self.rng.randn(self.nvis,self.nhid)), name='W') self.pred_W = shared(self.W.get_value(borrow=False),name='pred_W') self.pred_b = shared(N.zeros(self.nhid,dtype=floatX),name='pred_b') self.pred_g = shared(N.ones(self.nhid,dtype=floatX),name='pred_g') self.normalize_W() self.p = shared(N.zeros(self.nhid, dtype=floatX)+N.cast[floatX](self.init_p), name='p') #mispelling lambda because python is too dumb to know that self.lambda isn't a lambda function self.lamda = shared( N.zeros( self.nhid, dtype=floatX)+ N.cast[floatX](self.init_lambda), name='lambda') self.alpha = self.init_alpha self.failure_rate = .5 self.examples_seen = 0 self.batches_seen = 0 self.redo_theano() def recons_error(self, v, h): """ .. todo:: WRITEME """ recons = T.dot(self.W,h) diffs = recons - v rval = T.dot(diffs,diffs) / N.cast[floatX](self.nvis) return rval def recons_error_batch(self, V, H): """ .. todo:: WRITEME """ recons = T.dot(H,self.W.T) diffs = recons - V rval = T.mean(T.sqr(diffs)) return rval def sparsity_penalty(self, v, h): """ .. todo:: WRITEME """ sparsity_measure = h * T.log(h) - h * T.log(self.p) - h + self.p rval = T.dot(self.lamda, sparsity_measure) / N.cast[floatX](self.nhid) return rval def sparsity_penalty_batch(self, V, H): """ .. todo:: WRITEME """ sparsity_measure = H * T.log(H) - H * T.log(self.p) - H + self.p sparsity_measure_exp = T.mean(sparsity_measure, axis=0) rval = T.dot(self.lamda, sparsity_measure_exp) / N.cast[floatX](self.nhid) return rval def coding_obj(self, v, h): """ .. todo:: WRITEME """ return self.recons_error(v,h) + self.sparsity_penalty(v,h) def coding_obj_batch(self, V, H): """ .. todo:: WRITEME """ return self.recons_error_batch(V,H) + self.sparsity_penalty_batch(V,H) def predict(self, V): """ .. todo:: WRITEME """ rval = T.nnet.sigmoid(T.dot(V,self.pred_W)+self.pred_b)*self.pred_g assert rval.type.dtype == V.type.dtype return rval def redo_theano(self): """ .. todo:: WRITEME """ self.h = shared(N.zeros(self.nhid, dtype=floatX), name='h') self.v = shared(N.zeros(self.nvis, dtype=floatX), name='v') input_v = T.vector() assert input_v.type.dtype == floatX self.init_h_v = function([input_v], updates = { self.h : self.predict(input_v), self.v : input_v } ) coding_obj = self.coding_obj(self.v, self.h) assert len(coding_obj.type.broadcastable) == 0 coding_grad = T.grad(coding_obj, self.h) assert len(coding_grad.type.broadcastable) == 1 self.coding_obj_grad = function([], [coding_obj, coding_grad] ) self.new_h = shared(N.zeros(self.nhid, dtype=floatX), name='new_h') alpha = T.scalar(name='alpha') outside_grad = T.vector(name='outside_grad') new_h = T.clip(self.h * T.exp(-alpha * outside_grad), 1e-10, 1e4) new_obj = self.coding_obj(self.v, new_h) self.try_step = function( [alpha, outside_grad], updates = { self.new_h : new_h }, outputs = new_obj ) self.accept_h = function( [], updates = { self.h : self.new_h } ) self.get_h = function( [] , self.h ) V = T.matrix(name='V') H = T.matrix(name='H') coding_obj_batch = self.coding_obj_batch(V,H) self.code_learning_obj = function( [V,H], coding_obj_batch) learning_grad = T.grad( coding_obj_batch, self.W ) self.code_learning_step = function( [V,H,alpha], updates = { self.W : self.W - alpha * learning_grad } ) pred_obj = T.mean(T.sqr(self.predict(V)-H)) predictor_params = [ self.pred_W, self.pred_b, self.pred_g ] pred_grads = T.grad(pred_obj, wrt = predictor_params ) predictor_updates = {} for param, grad in zip(predictor_params, pred_grads): predictor_updates[param] = param - alpha * grad predictor_updates[self.pred_g ] = T.clip(predictor_updates[self.pred_g], N.cast[floatX](0.5), N.cast[floatX](1000.)) self.train_predictor = function([V,H,alpha] , updates = predictor_updates ) def weights_format(self): """ .. todo:: WRITEME """ return ['v','h'] def error_func(self, x): """ .. todo:: WRITEME """ batch_size = x.shape[0] H = N.zeros((batch_size,self.nhid),dtype=floatX) for i in xrange(batch_size): assert self.alpha > 9e-8 H[i,:] = self.optimize_h(x[i,:]) assert self.alpha > 9e-8 return self.code_learning_obj(x,H) def record_monitoring_error(self, dataset, batch_size, batches): """ .. todo:: WRITEME """ logger.info('running on monitoring set') assert self.error_record_mode == self.ERROR_RECORD_MODE_MONITORING w = self.W.get_value(borrow=True) logger.info('weights summary: ' '({0}, {1}, {2})'.format(w.min(), w.mean(), w.max())) errors = [] if self.instrumented: self.clear_instruments() for i in xrange(batches): x = dataset.get_batch_design(batch_size) error = self.error_func(x) errors.append( error ) if self.instrumented: self.update_instruments(x) self.error_record.append( (self.examples_seen, self.batches_seen, N.asarray(errors).mean() ) ) if self.instrumented: self.instrument_record.begin_report(examples_seen = self.examples_seen, batches_seen = self.batches_seen) self.make_instrument_report() self.instrument_record.end_report() self.clear_instruments() logger.info('monitoring set done') def infer_h(self, v): """ .. todo:: WRITEME """ return self.optimize_h(v) def optimize_h(self, v): """ .. todo:: WRITEME """ assert self.alpha > 9e-8 self.init_h_v(v) first = True while True: obj, grad = self.coding_obj_grad() if first: #print 'orig_obj: ', obj first = False assert not N.any(N.isnan(obj)) assert not N.any(N.isnan(grad)) if N.abs(grad).max() < self.tol: break #print 'max gradient ',N.abs(grad).max() cur_alpha = N.cast[floatX] ( self.alpha + 0.0 ) new_obj = self.try_step(cur_alpha, grad) assert not N.isnan(new_obj) self.failure_rate = (1. - self.time_constant ) * self.failure_rate + self.time_constant * float(new_obj > obj ) assert self.alpha > 9e-8 if self.failure_rate > .6 and self.alpha > 1e-7: self.alpha *= .9 #print '!!!!!!!!!!!!!!!!!!!!!!shrank alpha to ',self.alpha elif self.failure_rate < .3: self.alpha *= 1.1 #print '**********************grew alpha to ',self.alpha assert self.alpha > 9e-8 while new_obj >= obj: cur_alpha *= .9 if cur_alpha < 1e-12: self.accept_h() #print 'failing final obj ',new_obj return self.get_h() new_obj = self.try_step(cur_alpha, grad) assert not N.isnan(new_obj) self.accept_h() #print 'final obj ',new_obj return self.get_h() def train_batch(self, dataset, batch_size): """ .. todo:: WRITEME """ self.learn_mini_batch(dataset.get_batch_design(batch_size)) return True def learn_mini_batch(self, x): """ .. todo:: WRITEME """ assert self.alpha > 9e-8 batch_size = x.shape[0] H = N.zeros((batch_size,self.nhid),dtype=floatX) for i in xrange(batch_size): assert self.alpha > 9e-8 H[i,:] = self.optimize_h(x[i,:]) assert self.alpha > 9e-8 self.code_learning_step(x,H,self.learning_rate) self.normalize_W() self.train_predictor(x,H,self.predictor_learning_rate) self.examples_seen += x.shape[0] self.batches_seen += 1
xeddmc/pupy
refs/heads/master
pupy/packages/windows/amd64/psutil/_psosx.py
81
#!/usr/bin/env python # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """OSX platform implementation.""" import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import conn_tmap, usage_percent, isfile_strict from ._common import sockfam_to_enum, socktype_to_enum __extra__all__ = [] # --- constants PAGESIZE = os.sysconf("SC_PAGE_SIZE") AF_LINK = cext_posix.AF_LINK # http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h TCP_STATUSES = { cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV, cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, cext.TCPS_CLOSED: _common.CONN_CLOSE, cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, cext.TCPS_LISTEN: _common.CONN_LISTEN, cext.TCPS_CLOSING: _common.CONN_CLOSING, cext.PSUTIL_CONN_NONE: _common.CONN_NONE, } PROC_STATUSES = { cext.SIDL: _common.STATUS_IDLE, cext.SRUN: _common.STATUS_RUNNING, cext.SSLEEP: _common.STATUS_SLEEPING, cext.SSTOP: _common.STATUS_STOPPED, cext.SZOMB: _common.STATUS_ZOMBIE, } scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle']) svmem = namedtuple( 'svmem', ['total', 'available', 'percent', 'used', 'free', 'active', 'inactive', 'wired']) pextmem = namedtuple('pextmem', ['rss', 'vms', 'pfaults', 'pageins']) pmmap_grouped = namedtuple( 'pmmap_grouped', 'path rss private swapped dirtied ref_count shadow_depth') pmmap_ext = namedtuple( 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields)) # set later from __init__.py NoSuchProcess = None ZombieProcess = None AccessDenied = None TimeoutExpired = None # --- functions def virtual_memory(): """System virtual memory as a namedtuple.""" total, active, inactive, wired, free = cext.virtual_mem() avail = inactive + free used = active + inactive + wired percent = usage_percent((total - avail), total, _round=1) return svmem(total, avail, percent, used, free, active, inactive, wired) def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" total, used, free, sin, sout = cext.swap_mem() percent = usage_percent(used, total, _round=1) return _common.sswap(total, used, free, percent, sin, sout) def cpu_times(): """Return system CPU times as a namedtuple.""" user, nice, system, idle = cext.cpu_times() return scputimes(user, nice, system, idle) def per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in cext.per_cpu_times(): user, nice, system, idle = cpu_t item = scputimes(user, nice, system, idle) ret.append(item) return ret def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical() def cpu_count_physical(): """Return the number of physical CPUs in the system.""" return cext.cpu_count_phys() def boot_time(): """The system boot time expressed in seconds since the epoch.""" return cext.boot_time() def disk_partitions(all=False): retlist = [] partitions = cext.disk_partitions() for partition in partitions: device, mountpoint, fstype, opts = partition if device == 'none': device = '' if not all: if not os.path.isabs(device) or not os.path.exists(device): continue ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) retlist.append(ntuple) return retlist def users(): retlist = [] rawlist = cext.users() for item in rawlist: user, tty, hostname, tstamp = item if tty == '~': continue # reboot or shutdown if not tstamp: continue nt = _common.suser(user, tty or None, hostname or None, tstamp) retlist.append(nt) return retlist def net_connections(kind='inet'): # Note: on OSX this will fail with AccessDenied unless # the process is owned by root. ret = [] for pid in pids(): try: cons = Process(pid).connections(kind) except NoSuchProcess: continue else: if cons: for c in cons: c = list(c) + [pid] ret.append(_common.sconn(*c)) return ret def net_if_stats(): """Get NIC stats (isup, duplex, speed, mtu).""" names = net_io_counters().keys() ret = {} for name in names: isup, duplex, speed, mtu = cext_posix.net_if_stats(name) if hasattr(_common, 'NicDuplex'): duplex = _common.NicDuplex(duplex) ret[name] = _common.snicstats(isup, duplex, speed, mtu) return ret pids = cext.pids pid_exists = _psposix.pid_exists disk_usage = _psposix.disk_usage net_io_counters = cext.net_io_counters disk_io_counters = cext.disk_io_counters net_if_addrs = cext_posix.net_if_addrs def wrap_exceptions(fun): """Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except OSError as err: # support for private module import if (NoSuchProcess is None or AccessDenied is None or ZombieProcess is None): raise if err.errno == errno.ESRCH: if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name) else: raise ZombieProcess(self.pid, self._name, self._ppid) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._name) raise return wrapper class Process(object): """Wrapper class around underlying C implementation.""" __slots__ = ["pid", "_name", "_ppid"] def __init__(self, pid): self.pid = pid self._name = None self._ppid = None @wrap_exceptions def name(self): return cext.proc_name(self.pid) @wrap_exceptions def exe(self): return cext.proc_exe(self.pid) @wrap_exceptions def cmdline(self): if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name) return cext.proc_cmdline(self.pid) @wrap_exceptions def ppid(self): return cext.proc_ppid(self.pid) @wrap_exceptions def cwd(self): return cext.proc_cwd(self.pid) @wrap_exceptions def uids(self): real, effective, saved = cext.proc_uids(self.pid) return _common.puids(real, effective, saved) @wrap_exceptions def gids(self): real, effective, saved = cext.proc_gids(self.pid) return _common.pgids(real, effective, saved) @wrap_exceptions def terminal(self): tty_nr = cext.proc_tty_nr(self.pid) tmap = _psposix._get_terminal_map() try: return tmap[tty_nr] except KeyError: return None @wrap_exceptions def memory_info(self): rss, vms = cext.proc_memory_info(self.pid)[:2] return _common.pmem(rss, vms) @wrap_exceptions def memory_info_ex(self): rss, vms, pfaults, pageins = cext.proc_memory_info(self.pid) return pextmem(rss, vms, pfaults * PAGESIZE, pageins * PAGESIZE) @wrap_exceptions def cpu_times(self): user, system = cext.proc_cpu_times(self.pid) return _common.pcputimes(user, system) @wrap_exceptions def create_time(self): return cext.proc_create_time(self.pid) @wrap_exceptions def num_ctx_switches(self): return _common.pctxsw(*cext.proc_num_ctx_switches(self.pid)) @wrap_exceptions def num_threads(self): return cext.proc_num_threads(self.pid) @wrap_exceptions def open_files(self): if self.pid == 0: return [] files = [] rawlist = cext.proc_open_files(self.pid) for path, fd in rawlist: if isfile_strict(path): ntuple = _common.popenfile(path, fd) files.append(ntuple) return files @wrap_exceptions def connections(self, kind='inet'): if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] rawlist = cext.proc_connections(self.pid, families, types) ret = [] for item in rawlist: fd, fam, type, laddr, raddr, status = item status = TCP_STATUSES[status] fam = sockfam_to_enum(fam) type = socktype_to_enum(type) nt = _common.pconn(fd, fam, type, laddr, raddr, status) ret.append(nt) return ret @wrap_exceptions def num_fds(self): if self.pid == 0: return 0 return cext.proc_num_fds(self.pid) @wrap_exceptions def wait(self, timeout=None): try: return _psposix.wait_pid(self.pid, timeout) except _psposix.TimeoutExpired: # support for private module import if TimeoutExpired is None: raise raise TimeoutExpired(timeout, self.pid, self._name) @wrap_exceptions def nice_get(self): return cext_posix.getpriority(self.pid) @wrap_exceptions def nice_set(self, value): return cext_posix.setpriority(self.pid, value) @wrap_exceptions def status(self): code = cext.proc_status(self.pid) # XXX is '?' legit? (we're not supposed to return it anyway) return PROC_STATUSES.get(code, '?') @wrap_exceptions def threads(self): rawlist = cext.proc_threads(self.pid) retlist = [] for thread_id, utime, stime in rawlist: ntuple = _common.pthread(thread_id, utime, stime) retlist.append(ntuple) return retlist @wrap_exceptions def memory_maps(self): return cext.proc_memory_maps(self.pid)
ahmadshahwan/cohorte-runtime
refs/heads/master
python/src/lib/python/jsonrpclib/utils.py
7
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. :author: Thomas Calmant :license: Apache License 2.0 :version: 1.0.1 """ # Module version __version_info__ = (0, 2, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ import sys # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 import types try: string_types = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support string_types = (types.StringType,) numeric_types = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 string_types = ( bytes, str ) numeric_types = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple iterable_types = ( list, set, frozenset, tuple ) value_types = ( bool, type(None) ) primitive_types = string_types + numeric_types + value_types
guettli/django
refs/heads/master
django/contrib/admin/checks.py
13
# -*- coding: utf-8 -*- from __future__ import unicode_literals from itertools import chain from django.apps import apps from django.conf import settings from django.contrib.admin.utils import ( NotRelationField, flatten, get_fields_from_path, ) from django.core import checks from django.core.exceptions import FieldDoesNotExist from django.db import models from django.db.models.constants import LOOKUP_SEP from django.forms.models import ( BaseModelForm, BaseModelFormSet, _get_foreign_key, ) from django.template.engine import Engine def check_admin_app(**kwargs): from django.contrib.admin.sites import system_check_errors return system_check_errors def check_dependencies(**kwargs): """ Check that the admin's dependencies are correctly installed. """ errors = [] # contrib.contenttypes must be installed. if not apps.is_installed('django.contrib.contenttypes'): missing_app = checks.Error( "'django.contrib.contenttypes' must be in INSTALLED_APPS in order " "to use the admin application.", id="admin.E401", ) errors.append(missing_app) # The auth context processor must be installed if using the default # authentication backend. try: default_template_engine = Engine.get_default() except Exception: # Skip this non-critical check: # 1. if the user has a non-trivial TEMPLATES setting and Django # can't find a default template engine # 2. if anything goes wrong while loading template engines, in # order to avoid raising an exception from a confusing location # Catching ImproperlyConfigured suffices for 1. but 2. requires # catching all exceptions. pass else: if ('django.contrib.auth.context_processors.auth' not in default_template_engine.context_processors and 'django.contrib.auth.backends.ModelBackend' in settings.AUTHENTICATION_BACKENDS): missing_template = checks.Error( "'django.contrib.auth.context_processors.auth' must be in " "TEMPLATES in order to use the admin application.", id="admin.E402" ) errors.append(missing_template) return errors class BaseModelAdminChecks(object): def check(self, admin_obj, **kwargs): errors = [] errors.extend(self._check_raw_id_fields(admin_obj)) errors.extend(self._check_fields(admin_obj)) errors.extend(self._check_fieldsets(admin_obj)) errors.extend(self._check_exclude(admin_obj)) errors.extend(self._check_form(admin_obj)) errors.extend(self._check_filter_vertical(admin_obj)) errors.extend(self._check_filter_horizontal(admin_obj)) errors.extend(self._check_radio_fields(admin_obj)) errors.extend(self._check_prepopulated_fields(admin_obj)) errors.extend(self._check_view_on_site_url(admin_obj)) errors.extend(self._check_ordering(admin_obj)) errors.extend(self._check_readonly_fields(admin_obj)) return errors def _check_raw_id_fields(self, obj): """ Check that `raw_id_fields` only contains field names that are listed on the model. """ if not isinstance(obj.raw_id_fields, (list, tuple)): return must_be('a list or tuple', option='raw_id_fields', obj=obj, id='admin.E001') else: return list(chain(*[ self._check_raw_id_fields_item(obj, obj.model, field_name, 'raw_id_fields[%d]' % index) for index, field_name in enumerate(obj.raw_id_fields) ])) def _check_raw_id_fields_item(self, obj, model, field_name, label): """ Check an item of `raw_id_fields`, i.e. check that field named `field_name` exists in model `model` and is a ForeignKey or a ManyToManyField. """ try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E002') else: if not field.many_to_many and not isinstance(field, models.ForeignKey): return must_be('a foreign key or a many-to-many field', option=label, obj=obj, id='admin.E003') else: return [] def _check_fields(self, obj): """ Check that `fields` only refer to existing fields, doesn't contain duplicates. Check if at most one of `fields` and `fieldsets` is defined. """ if obj.fields is None: return [] elif not isinstance(obj.fields, (list, tuple)): return must_be('a list or tuple', option='fields', obj=obj, id='admin.E004') elif obj.fieldsets: return [ checks.Error( "Both 'fieldsets' and 'fields' are specified.", obj=obj.__class__, id='admin.E005', ) ] fields = flatten(obj.fields) if len(fields) != len(set(fields)): return [ checks.Error( "The value of 'fields' contains duplicate field(s).", obj=obj.__class__, id='admin.E006', ) ] return list(chain(*[ self._check_field_spec(obj, obj.model, field_name, 'fields') for field_name in obj.fields ])) def _check_fieldsets(self, obj): """ Check that fieldsets is properly formatted and doesn't contain duplicates. """ if obj.fieldsets is None: return [] elif not isinstance(obj.fieldsets, (list, tuple)): return must_be('a list or tuple', option='fieldsets', obj=obj, id='admin.E007') else: return list(chain(*[ self._check_fieldsets_item(obj, obj.model, fieldset, 'fieldsets[%d]' % index) for index, fieldset in enumerate(obj.fieldsets) ])) def _check_fieldsets_item(self, obj, model, fieldset, label): """ Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key. """ if not isinstance(fieldset, (list, tuple)): return must_be('a list or tuple', option=label, obj=obj, id='admin.E008') elif len(fieldset) != 2: return must_be('of length 2', option=label, obj=obj, id='admin.E009') elif not isinstance(fieldset[1], dict): return must_be('a dictionary', option='%s[1]' % label, obj=obj, id='admin.E010') elif 'fields' not in fieldset[1]: return [ checks.Error( "The value of '%s[1]' must contain the key 'fields'." % label, obj=obj.__class__, id='admin.E011', ) ] elif not isinstance(fieldset[1]['fields'], (list, tuple)): return must_be('a list or tuple', option="%s[1]['fields']" % label, obj=obj, id='admin.E008') fields = flatten(fieldset[1]['fields']) if len(fields) != len(set(fields)): return [ checks.Error( "There are duplicate field(s) in '%s[1]'." % label, obj=obj.__class__, id='admin.E012', ) ] return list(chain(*[ self._check_field_spec(obj, model, fieldset_fields, '%s[1]["fields"]' % label) for fieldset_fields in fieldset[1]['fields'] ])) def _check_field_spec(self, obj, model, fields, label): """ `fields` should be an item of `fields` or an item of fieldset[1]['fields'] for any `fieldset` in `fieldsets`. It should be a field name or a tuple of field names. """ if isinstance(fields, tuple): return list(chain(*[ self._check_field_spec_item(obj, model, field_name, "%s[%d]" % (label, index)) for index, field_name in enumerate(fields) ])) else: return self._check_field_spec_item(obj, model, fields, label) def _check_field_spec_item(self, obj, model, field_name, label): if field_name in obj.readonly_fields: # Stuff can be put in fields that isn't actually a model field if # it's in readonly_fields, readonly_fields will handle the # validation of such things. return [] else: try: field = model._meta.get_field(field_name) except FieldDoesNotExist: # If we can't find a field on the model that matches, it could # be an extra field on the form. return [] else: if (isinstance(field, models.ManyToManyField) and not field.remote_field.through._meta.auto_created): return [ checks.Error( "The value of '%s' cannot include the ManyToManyField '%s', " "because that field manually specifies a relationship model." % (label, field_name), obj=obj.__class__, id='admin.E013', ) ] else: return [] def _check_exclude(self, obj): """ Check that exclude is a sequence without duplicates. """ if obj.exclude is None: # default value is None return [] elif not isinstance(obj.exclude, (list, tuple)): return must_be('a list or tuple', option='exclude', obj=obj, id='admin.E014') elif len(obj.exclude) > len(set(obj.exclude)): return [ checks.Error( "The value of 'exclude' contains duplicate field(s).", obj=obj.__class__, id='admin.E015', ) ] else: return [] def _check_form(self, obj): """ Check that form subclasses BaseModelForm. """ if hasattr(obj, 'form') and not issubclass(obj.form, BaseModelForm): return must_inherit_from(parent='BaseModelForm', option='form', obj=obj, id='admin.E016') else: return [] def _check_filter_vertical(self, obj): """ Check that filter_vertical is a sequence of field names. """ if not hasattr(obj, 'filter_vertical'): return [] elif not isinstance(obj.filter_vertical, (list, tuple)): return must_be('a list or tuple', option='filter_vertical', obj=obj, id='admin.E017') else: return list(chain(*[ self._check_filter_item(obj, obj.model, field_name, "filter_vertical[%d]" % index) for index, field_name in enumerate(obj.filter_vertical) ])) def _check_filter_horizontal(self, obj): """ Check that filter_horizontal is a sequence of field names. """ if not hasattr(obj, 'filter_horizontal'): return [] elif not isinstance(obj.filter_horizontal, (list, tuple)): return must_be('a list or tuple', option='filter_horizontal', obj=obj, id='admin.E018') else: return list(chain(*[ self._check_filter_item(obj, obj.model, field_name, "filter_horizontal[%d]" % index) for index, field_name in enumerate(obj.filter_horizontal) ])) def _check_filter_item(self, obj, model, field_name, label): """ Check one item of `filter_vertical` or `filter_horizontal`, i.e. check that given field exists and is a ManyToManyField. """ try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E019') else: if not field.many_to_many: return must_be('a many-to-many field', option=label, obj=obj, id='admin.E020') else: return [] def _check_radio_fields(self, obj): """ Check that `radio_fields` is a dictionary. """ if not hasattr(obj, 'radio_fields'): return [] elif not isinstance(obj.radio_fields, dict): return must_be('a dictionary', option='radio_fields', obj=obj, id='admin.E021') else: return list(chain(*[ self._check_radio_fields_key(obj, obj.model, field_name, 'radio_fields') + self._check_radio_fields_value(obj, val, 'radio_fields["%s"]' % field_name) for field_name, val in obj.radio_fields.items() ])) def _check_radio_fields_key(self, obj, model, field_name, label): """ Check that a key of `radio_fields` dictionary is name of existing field and that the field is a ForeignKey or has `choices` defined. """ try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E022') else: if not (isinstance(field, models.ForeignKey) or field.choices): return [ checks.Error( "The value of '%s' refers to '%s', which is not an " "instance of ForeignKey, and does not have a 'choices' definition." % ( label, field_name ), obj=obj.__class__, id='admin.E023', ) ] else: return [] def _check_radio_fields_value(self, obj, val, label): """ Check type of a value of `radio_fields` dictionary. """ from django.contrib.admin.options import HORIZONTAL, VERTICAL if val not in (HORIZONTAL, VERTICAL): return [ checks.Error( "The value of '%s' must be either admin.HORIZONTAL or admin.VERTICAL." % label, obj=obj.__class__, id='admin.E024', ) ] else: return [] def _check_view_on_site_url(self, obj): if hasattr(obj, 'view_on_site'): if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool): return [ checks.Error( "The value of 'view_on_site' must be a callable or a boolean value.", obj=obj.__class__, id='admin.E025', ) ] else: return [] else: return [] def _check_prepopulated_fields(self, obj): """ Check that `prepopulated_fields` is a dictionary containing allowed field types. """ if not hasattr(obj, 'prepopulated_fields'): return [] elif not isinstance(obj.prepopulated_fields, dict): return must_be('a dictionary', option='prepopulated_fields', obj=obj, id='admin.E026') else: return list(chain(*[ self._check_prepopulated_fields_key(obj, obj.model, field_name, 'prepopulated_fields') + self._check_prepopulated_fields_value(obj, obj.model, val, 'prepopulated_fields["%s"]' % field_name) for field_name, val in obj.prepopulated_fields.items() ])) def _check_prepopulated_fields_key(self, obj, model, field_name, label): """ Check a key of `prepopulated_fields` dictionary, i.e. check that it is a name of existing field and the field is one of the allowed types. """ try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E027') else: if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)): return [ checks.Error( "The value of '%s' refers to '%s', which must not be a DateTimeField, " "a ForeignKey, or a ManyToManyField." % (label, field_name), obj=obj.__class__, id='admin.E028', ) ] else: return [] def _check_prepopulated_fields_value(self, obj, model, val, label): """ Check a value of `prepopulated_fields` dictionary, i.e. it's an iterable of existing fields. """ if not isinstance(val, (list, tuple)): return must_be('a list or tuple', option=label, obj=obj, id='admin.E029') else: return list(chain(*[ self._check_prepopulated_fields_value_item(obj, model, subfield_name, "%s[%r]" % (label, index)) for index, subfield_name in enumerate(val) ])) def _check_prepopulated_fields_value_item(self, obj, model, field_name, label): """ For `prepopulated_fields` equal to {"slug": ("title",)}, `field_name` is "title". """ try: model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E030') else: return [] def _check_ordering(self, obj): """ Check that ordering refers to existing fields or is random. """ # ordering = None if obj.ordering is None: # The default value is None return [] elif not isinstance(obj.ordering, (list, tuple)): return must_be('a list or tuple', option='ordering', obj=obj, id='admin.E031') else: return list(chain(*[ self._check_ordering_item(obj, obj.model, field_name, 'ordering[%d]' % index) for index, field_name in enumerate(obj.ordering) ])) def _check_ordering_item(self, obj, model, field_name, label): """ Check that `ordering` refers to existing fields. """ if field_name == '?' and len(obj.ordering) != 1: return [ checks.Error( "The value of 'ordering' has the random ordering marker '?', " "but contains other fields as well.", hint='Either remove the "?", or remove the other fields.', obj=obj.__class__, id='admin.E032', ) ] elif field_name == '?': return [] elif LOOKUP_SEP in field_name: # Skip ordering in the format field1__field2 (FIXME: checking # this format would be nice, but it's a little fiddly). return [] else: if field_name.startswith('-'): field_name = field_name[1:] try: model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E033') else: return [] def _check_readonly_fields(self, obj): """ Check that readonly_fields refers to proper attribute or field. """ if obj.readonly_fields == (): return [] elif not isinstance(obj.readonly_fields, (list, tuple)): return must_be('a list or tuple', option='readonly_fields', obj=obj, id='admin.E034') else: return list(chain(*[ self._check_readonly_fields_item(obj, obj.model, field_name, "readonly_fields[%d]" % index) for index, field_name in enumerate(obj.readonly_fields) ])) def _check_readonly_fields_item(self, obj, model, field_name, label): if callable(field_name): return [] elif hasattr(obj, field_name): return [] elif hasattr(model, field_name): return [] else: try: model._meta.get_field(field_name) except FieldDoesNotExist: return [ checks.Error( "The value of '%s' is not a callable, an attribute of '%s', or an attribute of '%s.%s'." % ( label, obj.__class__.__name__, model._meta.app_label, model._meta.object_name ), obj=obj.__class__, id='admin.E035', ) ] else: return [] class ModelAdminChecks(BaseModelAdminChecks): def check(self, admin_obj, **kwargs): errors = super(ModelAdminChecks, self).check(admin_obj) errors.extend(self._check_save_as(admin_obj)) errors.extend(self._check_save_on_top(admin_obj)) errors.extend(self._check_inlines(admin_obj)) errors.extend(self._check_list_display(admin_obj)) errors.extend(self._check_list_display_links(admin_obj)) errors.extend(self._check_list_filter(admin_obj)) errors.extend(self._check_list_select_related(admin_obj)) errors.extend(self._check_list_per_page(admin_obj)) errors.extend(self._check_list_max_show_all(admin_obj)) errors.extend(self._check_list_editable(admin_obj)) errors.extend(self._check_search_fields(admin_obj)) errors.extend(self._check_date_hierarchy(admin_obj)) return errors def _check_save_as(self, obj): """ Check save_as is a boolean. """ if not isinstance(obj.save_as, bool): return must_be('a boolean', option='save_as', obj=obj, id='admin.E101') else: return [] def _check_save_on_top(self, obj): """ Check save_on_top is a boolean. """ if not isinstance(obj.save_on_top, bool): return must_be('a boolean', option='save_on_top', obj=obj, id='admin.E102') else: return [] def _check_inlines(self, obj): """ Check all inline model admin classes. """ if not isinstance(obj.inlines, (list, tuple)): return must_be('a list or tuple', option='inlines', obj=obj, id='admin.E103') else: return list(chain(*[ self._check_inlines_item(obj, obj.model, item, "inlines[%d]" % index) for index, item in enumerate(obj.inlines) ])) def _check_inlines_item(self, obj, model, inline, label): """ Check one inline model admin. """ inline_label = '.'.join([inline.__module__, inline.__name__]) from django.contrib.admin.options import InlineModelAdmin if not issubclass(inline, InlineModelAdmin): return [ checks.Error( "'%s' must inherit from 'InlineModelAdmin'." % inline_label, obj=obj.__class__, id='admin.E104', ) ] elif not inline.model: return [ checks.Error( "'%s' must have a 'model' attribute." % inline_label, obj=obj.__class__, id='admin.E105', ) ] elif not issubclass(inline.model, models.Model): return must_be('a Model', option='%s.model' % inline_label, obj=obj, id='admin.E106') else: return inline(model, obj.admin_site).check() def _check_list_display(self, obj): """ Check that list_display only contains fields or usable attributes. """ if not isinstance(obj.list_display, (list, tuple)): return must_be('a list or tuple', option='list_display', obj=obj, id='admin.E107') else: return list(chain(*[ self._check_list_display_item(obj, obj.model, item, "list_display[%d]" % index) for index, item in enumerate(obj.list_display) ])) def _check_list_display_item(self, obj, model, item, label): if callable(item): return [] elif hasattr(obj, item): return [] elif hasattr(model, item): # getattr(model, item) could be an X_RelatedObjectsDescriptor try: field = model._meta.get_field(item) except FieldDoesNotExist: try: field = getattr(model, item) except AttributeError: field = None if field is None: return [ checks.Error( "The value of '%s' refers to '%s', which is not a " "callable, an attribute of '%s', or an attribute or method on '%s.%s'." % ( label, item, obj.__class__.__name__, model._meta.app_label, model._meta.object_name ), obj=obj.__class__, id='admin.E108', ) ] elif isinstance(field, models.ManyToManyField): return [ checks.Error( "The value of '%s' must not be a ManyToManyField." % label, obj=obj.__class__, id='admin.E109', ) ] else: return [] else: try: model._meta.get_field(item) except FieldDoesNotExist: return [ # This is a deliberate repeat of E108; there's more than one path # required to test this condition. checks.Error( "The value of '%s' refers to '%s', which is not a callable, " "an attribute of '%s', or an attribute or method on '%s.%s'." % ( label, item, obj.__class__.__name__, model._meta.app_label, model._meta.object_name ), obj=obj.__class__, id='admin.E108', ) ] else: return [] def _check_list_display_links(self, obj): """ Check that list_display_links is a unique subset of list_display. """ if obj.list_display_links is None: return [] elif not isinstance(obj.list_display_links, (list, tuple)): return must_be('a list, a tuple, or None', option='list_display_links', obj=obj, id='admin.E110') else: return list(chain(*[ self._check_list_display_links_item(obj, field_name, "list_display_links[%d]" % index) for index, field_name in enumerate(obj.list_display_links) ])) def _check_list_display_links_item(self, obj, field_name, label): if field_name not in obj.list_display: return [ checks.Error( "The value of '%s' refers to '%s', which is not defined in 'list_display'." % ( label, field_name ), obj=obj.__class__, id='admin.E111', ) ] else: return [] def _check_list_filter(self, obj): if not isinstance(obj.list_filter, (list, tuple)): return must_be('a list or tuple', option='list_filter', obj=obj, id='admin.E112') else: return list(chain(*[ self._check_list_filter_item(obj, obj.model, item, "list_filter[%d]" % index) for index, item in enumerate(obj.list_filter) ])) def _check_list_filter_item(self, obj, model, item, label): """ Check one item of `list_filter`, i.e. check if it is one of three options: 1. 'field' -- a basic field filter, possibly w/ relationships (e.g. 'field__rel') 2. ('field', SomeFieldListFilter) - a field-based list filter class 3. SomeListFilter - a non-field list filter class """ from django.contrib.admin import ListFilter, FieldListFilter if callable(item) and not isinstance(item, models.Field): # If item is option 3, it should be a ListFilter... if not issubclass(item, ListFilter): return must_inherit_from(parent='ListFilter', option=label, obj=obj, id='admin.E113') # ... but not a FieldListFilter. elif issubclass(item, FieldListFilter): return [ checks.Error( "The value of '%s' must not inherit from 'FieldListFilter'." % label, obj=obj.__class__, id='admin.E114', ) ] else: return [] elif isinstance(item, (tuple, list)): # item is option #2 field, list_filter_class = item if not issubclass(list_filter_class, FieldListFilter): return must_inherit_from(parent='FieldListFilter', option='%s[1]' % label, obj=obj, id='admin.E115') else: return [] else: # item is option #1 field = item # Validate the field string try: get_fields_from_path(model, field) except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of '%s' refers to '%s', which does not refer to a Field." % (label, field), obj=obj.__class__, id='admin.E116', ) ] else: return [] def _check_list_select_related(self, obj): """ Check that list_select_related is a boolean, a list or a tuple. """ if not isinstance(obj.list_select_related, (bool, list, tuple)): return must_be('a boolean, tuple or list', option='list_select_related', obj=obj, id='admin.E117') else: return [] def _check_list_per_page(self, obj): """ Check that list_per_page is an integer. """ if not isinstance(obj.list_per_page, int): return must_be('an integer', option='list_per_page', obj=obj, id='admin.E118') else: return [] def _check_list_max_show_all(self, obj): """ Check that list_max_show_all is an integer. """ if not isinstance(obj.list_max_show_all, int): return must_be('an integer', option='list_max_show_all', obj=obj, id='admin.E119') else: return [] def _check_list_editable(self, obj): """ Check that list_editable is a sequence of editable fields from list_display without first element. """ if not isinstance(obj.list_editable, (list, tuple)): return must_be('a list or tuple', option='list_editable', obj=obj, id='admin.E120') else: return list(chain(*[ self._check_list_editable_item(obj, obj.model, item, "list_editable[%d]" % index) for index, item in enumerate(obj.list_editable) ])) def _check_list_editable_item(self, obj, model, field_name, label): try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E121') else: if field_name not in obj.list_display: return [ checks.Error( "The value of '%s' refers to '%s', which is not " "contained in 'list_display'." % (label, field_name), obj=obj.__class__, id='admin.E122', ) ] elif obj.list_display_links and field_name in obj.list_display_links: return [ checks.Error( "The value of '%s' cannot be in both 'list_editable' and 'list_display_links'." % field_name, obj=obj.__class__, id='admin.E123', ) ] # If list_display[0] is in list_editable, check that # list_display_links is set. See #22792 and #26229 for use cases. elif (obj.list_display[0] == field_name and not obj.list_display_links and obj.list_display_links is not None): return [ checks.Error( "The value of '%s' refers to the first field in 'list_display' ('%s'), " "which cannot be used unless 'list_display_links' is set." % ( label, obj.list_display[0] ), obj=obj.__class__, id='admin.E124', ) ] elif not field.editable: return [ checks.Error( "The value of '%s' refers to '%s', which is not editable through the admin." % ( label, field_name ), obj=obj.__class__, id='admin.E125', ) ] else: return [] def _check_search_fields(self, obj): """ Check search_fields is a sequence. """ if not isinstance(obj.search_fields, (list, tuple)): return must_be('a list or tuple', option='search_fields', obj=obj, id='admin.E126') else: return [] def _check_date_hierarchy(self, obj): """ Check that date_hierarchy refers to DateField or DateTimeField. """ if obj.date_hierarchy is None: return [] else: try: field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of 'date_hierarchy' refers to '%s', which " "does not refer to a Field." % obj.date_hierarchy, obj=obj.__class__, id='admin.E127', ) ] else: if not isinstance(field, (models.DateField, models.DateTimeField)): return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128') else: return [] class InlineModelAdminChecks(BaseModelAdminChecks): def check(self, inline_obj, **kwargs): errors = super(InlineModelAdminChecks, self).check(inline_obj) parent_model = inline_obj.parent_model errors.extend(self._check_relation(inline_obj, parent_model)) errors.extend(self._check_exclude_of_parent_model(inline_obj, parent_model)) errors.extend(self._check_extra(inline_obj)) errors.extend(self._check_max_num(inline_obj)) errors.extend(self._check_min_num(inline_obj)) errors.extend(self._check_formset(inline_obj)) return errors def _check_exclude_of_parent_model(self, obj, parent_model): # Do not perform more specific checks if the base checks result in an # error. errors = super(InlineModelAdminChecks, self)._check_exclude(obj) if errors: return [] # Skip if `fk_name` is invalid. if self._check_relation(obj, parent_model): return [] if obj.exclude is None: return [] fk = _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name) if fk.name in obj.exclude: return [ checks.Error( "Cannot exclude the field '%s', because it is the foreign key " "to the parent model '%s.%s'." % ( fk.name, parent_model._meta.app_label, parent_model._meta.object_name ), obj=obj.__class__, id='admin.E201', ) ] else: return [] def _check_relation(self, obj, parent_model): try: _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name) except ValueError as e: return [checks.Error(e.args[0], obj=obj.__class__, id='admin.E202')] else: return [] def _check_extra(self, obj): """ Check that extra is an integer. """ if not isinstance(obj.extra, int): return must_be('an integer', option='extra', obj=obj, id='admin.E203') else: return [] def _check_max_num(self, obj): """ Check that max_num is an integer. """ if obj.max_num is None: return [] elif not isinstance(obj.max_num, int): return must_be('an integer', option='max_num', obj=obj, id='admin.E204') else: return [] def _check_min_num(self, obj): """ Check that min_num is an integer. """ if obj.min_num is None: return [] elif not isinstance(obj.min_num, int): return must_be('an integer', option='min_num', obj=obj, id='admin.E205') else: return [] def _check_formset(self, obj): """ Check formset is a subclass of BaseModelFormSet. """ if not issubclass(obj.formset, BaseModelFormSet): return must_inherit_from(parent='BaseModelFormSet', option='formset', obj=obj, id='admin.E206') else: return [] def must_be(type, option, obj, id): return [ checks.Error( "The value of '%s' must be %s." % (option, type), obj=obj.__class__, id=id, ), ] def must_inherit_from(parent, option, obj, id): return [ checks.Error( "The value of '%s' must inherit from '%s'." % (option, parent), obj=obj.__class__, id=id, ), ] def refer_to_missing_field(field, option, model, obj, id): return [ checks.Error( "The value of '%s' refers to '%s', which is not an attribute of '%s.%s'." % ( option, field, model._meta.app_label, model._meta.object_name ), obj=obj.__class__, id=id, ), ]
HybridF5/tempest
refs/heads/master
tempest/common/fixed_network.py
6
# 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 oslo_log import log as logging from tempest import exceptions from tempest.lib.common.utils import misc as misc_utils LOG = logging.getLogger(__name__) def get_network_from_name(name, compute_networks_client): """Get a full network dict from just a network name :param str name: the name of the network to use :param NetworksClient compute_networks_client: The network client object to use for making the network lists api request :return: The full dictionary for the network in question :rtype: dict :raises InvalidTestResource: If the name provided is invalid, the networks list returns a 404, there are no found networks, or the found network is invalid """ caller = misc_utils.find_test_caller() if not name: raise exceptions.InvalidTestResource(type='network', name=name) networks = compute_networks_client.list_networks()['networks'] networks = [n for n in networks if n['label'] == name] # Check that a network exists, else raise an InvalidConfigurationException if len(networks) == 1: network = sorted(networks)[0] elif len(networks) > 1: msg = ("Network with name: %s had multiple matching networks in the " "list response: %s\n Unable to specify a single network" % ( name, networks)) if caller: msg = '(%s) %s' % (caller, msg) LOG.warning(msg) raise exceptions.InvalidTestResource(type='network', name=name) else: msg = "Network with name: %s not found" % name if caller: msg = '(%s) %s' % (caller, msg) LOG.warning(msg) raise exceptions.InvalidTestResource(type='network', name=name) # To be consistent between neutron and nova network always use name even # if label is used in the api response. If neither is present than then # the returned network is invalid. name = network.get('name') or network.get('label') if not name: msg = "Network found from list doesn't contain a valid name or label" if caller: msg = '(%s) %s' % (caller, msg) LOG.warning(msg) raise exceptions.InvalidTestResource(type='network', name=name) network['name'] = name return network def get_tenant_network(creds_provider, compute_networks_client, shared_network_name): """Get a network usable by the primary tenant :param creds_provider: instance of credential provider :param compute_networks_client: compute network client. We want to have the compute network client so we can have use a common approach for both neutron and nova-network cases. If this is not an admin network client, set_network_kwargs might fail in case fixed_network_name is the network to be used, and it's not visible to the tenant :param shared_network_name: name of the shared network to be used if no tenant network is available in the creds provider :returns: a dict with 'id' and 'name' of the network """ caller = misc_utils.find_test_caller() net_creds = creds_provider.get_primary_creds() network = getattr(net_creds, 'network', None) if not network or not network.get('name'): if shared_network_name: msg = ('No valid network provided or created, defaulting to ' 'fixed_network_name') if caller: msg = '(%s) %s' % (caller, msg) LOG.debug(msg) try: network = get_network_from_name(shared_network_name, compute_networks_client) except exceptions.InvalidTestResource: network = {} msg = ('Found network %s available for tenant' % network) if caller: msg = '(%s) %s' % (caller, msg) LOG.info(msg) return network def set_networks_kwarg(network, kwargs=None): """Set 'networks' kwargs for a server create if missing :param network: dict of network to be used with 'id' and 'name' :param kwargs: server create kwargs to be enhanced :return: new dict of kwargs updated to include networks """ params = copy.copy(kwargs) or {} if kwargs and 'networks' in kwargs: return params if network: if 'id' in network.keys(): params.update({"networks": [{'uuid': network['id']}]}) else: LOG.warning('The provided network dict: %s was invalid and did ' 'not contain an id' % network) return params
kytvi2p/Sigil
refs/heads/master
3rdparty/python/Lib/imghdr.py
88
"""Recognize image file formats based on their first few bytes.""" __all__ = ["what"] #-------------------------# # Recognize image headers # #-------------------------# def what(file, h=None): f = None try: if h is None: if isinstance(file, str): f = open(file, 'rb') h = f.read(32) else: location = file.tell() h = file.read(32) file.seek(location) for tf in tests: res = tf(h, f) if res: return res finally: if f: f.close() return None #---------------------------------# # Subroutines per image file type # #---------------------------------# tests = [] def test_jpeg(h, f): """JPEG data in JFIF or Exif format""" if h[6:10] in (b'JFIF', b'Exif'): return 'jpeg' tests.append(test_jpeg) def test_png(h, f): if h.startswith(b'\211PNG\r\n\032\n'): return 'png' tests.append(test_png) def test_gif(h, f): """GIF ('87 and '89 variants)""" if h[:6] in (b'GIF87a', b'GIF89a'): return 'gif' tests.append(test_gif) def test_tiff(h, f): """TIFF (can be in Motorola or Intel byte order)""" if h[:2] in (b'MM', b'II'): return 'tiff' tests.append(test_tiff) def test_rgb(h, f): """SGI image library""" if h.startswith(b'\001\332'): return 'rgb' tests.append(test_rgb) def test_pbm(h, f): """PBM (portable bitmap)""" if len(h) >= 3 and \ h[0] == ord(b'P') and h[1] in b'14' and h[2] in b' \t\n\r': return 'pbm' tests.append(test_pbm) def test_pgm(h, f): """PGM (portable graymap)""" if len(h) >= 3 and \ h[0] == ord(b'P') and h[1] in b'25' and h[2] in b' \t\n\r': return 'pgm' tests.append(test_pgm) def test_ppm(h, f): """PPM (portable pixmap)""" if len(h) >= 3 and \ h[0] == ord(b'P') and h[1] in b'36' and h[2] in b' \t\n\r': return 'ppm' tests.append(test_ppm) def test_rast(h, f): """Sun raster file""" if h.startswith(b'\x59\xA6\x6A\x95'): return 'rast' tests.append(test_rast) def test_xbm(h, f): """X bitmap (X10 or X11)""" if h.startswith(b'#define '): return 'xbm' tests.append(test_xbm) def test_bmp(h, f): if h.startswith(b'BM'): return 'bmp' tests.append(test_bmp) #--------------------# # Small test program # #--------------------# def test(): import sys recursive = 0 if sys.argv[1:] and sys.argv[1] == '-r': del sys.argv[1:2] recursive = 1 try: if sys.argv[1:]: testall(sys.argv[1:], recursive, 1) else: testall(['.'], recursive, 1) except KeyboardInterrupt: sys.stderr.write('\n[Interrupted]\n') sys.exit(1) def testall(list, recursive, toplevel): import sys import os for filename in list: if os.path.isdir(filename): print(filename + '/:', end=' ') if recursive or toplevel: print('recursing down:') import glob names = glob.glob(os.path.join(filename, '*')) testall(names, recursive, 0) else: print('*** directory (use -r) ***') else: print(filename + ':', end=' ') sys.stdout.flush() try: print(what(filename)) except OSError: print('*** not found ***') if __name__ == '__main__': test()
wwj718/ANALYSE
refs/heads/master
common/lib/xmodule/xmodule/hidden_module.py
94
from xmodule.x_module import XModule from xmodule.raw_module import RawDescriptor class HiddenModule(XModule): def get_html(self): if self.system.user_is_staff: return u"ERROR: This module is unknown--students will not see it at all" else: return u"" class HiddenDescriptor(RawDescriptor): module_class = HiddenModule
craisins/nascarbot
refs/heads/master
plugins/wikipedia.py
6
'''Searches wikipedia and returns first sentence of article Scaevolus 2009''' import re from util import hook, http api_prefix = "http://en.wikipedia.org/w/api.php" search_url = api_prefix + "?action=opensearch&format=xml" paren_re = re.compile('\s*\(.*\)$') @hook.command('w') @hook.command def wiki(inp): '''.w/.wiki <phrase> -- gets first sentence of wikipedia ''' \ '''article on <phrase>''' x = http.get_xml(search_url, search=inp) ns = '{http://opensearch.org/searchsuggest2}' items = x.findall(ns + 'Section/' + ns + 'Item') if items == []: if x.find('error') is not None: return 'error: %(code)s: %(info)s' % x.find('error').attrib else: return 'no results found' def extract(item): return [item.find(ns + x).text for x in ('Text', 'Description', 'Url')] title, desc, url = extract(items[0]) if 'may refer to' in desc: title, desc, url = extract(items[1]) title = paren_re.sub('', title) if title.lower() not in desc.lower(): desc = title + desc desc = re.sub('\s+', ' ', desc).strip() # remove excess spaces if len(desc) > 300: desc = desc[:300] + '...' return '%s -- %s' % (desc, http.quote(http.unquote(url), ':/'))
MichaelNedzelsky/intellij-community
refs/heads/master
python/testData/completion/matMul.py
79
class C: def __matmul<caret>
arthru/OpenUpgrade
refs/heads/master
addons/marketing_campaign_crm_demo/__openerp__.py
119
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Marketing Campaign - Demo', 'version': '1.0', 'depends': ['marketing_campaign', 'crm', ], 'author': 'OpenERP SA', 'category': 'Marketing', 'description': """ Demo data for the module marketing_campaign. ============================================ Creates demo data like leads, campaigns and segments for the module marketing_campaign. """, 'website': 'http://www.openerp.com', 'data': [], 'demo': ['marketing_campaign_demo.xml'], 'installable': True, 'auto_install': False, 'images': ['images/campaigns.jpeg','images/email_templates.jpeg'], } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
vgrem/Office365-REST-Python-Client
refs/heads/master
office365/calendar/calendar_group.py
1
from office365.calendar.calendar_collection import CalendarCollection from office365.entity import Entity from office365.runtime.resource_path import ResourcePath class CalendarGroup(Entity): """ A group of user calendars. """ @property def calendars(self): """The calendars in the calendar group. Navigation property. Read-only. Nullable.""" return self.properties.get('calendars', CalendarCollection(self.context, ResourcePath("calendars", self.resource_path)))
botchat/sampleGroupChat
refs/heads/master
chatting/tests.py
24123
from django.test import TestCase # Create your tests here.
savoirfairelinux/OpenUpgrade
refs/heads/master
addons/mail/tests/test_message_read.py
44
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.addons.mail.tests.common import TestMail class test_mail_access_rights(TestMail): def test_00_message_read(self): """ Tests for message_read and expandables. """ cr, uid, user_admin, user_raoul, group_pigs = self.cr, self.uid, self.user_admin, self.user_raoul, self.group_pigs self.mail_group.message_subscribe_users(cr, uid, [group_pigs.id], [user_raoul.id]) pigs_domain = [('model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id)] # Data: create a discussion in Pigs (3 threads, with respectively 0, 4 and 4 answers) msg_id0 = self.group_pigs.message_post(body='0', subtype='mt_comment') msg_id1 = self.group_pigs.message_post(body='1', subtype='mt_comment') msg_id2 = self.group_pigs.message_post(body='2', subtype='mt_comment') msg_id3 = self.group_pigs.message_post(body='1-1', subtype='mt_comment', parent_id=msg_id1) msg_id4 = self.group_pigs.message_post(body='2-1', subtype='mt_comment', parent_id=msg_id2) msg_id5 = self.group_pigs.message_post(body='1-2', subtype='mt_comment', parent_id=msg_id1) msg_id6 = self.group_pigs.message_post(body='2-2', subtype='mt_comment', parent_id=msg_id2) msg_id7 = self.group_pigs.message_post(body='1-1-1', subtype='mt_comment', parent_id=msg_id3) msg_id8 = self.group_pigs.message_post(body='2-1-1', subtype='mt_comment', parent_id=msg_id4) msg_id9 = self.group_pigs.message_post(body='1-1-1', subtype='mt_comment', parent_id=msg_id3) msg_id10 = self.group_pigs.message_post(body='2-1-1', subtype='mt_comment', parent_id=msg_id4) msg_ids = [msg_id10, msg_id9, msg_id8, msg_id7, msg_id6, msg_id5, msg_id4, msg_id3, msg_id2, msg_id1, msg_id0] ordered_msg_ids = [msg_id2, msg_id4, msg_id6, msg_id8, msg_id10, msg_id1, msg_id3, msg_id5, msg_id7, msg_id9, msg_id0] # Test: raoul received notifications raoul_notification_ids = self.mail_notification.search(cr, user_raoul.id, [('read', '=', False), ('message_id', 'in', msg_ids), ('partner_id', '=', user_raoul.partner_id.id)]) self.assertEqual(len(raoul_notification_ids), 11, 'message_post: wrong number of produced notifications') # Test: read some specific ids read_msg_list = self.mail_message.message_read(cr, user_raoul.id, ids=msg_ids[2:4], domain=[('body', 'like', 'dummy')], context={'mail_read_set_read': True}) read_msg_ids = [msg.get('id') for msg in read_msg_list] self.assertEqual(msg_ids[2:4], read_msg_ids, 'message_read with direct ids should read only the requested ids') # Test: read messages of Pigs through a domain, being thread or not threaded read_msg_list = self.mail_message.message_read(cr, user_raoul.id, domain=pigs_domain, limit=200) read_msg_ids = [msg.get('id') for msg in read_msg_list] self.assertEqual(msg_ids, read_msg_ids, 'message_read flat with domain on Pigs should equal all messages of Pigs') read_msg_list = self.mail_message.message_read(cr, user_raoul.id, domain=pigs_domain, limit=200, thread_level=1) read_msg_ids = [msg.get('id') for msg in read_msg_list] self.assertEqual(ordered_msg_ids, read_msg_ids, 'message_read threaded with domain on Pigs should equal all messages of Pigs, and sort them with newer thread first, last message last in thread') # ---------------------------------------- # CASE1: message_read with domain, threaded # We simulate an entire flow, using the expandables to test them # ---------------------------------------- # Do: read last message, threaded read_msg_list = self.mail_message.message_read(cr, uid, domain=pigs_domain, limit=1, thread_level=1) read_msg_ids = [msg.get('id') for msg in read_msg_list if msg.get('type') != 'expandable'] # TDE TODO: test expandables order type_list = map(lambda item: item.get('type'), read_msg_list) # Test: structure content, ancestor is added to the read messages, ordered by id, ancestor is set, 2 expandables self.assertEqual(len(read_msg_list), 4, 'message_read on last Pigs message should return 2 messages and 2 expandables') self.assertEqual(set([msg_id2, msg_id10]), set(read_msg_ids), 'message_read on the last Pigs message should also get its parent') self.assertEqual(read_msg_list[1].get('parent_id'), read_msg_list[0].get('id'), 'message_read should set the ancestor to the thread header') # Data: get expandables new_threads_exp, new_msg_exp = None, None for msg in read_msg_list: if msg.get('type') == 'expandable' and msg.get('nb_messages') == -1 and msg.get('max_limit'): new_threads_exp = msg elif msg.get('type') == 'expandable': new_msg_exp = msg # Do: fetch new messages in first thread, domain from expandable self.assertIsNotNone(new_msg_exp, 'message_read on last Pigs message should have returned a new messages expandable') domain = new_msg_exp.get('domain', []) # Test: expandable, conditions in domain self.assertIn(('id', 'child_of', msg_id2), domain, 'new messages expandable domain should contain a child_of condition') self.assertIn(('id', '>=', msg_id4), domain, 'new messages expandable domain should contain an id greater than condition') self.assertIn(('id', '<=', msg_id8), domain, 'new messages expandable domain should contain an id less than condition') self.assertEqual(new_msg_exp.get('parent_id'), msg_id2, 'new messages expandable should have parent_id set to the thread header') # Do: message_read with domain, thread_level=0, parent_id=msg_id2 (should be imposed by JS), 2 messages read_msg_list = self.mail_message.message_read(cr, uid, domain=domain, limit=2, thread_level=0, parent_id=msg_id2) read_msg_ids = [msg.get('id') for msg in read_msg_list if msg.get('type') != 'expandable'] new_msg_exp = [msg for msg in read_msg_list if msg.get('type') == 'expandable'][0] # Test: structure content, 2 messages and 1 thread expandable self.assertEqual(len(read_msg_list), 3, 'message_read in Pigs thread should return 2 messages and 1 expandables') self.assertEqual(set([msg_id6, msg_id8]), set(read_msg_ids), 'message_read in Pigs thread should return 2 more previous messages in thread') # Do: read the last message read_msg_list = self.mail_message.message_read(cr, uid, domain=new_msg_exp.get('domain'), limit=2, thread_level=0, parent_id=msg_id2) read_msg_ids = [msg.get('id') for msg in read_msg_list if msg.get('type') != 'expandable'] # Test: structure content, 1 message self.assertEqual(len(read_msg_list), 1, 'message_read in Pigs thread should return 1 message') self.assertEqual(set([msg_id4]), set(read_msg_ids), 'message_read in Pigs thread should return the last message in thread') # Do: fetch a new thread, domain from expandable self.assertIsNotNone(new_threads_exp, 'message_read on last Pigs message should have returned a new threads expandable') domain = new_threads_exp.get('domain', []) # Test: expandable, conditions in domain for condition in pigs_domain: self.assertIn(condition, domain, 'new threads expandable domain should contain the message_read domain parameter') self.assertFalse(new_threads_exp.get('parent_id'), 'new threads expandable should not have an parent_id') # Do: message_read with domain, thread_level=1 (should be imposed by JS) read_msg_list = self.mail_message.message_read(cr, uid, domain=domain, limit=1, thread_level=1) read_msg_ids = [msg.get('id') for msg in read_msg_list if msg.get('type') != 'expandable'] # Test: structure content, ancestor is added to the read messages, ordered by id, ancestor is set, 2 expandables self.assertEqual(len(read_msg_list), 4, 'message_read on Pigs should return 2 messages and 2 expandables') self.assertEqual(set([msg_id1, msg_id9]), set(read_msg_ids), 'message_read on a Pigs message should also get its parent') self.assertEqual(read_msg_list[1].get('parent_id'), read_msg_list[0].get('id'), 'message_read should set the ancestor to the thread header') # Data: get expandables new_threads_exp, new_msg_exp = None, None for msg in read_msg_list: if msg.get('type') == 'expandable' and msg.get('nb_messages') == -1 and msg.get('max_limit'): new_threads_exp = msg elif msg.get('type') == 'expandable': new_msg_exp = msg # Do: fetch new messages in second thread, domain from expandable self.assertIsNotNone(new_msg_exp, 'message_read on Pigs message should have returned a new messages expandable') domain = new_msg_exp.get('domain', []) # Test: expandable, conditions in domain self.assertIn(('id', 'child_of', msg_id1), domain, 'new messages expandable domain should contain a child_of condition') self.assertIn(('id', '>=', msg_id3), domain, 'new messages expandable domain should contain an id greater than condition') self.assertIn(('id', '<=', msg_id7), domain, 'new messages expandable domain should contain an id less than condition') self.assertEqual(new_msg_exp.get('parent_id'), msg_id1, 'new messages expandable should have ancestor_id set to the thread header') # Do: message_read with domain, thread_level=0, parent_id=msg_id1 (should be imposed by JS) read_msg_list = self.mail_message.message_read(cr, uid, domain=domain, limit=200, thread_level=0, parent_id=msg_id1) read_msg_ids = [msg.get('id') for msg in read_msg_list if msg.get('type') != 'expandable'] # Test: other message in thread have been fetch self.assertEqual(set([msg_id3, msg_id5, msg_id7]), set(read_msg_ids), 'message_read on the last Pigs message should also get its parent') # Test: fetch a new thread, domain from expandable self.assertIsNotNone(new_threads_exp, 'message_read should have returned a new threads expandable') domain = new_threads_exp.get('domain', []) # Test: expandable, conditions in domain for condition in pigs_domain: self.assertIn(condition, domain, 'general expandable domain should contain the message_read domain parameter') # Do: message_read with domain, thread_level=1 (should be imposed by JS) read_msg_list = self.mail_message.message_read(cr, uid, domain=domain, limit=1, thread_level=1) read_msg_ids = [msg.get('id') for msg in read_msg_list if msg.get('type') != 'expandable'] # Test: structure content, ancestor is added to the read messages, ordered by id, ancestor is set, 2 expandables self.assertEqual(len(read_msg_list), 1, 'message_read on Pigs should return 1 message because everything else has been fetched') self.assertEqual([msg_id0], read_msg_ids, 'message_read after 2 More should return only 1 last message') # ---------------------------------------- # CASE2: message_read with domain, flat # ---------------------------------------- # Do: read 2 lasts message, flat read_msg_list = self.mail_message.message_read(cr, uid, domain=pigs_domain, limit=2, thread_level=0) read_msg_ids = [msg.get('id') for msg in read_msg_list if msg.get('type') != 'expandable'] # Test: structure content, ancestor is added to the read messages, ordered by id, ancestor is not set, 1 expandable self.assertEqual(len(read_msg_list), 3, 'message_read on last Pigs message should return 2 messages and 1 expandable') self.assertEqual(set([msg_id9, msg_id10]), set(read_msg_ids), 'message_read flat on Pigs last messages should only return those messages') self.assertFalse(read_msg_list[0].get('parent_id'), 'message_read flat should set the ancestor as False') self.assertFalse(read_msg_list[1].get('parent_id'), 'message_read flat should set the ancestor as False') # Data: get expandables new_threads_exp, new_msg_exp = None, None for msg in read_msg_list: if msg.get('type') == 'expandable' and msg.get('nb_messages') == -1 and msg.get('max_limit'): new_threads_exp = msg # Do: fetch new messages, domain from expandable self.assertIsNotNone(new_threads_exp, 'message_read flat on the 2 last Pigs messages should have returns a new threads expandable') domain = new_threads_exp.get('domain', []) # Test: expandable, conditions in domain for condition in pigs_domain: self.assertIn(condition, domain, 'new threads expandable domain should contain the message_read domain parameter') # Do: message_read with domain, thread_level=0 (should be imposed by JS) read_msg_list = self.mail_message.message_read(cr, uid, domain=domain, limit=20, thread_level=0) read_msg_ids = [msg.get('id') for msg in read_msg_list if msg.get('type') != 'expandable'] # Test: structure content, ancestor is added to the read messages, ordered by id, ancestor is set, 2 expandables self.assertEqual(len(read_msg_list), 9, 'message_read on Pigs should return 9 messages and 0 expandable') self.assertEqual([msg_id8, msg_id7, msg_id6, msg_id5, msg_id4, msg_id3, msg_id2, msg_id1, msg_id0], read_msg_ids, 'message_read, More on flat, should return all remaning messages')
SnappleCap/oh-mainline
refs/heads/master
vendor/packages/requests/requests/models.py
410
# -*- coding: utf-8 -*- """ requests.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power Requests. """ import collections import datetime from io import BytesIO, UnsupportedOperation from .hooks import default_hooks from .structures import CaseInsensitiveDict from .auth import HTTPBasicAuth from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar from .packages.urllib3.fields import RequestField from .packages.urllib3.filepost import encode_multipart_formdata from .packages.urllib3.util import parse_url from .packages.urllib3.exceptions import ( DecodeError, ReadTimeoutError, ProtocolError, LocationParseError) from .exceptions import ( HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError, ContentDecodingError, ConnectionError, StreamConsumedError) from .utils import ( guess_filename, get_auth_from_url, requote_uri, stream_decode_response_unicode, to_key_val_list, parse_header_links, iter_slices, guess_json_utf, super_len, to_native_string) from .compat import ( cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO, is_py2, chardet, json, builtin_str, basestring) from .status_codes import codes #: The set of HTTP status codes that indicate an automatically #: processable redirect. REDIRECT_STATI = ( codes.moved, # 301 codes.found, # 302 codes.other, # 303 codes.temporary_redirect, # 307 codes.permanent_redirect, # 308 ) DEFAULT_REDIRECT_LIMIT = 30 CONTENT_CHUNK_SIZE = 10 * 1024 ITER_CHUNK_SIZE = 512 json_dumps = json.dumps class RequestEncodingMixin(object): @property def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url) @staticmethod def _encode_params(data): """Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if isinstance(data, (str, bytes)): return data elif hasattr(data, 'read'): return data elif hasattr(data, '__iter__'): result = [] for k, vs in to_key_val_list(data): if isinstance(vs, basestring) or not hasattr(vs, '__iter__'): vs = [vs] for v in vs: if v is not None: result.append( (k.encode('utf-8') if isinstance(k, str) else k, v.encode('utf-8') if isinstance(v, str) else v)) return urlencode(result, doseq=True) else: return data @staticmethod def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if (not files): raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, '__iter__'): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( (field.decode('utf-8') if isinstance(field, bytes) else field, v.encode('utf-8') if isinstance(v, str) else v)) for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp else: fdata = fp.read() rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type class RequestHooksMixin(object): def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks: raise ValueError('Unsupported event specified, with event name "%s"' % (event)) if isinstance(hook, collections.Callable): self.hooks[event].append(hook) elif hasattr(hook, '__iter__'): self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False class Request(RequestHooksMixin): """A user-created :class:`Request <Request>` object. Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server. :param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place. :param json: json for the body to attach to the request (if data is not specified). :param params: dictionary of URL parameters to append to the URL. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage. Usage:: >>> import requests >>> req = requests.Request('GET', 'http://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]> """ def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies def __repr__(self): return '<Request [%s]>' % (self.method) def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): """The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server. Generated from either a :class:`Request <Request>` object or manually. Usage:: >>> import requests >>> req = requests.Request('GET', 'http://httpbin.org/get') >>> r = req.prepare() <PreparedRequest [GET]> >>> s = requests.Session() >>> s.send(r) <Response [200]> """ def __init__(self): #: HTTP verb to send to the server. self.method = None #: HTTP URL to send the request to. self.url = None #: dictionary of HTTP headers. self.headers = None # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called self._cookies = None #: request body to send to the server. self.body = None #: dictionary of callback hooks, for internal usage. self.hooks = default_hooks() def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): """Prepares the entire request with the given parameters.""" self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks) def __repr__(self): return '<PreparedRequest [%s]>' % (self.method) def copy(self): p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() if self.headers is not None else None p._cookies = _copy_cookie_jar(self._cookies) p.body = self.body p.hooks = self.hooks return p def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = self.method.upper() def prepare_url(self, url, params): """Prepares the given HTTP URL.""" #: Accept objects that have string representations. #: We're unable to blindy call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/kennethreitz/requests/pull/2238 if isinstance(url, bytes): url = url.decode('utf8') else: url = unicode(url) if is_py2 else str(url) # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ':' in url and not url.lower().startswith('http'): self.url = url return # Support for unicode domain names and paths. try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: raise MissingSchema("Invalid URL {0!r}: No schema supplied. " "Perhaps you meant http://{0}?".format( to_native_string(url, 'utf8'))) if not host: raise InvalidURL("Invalid URL %r: No host supplied" % url) # Only want to apply IDNA to the hostname try: host = host.encode('idna').decode('utf-8') except UnicodeError: raise InvalidURL('URL has an invalid label.') # Carefully reconstruct the network location netloc = auth or '' if netloc: netloc += '@' netloc += host if port: netloc += ':' + str(port) # Bare domains aren't valid URLs. if not path: path = '/' if is_py2: if isinstance(scheme, str): scheme = scheme.encode('utf-8') if isinstance(netloc, str): netloc = netloc.encode('utf-8') if isinstance(path, str): path = path.encode('utf-8') if isinstance(query, str): query = query.encode('utf-8') if isinstance(fragment, str): fragment = fragment.encode('utf-8') enc_params = self._encode_params(params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url def prepare_headers(self, headers): """Prepares the given HTTP headers.""" if headers: self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items()) else: self.headers = CaseInsensitiveDict() def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None length = None if json is not None: content_type = 'application/json' body = json_dumps(json) is_stream = all([ hasattr(data, '__iter__'), not isinstance(data, (basestring, list, tuple, dict)) ]) try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None if is_stream: body = data if files: raise NotImplementedError('Streamed bodies and files are mutually exclusive.') if length is not None: self.headers['Content-Length'] = builtin_str(length) else: self.headers['Transfer-Encoding'] = 'chunked' else: # Multi-part file uploads. if files: (body, content_type) = self._encode_files(files, data) else: if data and json is None: body = self._encode_params(data) if isinstance(data, basestring) or hasattr(data, 'read'): content_type = None else: content_type = 'application/x-www-form-urlencoded' self.prepare_content_length(body) # Add content-type if it wasn't explicitly provided. if content_type and ('content-type' not in self.headers): self.headers['Content-Type'] = content_type self.body = body def prepare_content_length(self, body): if hasattr(body, 'seek') and hasattr(body, 'tell'): body.seek(0, 2) self.headers['Content-Length'] = builtin_str(body.tell()) body.seek(0, 0) elif body is not None: l = super_len(body) if l: self.headers['Content-Length'] = builtin_str(l) elif (self.method not in ('GET', 'HEAD')) and (self.headers.get('Content-Length') is None): self.headers['Content-Length'] = '0' def prepare_auth(self, auth, url=''): """Prepares the given HTTP auth data.""" # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = HTTPBasicAuth(*auth) # Allow auth to make its changes. r = auth(self) # Update self to reflect the auth changes. self.__dict__.update(r.__dict__) # Recompute Content-Length self.prepare_content_length(self.body) def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand.""" if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers['Cookie'] = cookie_header def prepare_hooks(self, hooks): """Prepares the given hooks.""" # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: self.register_hook(event, hooks[event]) class Response(object): """The :class:`Response <Response>` object, which contains a server's response to an HTTP request. """ __attrs__ = [ '_content', 'status_code', 'headers', 'url', 'history', 'encoding', 'reason', 'cookies', 'elapsed', 'request', ] def __init__(self): super(Response, self).__init__() self._content = False self._content_consumed = False #: Integer Code of responded HTTP Status, e.g. 404 or 200. self.status_code = None #: Case-insensitive Dictionary of Response Headers. #: For example, ``headers['content-encoding']`` will return the #: value of a ``'Content-Encoding'`` response header. self.headers = CaseInsensitiveDict() #: File-like object representation of response (for advanced usage). #: Use of ``raw`` requires that ``stream=True`` be set on the request. # This requirement does not apply for use internally to Requests. self.raw = None #: Final URL location of Response. self.url = None #: Encoding to decode with when accessing r.text. self.encoding = None #: A list of :class:`Response <Response>` objects from #: the history of the Request. Any redirect responses will end #: up here. The list is sorted from the oldest to the most recent request. self.history = [] #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". self.reason = None #: A CookieJar of Cookies the server sent back. self.cookies = cookiejar_from_dict({}) #: The amount of time elapsed between sending the request #: and the arrival of the response (as a timedelta). #: This property specifically measures the time taken between sending #: the first byte of the request and finishing parsing the headers. It #: is therefore unaffected by consuming the response content or the #: value of the ``stream`` keyword argument. self.elapsed = datetime.timedelta(0) #: The :class:`PreparedRequest <PreparedRequest>` object to which this #: is a response. self.request = None def __getstate__(self): # Consume everything; accessing the content attribute makes # sure the content has been fully read. if not self._content_consumed: self.content return dict( (attr, getattr(self, attr, None)) for attr in self.__attrs__ ) def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) # pickled objects do not have .raw setattr(self, '_content_consumed', True) setattr(self, 'raw', None) def __repr__(self): return '<Response [%s]>' % (self.status_code) def __bool__(self): """Returns true if :attr:`status_code` is 'OK'.""" return self.ok def __nonzero__(self): """Returns true if :attr:`status_code` is 'OK'.""" return self.ok def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128) @property def ok(self): try: self.raise_for_status() except HTTPError: return False return True @property def is_redirect(self): """True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). """ return ('location' in self.headers and self.status_code in REDIRECT_STATI) @property def is_permanent_redirect(self): """True if this Response one of the permanant versions of redirect""" return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect)) @property def apparent_encoding(self): """The apparent encoding, provided by the chardet library""" return chardet.detect(self.content)['encoding'] def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ def generate(): try: # Special case for urllib3. try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) except AttributeError: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe. """ pending = None for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending @property def content(self): """Content of the response, in bytes.""" if self._content is False: # Read the contents. try: if self._content_consumed: raise RuntimeError( 'The content for this response was already consumed') if self.status_code == 0: self._content = None else: self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes() except AttributeError: self._content = None self._content_consumed = True # don't need to release the connection; that's been handled by urllib3 # since we exhausted the data. return self._content @property def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. """ # Try charset from content-type content = None encoding = self.encoding if not self.content: return str('') # Fallback to auto-detected encoding. if self.encoding is None: encoding = self.apparent_encoding # Decode unicode from given encoding. try: content = str(self.content, encoding, errors='replace') except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors='replace') return content def json(self, **kwargs): """Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return json.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return json.loads(self.text, **kwargs) @property def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get('link') # l = MultiDict() l = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.get('url') l[key] = link return l def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if 400 <= self.status_code < 500: http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason) elif 500 <= self.status_code < 600: http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason) if http_error_msg: raise HTTPError(http_error_msg, response=self) def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ return self.raw.release_conn()
pcu4dros/pandora-core
refs/heads/master
workspace/lib/python3.5/site-packages/werkzeug/contrib/testtools.py
4
# -*- coding: utf-8 -*- """ werkzeug.contrib.testtools ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module implements extended wrappers for simplified testing. `TestResponse` A response wrapper which adds various cached attributes for simplified assertions on various content types. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from werkzeug.utils import cached_property, import_string from werkzeug.wrappers import Response from warnings import warn warn(DeprecationWarning('werkzeug.contrib.testtools is deprecated and ' 'will be removed with Werkzeug 1.0')) class ContentAccessors(object): """ A mixin class for response objects that provides a couple of useful accessors for unittesting. """ def xml(self): """Get an etree if possible.""" if 'xml' not in self.mimetype: raise AttributeError( 'Not a XML response (Content-Type: %s)' % self.mimetype) for module in ['xml.etree.ElementTree', 'ElementTree', 'elementtree.ElementTree']: etree = import_string(module, silent=True) if etree is not None: return etree.XML(self.body) raise RuntimeError('You must have ElementTree installed ' 'to use TestResponse.xml') xml = cached_property(xml) def lxml(self): """Get an lxml etree if possible.""" if ('html' not in self.mimetype and 'xml' not in self.mimetype): raise AttributeError('Not an HTML/XML response') from lxml import etree try: from lxml.html import fromstring except ImportError: fromstring = etree.HTML if self.mimetype == 'text/html': return fromstring(self.data) return etree.XML(self.data) lxml = cached_property(lxml) def json(self): """Get the result of simplejson.loads if possible.""" if 'json' not in self.mimetype: raise AttributeError('Not a JSON response') try: from simplejson import loads except ImportError: from json import loads return loads(self.data) json = cached_property(json) class TestResponse(Response, ContentAccessors): """Pass this to `werkzeug.test.Client` for easier unittesting."""
CenterForOpenScience/osf.io
refs/heads/develop
api_tests/providers/registrations/views/test_registration_provider_moderator_list.py
5
import pytest from api.base.settings.defaults import API_BASE from osf_tests.factories import ( RegistrationProviderFactory, ) from api_tests.providers.preprints.views.test_preprint_provider_moderator_list import ProviderModeratorListTestClass @pytest.mark.django_db class TestRegistrationProviderModeratorList(ProviderModeratorListTestClass): @pytest.fixture() def provider(self): pp = RegistrationProviderFactory(name='EGAP') pp.update_group_permissions() return pp @pytest.fixture() def url(self, provider): return f'/{API_BASE}providers/registrations/{provider._id}/moderators/'
ghchinoy/tensorflow
refs/heads/master
tensorflow/contrib/rnn/python/ops/core_rnn_cell.py
19
# Copyright 2015 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. # ============================================================================== """Module implementing RNN Cells that used to be in core. @@EmbeddingWrapper @@InputProjectionWrapper @@OutputProjectionWrapper """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import embedding_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import rnn_cell_impl from tensorflow.python.ops import variable_scope as vs from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import nest # pylint: disable=protected-access,invalid-name RNNCell = rnn_cell_impl.RNNCell _WEIGHTS_VARIABLE_NAME = rnn_cell_impl._WEIGHTS_VARIABLE_NAME _BIAS_VARIABLE_NAME = rnn_cell_impl._BIAS_VARIABLE_NAME # pylint: enable=protected-access,invalid-name class _Linear(object): """Linear map: sum_i(args[i] * W[i]), where W[i] is a variable. Args: args: a 2D Tensor or a list of 2D, batch, n, Tensors. output_size: int, second dimension of weight variable. dtype: data type for variables. build_bias: boolean, whether to build a bias variable. bias_initializer: starting value to initialize the bias (default is all zeros). kernel_initializer: starting value to initialize the weight. Raises: ValueError: if inputs_shape is wrong. """ def __init__(self, args, output_size, build_bias, bias_initializer=None, kernel_initializer=None): self._build_bias = build_bias if args is None or (nest.is_sequence(args) and not args): raise ValueError("`args` must be specified") if not nest.is_sequence(args): args = [args] self._is_sequence = False else: self._is_sequence = True # Calculate the total size of arguments on dimension 1. total_arg_size = 0 shapes = [a.get_shape() for a in args] for shape in shapes: if shape.ndims != 2: raise ValueError("linear is expecting 2D arguments: %s" % shapes) if shape.dims[1].value is None: raise ValueError("linear expects shape[1] to be provided for shape %s, " "but saw %s" % (shape, shape[1])) else: total_arg_size += shape.dims[1].value dtype = [a.dtype for a in args][0] scope = vs.get_variable_scope() with vs.variable_scope(scope) as outer_scope: self._weights = vs.get_variable( _WEIGHTS_VARIABLE_NAME, [total_arg_size, output_size], dtype=dtype, initializer=kernel_initializer) if build_bias: with vs.variable_scope(outer_scope) as inner_scope: inner_scope.set_partitioner(None) if bias_initializer is None: bias_initializer = init_ops.constant_initializer(0.0, dtype=dtype) self._biases = vs.get_variable( _BIAS_VARIABLE_NAME, [output_size], dtype=dtype, initializer=bias_initializer) def __call__(self, args): if not self._is_sequence: args = [args] if len(args) == 1: res = math_ops.matmul(args[0], self._weights) else: # Explicitly creating a one for a minor performance improvement. one = constant_op.constant(1, dtype=dtypes.int32) res = math_ops.matmul(array_ops.concat(args, one), self._weights) if self._build_bias: res = nn_ops.bias_add(res, self._biases) return res # TODO(xpan): Remove this function in a follow up. def _linear(args, output_size, bias, bias_initializer=None, kernel_initializer=None): """Linear map: sum_i(args[i] * W[i]), where W[i] is a variable. Args: args: a 2D Tensor or a list of 2D, batch, n, Tensors. output_size: int, second dimension of W[i]. bias: boolean, whether to add a bias term or not. bias_initializer: starting value to initialize the bias (default is all zeros). kernel_initializer: starting value to initialize the weight. Returns: A 2D Tensor with shape `[batch, output_size]` equal to sum_i(args[i] * W[i]), where W[i]s are newly created matrices. Raises: ValueError: if some of the arguments has unspecified or wrong shape. """ if args is None or (nest.is_sequence(args) and not args): raise ValueError("`args` must be specified") if not nest.is_sequence(args): args = [args] # Calculate the total size of arguments on dimension 1. total_arg_size = 0 shapes = [a.get_shape() for a in args] for shape in shapes: if shape.ndims != 2: raise ValueError("linear is expecting 2D arguments: %s" % shapes) if shape.dims[1].value is None: raise ValueError("linear expects shape[1] to be provided for shape %s, " "but saw %s" % (shape, shape[1])) else: total_arg_size += shape.dims[1].value dtype = [a.dtype for a in args][0] # Now the computation. scope = vs.get_variable_scope() with vs.variable_scope(scope) as outer_scope: weights = vs.get_variable( _WEIGHTS_VARIABLE_NAME, [total_arg_size, output_size], dtype=dtype, initializer=kernel_initializer) if len(args) == 1: res = math_ops.matmul(args[0], weights) else: res = math_ops.matmul(array_ops.concat(args, 1), weights) if not bias: return res with vs.variable_scope(outer_scope) as inner_scope: inner_scope.set_partitioner(None) if bias_initializer is None: bias_initializer = init_ops.constant_initializer(0.0, dtype=dtype) biases = vs.get_variable( _BIAS_VARIABLE_NAME, [output_size], dtype=dtype, initializer=bias_initializer) return nn_ops.bias_add(res, biases) class EmbeddingWrapper(RNNCell): """Operator adding input embedding to the given cell. Note: in many cases it may be more efficient to not use this wrapper, but instead concatenate the whole sequence of your inputs in time, do the embedding on this batch-concatenated sequence, then split it and feed into your RNN. """ def __init__(self, cell, embedding_classes, embedding_size, initializer=None, reuse=None): """Create a cell with an added input embedding. Args: cell: an RNNCell, an embedding will be put before its inputs. embedding_classes: integer, how many symbols will be embedded. embedding_size: integer, the size of the vectors we embed into. initializer: an initializer to use when creating the embedding; if None, the initializer from variable scope or a default one is used. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. Raises: TypeError: if cell is not an RNNCell. ValueError: if embedding_classes is not positive. """ super(EmbeddingWrapper, self).__init__(_reuse=reuse) rnn_cell_impl.assert_like_rnncell("cell", cell) if embedding_classes <= 0 or embedding_size <= 0: raise ValueError("Both embedding_classes and embedding_size must be > 0: " "%d, %d." % (embedding_classes, embedding_size)) self._cell = cell self._embedding_classes = embedding_classes self._embedding_size = embedding_size self._initializer = initializer @property def state_size(self): return self._cell.state_size @property def output_size(self): return self._cell.output_size def zero_state(self, batch_size, dtype): with ops.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]): return self._cell.zero_state(batch_size, dtype) def call(self, inputs, state): """Run the cell on embedded inputs.""" with ops.device("/cpu:0"): if self._initializer: initializer = self._initializer elif vs.get_variable_scope().initializer: initializer = vs.get_variable_scope().initializer else: # Default initializer for embeddings should have variance=1. sqrt3 = math.sqrt(3) # Uniform(-sqrt(3), sqrt(3)) has variance=1. initializer = init_ops.random_uniform_initializer(-sqrt3, sqrt3) if isinstance(state, tuple): data_type = state[0].dtype else: data_type = state.dtype embedding = vs.get_variable( "embedding", [self._embedding_classes, self._embedding_size], initializer=initializer, dtype=data_type) embedded = embedding_ops.embedding_lookup(embedding, array_ops.reshape(inputs, [-1])) return self._cell(embedded, state) class InputProjectionWrapper(RNNCell): """Operator adding an input projection to the given cell. Note: in many cases it may be more efficient to not use this wrapper, but instead concatenate the whole sequence of your inputs in time, do the projection on this batch-concatenated sequence, then split it. """ def __init__(self, cell, num_proj, activation=None, input_size=None, reuse=None): """Create a cell with input projection. Args: cell: an RNNCell, a projection of inputs is added before it. num_proj: Python integer. The dimension to project to. activation: (optional) an optional activation function. input_size: Deprecated and unused. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. Raises: TypeError: if cell is not an RNNCell. """ super(InputProjectionWrapper, self).__init__(_reuse=reuse) if input_size is not None: logging.warn("%s: The input_size parameter is deprecated.", self) rnn_cell_impl.assert_like_rnncell("cell", cell) self._cell = cell self._num_proj = num_proj self._activation = activation self._linear = None @property def state_size(self): return self._cell.state_size @property def output_size(self): return self._cell.output_size def zero_state(self, batch_size, dtype): with ops.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]): return self._cell.zero_state(batch_size, dtype) def call(self, inputs, state): """Run the input projection and then the cell.""" # Default scope: "InputProjectionWrapper" if self._linear is None: self._linear = _Linear(inputs, self._num_proj, True) projected = self._linear(inputs) if self._activation: projected = self._activation(projected) return self._cell(projected, state) class OutputProjectionWrapper(RNNCell): """Operator adding an output projection to the given cell. Note: in many cases it may be more efficient to not use this wrapper, but instead concatenate the whole sequence of your outputs in time, do the projection on this batch-concatenated sequence, then split it if needed or directly feed into a softmax. """ def __init__(self, cell, output_size, activation=None, reuse=None): """Create a cell with output projection. Args: cell: an RNNCell, a projection to output_size is added to it. output_size: integer, the size of the output after projection. activation: (optional) an optional activation function. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. Raises: TypeError: if cell is not an RNNCell. ValueError: if output_size is not positive. """ super(OutputProjectionWrapper, self).__init__(_reuse=reuse) rnn_cell_impl.assert_like_rnncell("cell", cell) if output_size < 1: raise ValueError("Parameter output_size must be > 0: %d." % output_size) self._cell = cell self._output_size = output_size self._activation = activation self._linear = None @property def state_size(self): return self._cell.state_size @property def output_size(self): return self._output_size def zero_state(self, batch_size, dtype): with ops.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]): return self._cell.zero_state(batch_size, dtype) def call(self, inputs, state): """Run the cell and output projection on inputs, starting from state.""" output, res_state = self._cell(inputs, state) if self._linear is None: self._linear = _Linear(output, self._output_size, True) projected = self._linear(output) if self._activation: projected = self._activation(projected) return projected, res_state
datalocale/drupal7
refs/heads/master
sites/all/libraries/OpenLayers/tools/BeautifulSoup.py
307
"""Beautiful Soup Elixir and Tonic "The Screen-Scraper's Friend" http://www.crummy.com/software/BeautifulSoup/ Beautiful Soup parses a (possibly invalid) XML or HTML document into a tree representation. It provides methods and Pythonic idioms that make it easy to navigate, search, and modify the tree. A well-formed XML/HTML document yields a well-formed data structure. An ill-formed XML/HTML document yields a correspondingly ill-formed data structure. If your document is only locally well-formed, you can use this library to find and process the well-formed part of it. The BeautifulSoup class Beautiful Soup works with Python 2.2 and up. It has no external dependencies, but you'll have more success at converting data to UTF-8 if you also install these three packages: * chardet, for auto-detecting character encodings http://chardet.feedparser.org/ * cjkcodecs and iconv_codec, which add more encodings to the ones supported by stock Python. http://cjkpython.i18n.org/ Beautiful Soup defines classes for two main parsing strategies: * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific language that kind of looks like XML. * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid or invalid. This class has web browser-like heuristics for obtaining a sensible parse tree in the face of common HTML errors. Beautiful Soup also defines a class (UnicodeDammit) for autodetecting the encoding of an HTML or XML document, and converting it to Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser. For more than you ever wanted to know about Beautiful Soup, see the documentation: http://www.crummy.com/software/BeautifulSoup/documentation.html """ from __future__ import generators __author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.0.4" __copyright__ = "Copyright (c) 2004-2007 Leonard Richardson" __license__ = "PSF" from sgmllib import SGMLParser, SGMLParseError import codecs import types import re import sgmllib try: from htmlentitydefs import name2codepoint except ImportError: name2codepoint = {} #This hack makes Beautiful Soup able to parse XML with namespaces sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*') DEFAULT_OUTPUT_ENCODING = "utf-8" # First, the classes that represent markup elements. class PageElement: """Contains the navigational information for some part of the page (either a tag or a piece of text)""" def setup(self, parent=None, previous=None): """Sets up the initial relations between this element and other elements.""" self.parent = parent self.previous = previous self.next = None self.previousSibling = None self.nextSibling = None if self.parent and self.parent.contents: self.previousSibling = self.parent.contents[-1] self.previousSibling.nextSibling = self def replaceWith(self, replaceWith): oldParent = self.parent myIndex = self.parent.contents.index(self) if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent: # We're replacing this element with one of its siblings. index = self.parent.contents.index(replaceWith) if index and index < myIndex: # Furthermore, it comes before this element. That # means that when we extract it, the index of this # element will change. myIndex = myIndex - 1 self.extract() oldParent.insert(myIndex, replaceWith) def extract(self): """Destructively rips this element out of the tree.""" if self.parent: try: self.parent.contents.remove(self) except ValueError: pass #Find the two elements that would be next to each other if #this element (and any children) hadn't been parsed. Connect #the two. lastChild = self._lastRecursiveChild() nextElement = lastChild.next if self.previous: self.previous.next = nextElement if nextElement: nextElement.previous = self.previous self.previous = None lastChild.next = None self.parent = None if self.previousSibling: self.previousSibling.nextSibling = self.nextSibling if self.nextSibling: self.nextSibling.previousSibling = self.previousSibling self.previousSibling = self.nextSibling = None def _lastRecursiveChild(self): "Finds the last element beneath this object to be parsed." lastChild = self while hasattr(lastChild, 'contents') and lastChild.contents: lastChild = lastChild.contents[-1] return lastChild def insert(self, position, newChild): if (isinstance(newChild, basestring) or isinstance(newChild, unicode)) \ and not isinstance(newChild, NavigableString): newChild = NavigableString(newChild) position = min(position, len(self.contents)) if hasattr(newChild, 'parent') and newChild.parent != None: # We're 'inserting' an element that's already one # of this object's children. if newChild.parent == self: index = self.find(newChild) if index and index < position: # Furthermore we're moving it further down the # list of this object's children. That means that # when we extract this element, our target index # will jump down one. position = position - 1 newChild.extract() newChild.parent = self previousChild = None if position == 0: newChild.previousSibling = None newChild.previous = self else: previousChild = self.contents[position-1] newChild.previousSibling = previousChild newChild.previousSibling.nextSibling = newChild newChild.previous = previousChild._lastRecursiveChild() if newChild.previous: newChild.previous.next = newChild newChildsLastElement = newChild._lastRecursiveChild() if position >= len(self.contents): newChild.nextSibling = None parent = self parentsNextSibling = None while not parentsNextSibling: parentsNextSibling = parent.nextSibling parent = parent.parent if not parent: # This is the last element in the document. break if parentsNextSibling: newChildsLastElement.next = parentsNextSibling else: newChildsLastElement.next = None else: nextChild = self.contents[position] newChild.nextSibling = nextChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild newChildsLastElement.next = nextChild if newChildsLastElement.next: newChildsLastElement.next.previous = newChildsLastElement self.contents.insert(position, newChild) def findNext(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findAllNext, name, attrs, text, **kwargs) def findAllNext(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear before after Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextGenerator) def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findNextSiblings, name, attrs, text, **kwargs) def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextSiblingGenerator, **kwargs) fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x def findPrevious(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs) def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousGenerator, **kwargs) fetchPrevious = findAllPrevious # Compatibility with pre-3.x def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findPreviousSiblings, name, attrs, text, **kwargs) def findPreviousSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousSiblingGenerator, **kwargs) fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x def findParent(self, name=None, attrs={}, **kwargs): """Returns the closest parent of this Tag that matches the given criteria.""" # NOTE: We can't use _findOne because findParents takes a different # set of arguments. r = None l = self.findParents(name, attrs, 1) if l: r = l[0] return r def findParents(self, name=None, attrs={}, limit=None, **kwargs): """Returns the parents of this Tag that match the given criteria.""" return self._findAll(name, attrs, None, limit, self.parentGenerator, **kwargs) fetchParents = findParents # Compatibility with pre-3.x #These methods do the real heavy lifting. def _findOne(self, method, name, attrs, text, **kwargs): r = None l = method(name, attrs, text, 1, **kwargs) if l: r = l[0] return r def _findAll(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name else: # Build a SoupStrainer strainer = SoupStrainer(name, attrs, text, **kwargs) results = ResultSet(strainer) g = generator() while True: try: i = g.next() except StopIteration: break if i: found = strainer.search(i) if found: results.append(found) if limit and len(results) >= limit: break return results #These Generators can be used to navigate starting from both #NavigableStrings and Tags. def nextGenerator(self): i = self while i: i = i.next yield i def nextSiblingGenerator(self): i = self while i: i = i.nextSibling yield i def previousGenerator(self): i = self while i: i = i.previous yield i def previousSiblingGenerator(self): i = self while i: i = i.previousSibling yield i def parentGenerator(self): i = self while i: i = i.parent yield i # Utility methods def substituteEncoding(self, str, encoding=None): encoding = encoding or "utf-8" return str.replace("%SOUP-ENCODING%", encoding) def toEncoding(self, s, encoding=None): """Encodes an object to a string in some encoding, or to Unicode. .""" if isinstance(s, unicode): if encoding: s = s.encode(encoding) elif isinstance(s, str): if encoding: s = s.encode(encoding) else: s = unicode(s) else: if encoding: s = self.toEncoding(str(s), encoding) else: s = unicode(s) return s class NavigableString(unicode, PageElement): def __getattr__(self, attr): """text.string gives you text. This is for backwards compatibility for Navigable*String, but for CData* it lets you get the string without the CData wrapper.""" if attr == 'string': return self else: raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr) def __unicode__(self): return self.__str__(None) def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): if encoding: return self.encode(encoding) else: return self class CData(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): return "<![CDATA[%s]]>" % NavigableString.__str__(self, encoding) class ProcessingInstruction(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): output = self if "%SOUP-ENCODING%" in output: output = self.substituteEncoding(output, encoding) return "<?%s?>" % self.toEncoding(output, encoding) class Comment(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): return "<!--%s-->" % NavigableString.__str__(self, encoding) class Declaration(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): return "<!%s>" % NavigableString.__str__(self, encoding) class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" XML_SPECIAL_CHARS_TO_ENTITIES = { "'" : "squot", '"' : "quote", "&" : "amp", "<" : "lt", ">" : "gt" } def __init__(self, parser, name, attrs=None, parent=None, previous=None): "Basic constructor." # We don't actually store the parser object: that lets extracted # chunks be garbage-collected self.parserClass = parser.__class__ self.isSelfClosing = parser.isSelfClosingTag(name) self.name = name if attrs == None: attrs = [] self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = False self.containsSubstitutions = False def get(self, key, default=None): """Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.""" return self._getAttrMap().get(key, default) def has_key(self, key): return self._getAttrMap().has_key(key) def __getitem__(self, key): """tag[key] returns the value of the 'key' attribute for the tag, and throws an exception if it's not there.""" return self._getAttrMap()[key] def __iter__(self): "Iterating over a tag iterates over its contents." return iter(self.contents) def __len__(self): "The length of a tag is the length of its list of contents." return len(self.contents) def __contains__(self, x): return x in self.contents def __nonzero__(self): "A tag is non-None even if it has no contents." return True def __setitem__(self, key, value): """Setting tag[key] sets the value of the 'key' attribute for the tag.""" self._getAttrMap() self.attrMap[key] = value found = False for i in range(0, len(self.attrs)): if self.attrs[i][0] == key: self.attrs[i] = (key, value) found = True if not found: self.attrs.append((key, value)) self._getAttrMap()[key] = value def __delitem__(self, key): "Deleting tag[key] deletes all 'key' attributes for the tag." for item in self.attrs: if item[0] == key: self.attrs.remove(item) #We don't break because bad HTML can define the same #attribute multiple times. self._getAttrMap() if self.attrMap.has_key(key): del self.attrMap[key] def __call__(self, *args, **kwargs): """Calling a tag like a function is the same as calling its findAll() method. Eg. tag('a') returns a list of all the A tags found within this tag.""" return apply(self.findAll, args, kwargs) def __getattr__(self, tag): #print "Getattr %s.%s" % (self.__class__, tag) if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3: return self.find(tag[:-3]) elif tag.find('__') != 0: return self.find(tag) def __eq__(self, other): """Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag. NOTE: right now this will return false if two tags have the same attributes in a different order. Should this be fixed?""" if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other): return False for i in range(0, len(self.contents)): if self.contents[i] != other.contents[i]: return False return True def __ne__(self, other): """Returns true iff this tag is not identical to the other tag, as defined in __eq__.""" return not self == other def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): """Renders this tag as a string.""" return self.__str__(encoding) def __unicode__(self): return self.__str__(None) def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): """Returns a string or Unicode representation of this tag and its contents. To get Unicode, pass None for encoding. NOTE: since Python's HTML parser consumes whitespace, this method is not certain to reproduce the whitespace present in the original string.""" encodedName = self.toEncoding(self.name, encoding) attrs = [] if self.attrs: for key, val in self.attrs: fmt = '%s="%s"' if isString(val): if self.containsSubstitutions and '%SOUP-ENCODING%' in val: val = self.substituteEncoding(val, encoding) # The attribute value either: # # * Contains no embedded double quotes or single quotes. # No problem: we enclose it in double quotes. # * Contains embedded single quotes. No problem: # double quotes work here too. # * Contains embedded double quotes. No problem: # we enclose it in single quotes. # * Embeds both single _and_ double quotes. This # can't happen naturally, but it can happen if # you modify an attribute value after parsing # the document. Now we have a bit of a # problem. We solve it by enclosing the # attribute in single quotes, and escaping any # embedded single quotes to XML entities. if '"' in val: fmt = "%s='%s'" # This can't happen naturally, but it can happen # if you modify an attribute value after parsing. if "'" in val: val = val.replace("'", "&squot;") # Now we're okay w/r/t quotes. But the attribute # value might also contain angle brackets, or # ampersands that aren't part of entities. We need # to escape those to XML entities too. val = re.sub("([<>]|&(?![^\s]+;))", lambda x: "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";", val) attrs.append(fmt % (self.toEncoding(key, encoding), self.toEncoding(val, encoding))) close = '' closeTag = '' if self.isSelfClosing: close = ' /' else: closeTag = '</%s>' % encodedName indentTag, indentContents = 0, 0 if prettyPrint: indentTag = indentLevel space = (' ' * (indentTag-1)) indentContents = indentTag + 1 contents = self.renderContents(encoding, prettyPrint, indentContents) if self.hidden: s = contents else: s = [] attributeString = '' if attrs: attributeString = ' ' + ' '.join(attrs) if prettyPrint: s.append(space) s.append('<%s%s%s>' % (encodedName, attributeString, close)) if prettyPrint: s.append("\n") s.append(contents) if prettyPrint and contents and contents[-1] != "\n": s.append("\n") if prettyPrint and closeTag: s.append(space) s.append(closeTag) if prettyPrint and closeTag and self.nextSibling: s.append("\n") s = ''.join(s) return s def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING): return self.__str__(encoding, True) def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): """Renders the contents of this tag as a string in the given encoding. If encoding is None, returns a Unicode string..""" s=[] for c in self: text = None if isinstance(c, NavigableString): text = c.__str__(encoding) elif isinstance(c, Tag): s.append(c.__str__(encoding, prettyPrint, indentLevel)) if text and prettyPrint: text = text.strip() if text: if prettyPrint: s.append(" " * (indentLevel-1)) s.append(text) if prettyPrint: s.append("\n") return ''.join(s) #Soup methods def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): """Return only the first child of this Tag matching the given criteria.""" r = None l = self.findAll(name, attrs, recursive, text, 1, **kwargs) if l: r = l[0] return r findChild = find def findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): """Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the 'attrs' map can be a string, a list of strings, a regular expression object, or a callable that takes a string and returns whether or not the string matches for some custom definition of 'matches'. The same is true of the tag name.""" generator = self.recursiveChildGenerator if not recursive: generator = self.childGenerator return self._findAll(name, attrs, text, limit, generator, **kwargs) findChildren = findAll # Pre-3.x compatibility methods first = find fetch = findAll def fetchText(self, text=None, recursive=True, limit=None): return self.findAll(text=text, recursive=recursive, limit=limit) def firstText(self, text=None, recursive=True): return self.find(text=text, recursive=recursive) #Utility methods def append(self, tag): """Appends the given tag to the contents of this tag.""" self.contents.append(tag) #Private methods def _getAttrMap(self): """Initializes a map representation of this tag's attributes, if not already initialized.""" if not getattr(self, 'attrMap'): self.attrMap = {} for (key, value) in self.attrs: self.attrMap[key] = value return self.attrMap #Generator methods def childGenerator(self): for i in range(0, len(self.contents)): yield self.contents[i] raise StopIteration def recursiveChildGenerator(self): stack = [(self, 0)] while stack: tag, start = stack.pop() if isinstance(tag, Tag): for i in range(start, len(tag.contents)): a = tag.contents[i] yield a if isinstance(a, Tag) and tag.contents: if i < len(tag.contents) - 1: stack.append((tag, i+1)) stack.append((a, 0)) break raise StopIteration # Next, a couple classes to represent queries and their results. class SoupStrainer: """Encapsulates a number of ways of matching a markup element (tag or text).""" def __init__(self, name=None, attrs={}, text=None, **kwargs): self.name = name if isString(attrs): kwargs['class'] = attrs attrs = None if kwargs: if attrs: attrs = attrs.copy() attrs.update(kwargs) else: attrs = kwargs self.attrs = attrs self.text = text def __str__(self): if self.text: return self.text else: return "%s|%s" % (self.name, self.attrs) def searchTag(self, markupName=None, markupAttrs={}): found = None markup = None if isinstance(markupName, Tag): markup = markupName markupAttrs = markup callFunctionWithTagData = callable(self.name) \ and not isinstance(markupName, Tag) if (not self.name) \ or callFunctionWithTagData \ or (markup and self._matches(markup, self.name)) \ or (not markup and self._matches(markupName, self.name)): if callFunctionWithTagData: match = self.name(markupName, markupAttrs) else: match = True markupAttrMap = None for attr, matchAgainst in self.attrs.items(): if not markupAttrMap: if hasattr(markupAttrs, 'get'): markupAttrMap = markupAttrs else: markupAttrMap = {} for k,v in markupAttrs: markupAttrMap[k] = v attrValue = markupAttrMap.get(attr) if not self._matches(attrValue, matchAgainst): match = False break if match: if markup: found = markup else: found = markupName return found def search(self, markup): #print 'looking for %s in %s' % (self, markup) found = None # If given a list of items, scan it for a text element that # matches. if isList(markup) and not isinstance(markup, Tag): for element in markup: if isinstance(element, NavigableString) \ and self.search(element): found = element break # If it's a Tag, make sure its name or attributes match. # Don't bother with Tags if we're searching for text. elif isinstance(markup, Tag): if not self.text: found = self.searchTag(markup) # If it's text, make sure the text matches. elif isinstance(markup, NavigableString) or \ isString(markup): if self._matches(markup, self.text): found = markup else: raise Exception, "I don't know how to match against a %s" \ % markup.__class__ return found def _matches(self, markup, matchAgainst): #print "Matching %s against %s" % (markup, matchAgainst) result = False if matchAgainst == True and type(matchAgainst) == types.BooleanType: result = markup != None elif callable(matchAgainst): result = matchAgainst(markup) else: #Custom match methods take the tag as an argument, but all #other ways of matching match the tag name as a string. if isinstance(markup, Tag): markup = markup.name if markup and not isString(markup): markup = unicode(markup) #Now we know that chunk is either a string, or None. if hasattr(matchAgainst, 'match'): # It's a regexp object. result = markup and matchAgainst.search(markup) elif isList(matchAgainst): result = markup in matchAgainst elif hasattr(matchAgainst, 'items'): result = markup.has_key(matchAgainst) elif matchAgainst and isString(markup): if isinstance(markup, unicode): matchAgainst = unicode(matchAgainst) else: matchAgainst = str(matchAgainst) if not result: result = matchAgainst == markup return result class ResultSet(list): """A ResultSet is just a list that keeps track of the SoupStrainer that created it.""" def __init__(self, source): list.__init__([]) self.source = source # Now, some helper functions. def isList(l): """Convenience method that works with all 2.x versions of Python to determine whether or not something is listlike.""" return hasattr(l, '__iter__') \ or (type(l) in (types.ListType, types.TupleType)) def isString(s): """Convenience method that works with all 2.x versions of Python to determine whether or not something is stringlike.""" try: return isinstance(s, unicode) or isintance(s, basestring) except NameError: return isinstance(s, str) def buildTagMap(default, *args): """Turns a list of maps, lists, or scalars into a single map. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and NESTING_RESET_TAGS maps out of lists and partial maps.""" built = {} for portion in args: if hasattr(portion, 'items'): #It's a map. Merge it. for k,v in portion.items(): built[k] = v elif isList(portion): #It's a list. Map each item to the default. for k in portion: built[k] = default else: #It's a scalar. Map it to the default. built[portion] = default return built # Now, the parser classes. class BeautifulStoneSoup(Tag, SGMLParser): """This class contains the basic parser and search code. It defines a parser that knows nothing about tag behavior except for the following: You can't close a tag without closing all the tags it encloses. That is, "<foo><bar></foo>" actually means "<foo><bar></bar></foo>". [Another possible explanation is "<foo><bar /></foo>", but since this class defines no SELF_CLOSING_TAGS, it will never use that explanation.] This class is useful for parsing XML or made-up markup languages, or when BeautifulSoup makes an assumption counter to what you were expecting.""" XML_ENTITY_LIST = {} for i in Tag.XML_SPECIAL_CHARS_TO_ENTITIES.values(): XML_ENTITY_LIST[i] = True SELF_CLOSING_TAGS = {} NESTABLE_TAGS = {} RESET_NESTING_TAGS = {} QUOTE_TAGS = {} MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'), lambda x: x.group(1) + ' />'), (re.compile('<!\s+([^<>]*)>'), lambda x: '<!' + x.group(1) + '>') ] ROOT_TAG_NAME = u'[document]' HTML_ENTITIES = "html" XML_ENTITIES = "xml" def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo=XML_ENTITIES, convertEntities=None, selfClosingTags=None): """The Soup object is initialized as the 'root tag', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser. sgmllib will process most bad HTML, and the BeautifulSoup class has some tricks for dealing with some HTML that kills sgmllib, but Beautiful Soup can nonetheless choke or lose data if your data uses self-closing tags or declarations incorrectly. By default, Beautiful Soup uses regexes to sanitize input, avoiding the vast majority of these problems. If the problems don't apply to you, pass in False for markupMassage, and you'll get better performance. The default parser massage techniques fix the two most common instances of invalid HTML that choke sgmllib: <br/> (No space between name of closing tag and tag close) <! --Comment--> (Extraneous whitespace in declaration) You can pass in a custom list of (RE object, replace method) tuples to get Beautiful Soup to scrub your input the way you want.""" self.parseOnlyThese = parseOnlyThese self.fromEncoding = fromEncoding self.smartQuotesTo = smartQuotesTo self.convertEntities = convertEntities if self.convertEntities: # It doesn't make sense to convert encoded characters to # entities even while you're converting entities to Unicode. # Just convert it all to Unicode. self.smartQuotesTo = None self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags) SGMLParser.__init__(self) if hasattr(markup, 'read'): # It's a file-type object. markup = markup.read() self.markup = markup self.markupMassage = markupMassage try: self._feed() except StopParsing: pass self.markup = None # The markup can now be GCed def _feed(self, inDocumentEncoding=None): # Convert the document to Unicode. markup = self.markup if isinstance(markup, unicode): if not hasattr(self, 'originalEncoding'): self.originalEncoding = None else: dammit = UnicodeDammit\ (markup, [self.fromEncoding, inDocumentEncoding], smartQuotesTo=self.smartQuotesTo) markup = dammit.unicode self.originalEncoding = dammit.originalEncoding if markup: if self.markupMassage: if not isList(self.markupMassage): self.markupMassage = self.MARKUP_MASSAGE for fix, m in self.markupMassage: markup = fix.sub(m, markup) self.reset() SGMLParser.feed(self, markup) # Close out any unfinished strings and close all the open tags. self.endData() while self.currentTag.name != self.ROOT_TAG_NAME: self.popTag() def __getattr__(self, methodName): """This method routes method call requests to either the SGMLParser superclass or the Tag superclass, depending on the method name.""" #print "__getattr__ called on %s.%s" % (self.__class__, methodName) if methodName.find('start_') == 0 or methodName.find('end_') == 0 \ or methodName.find('do_') == 0: return SGMLParser.__getattr__(self, methodName) elif methodName.find('__') != 0: return Tag.__getattr__(self, methodName) else: raise AttributeError def isSelfClosingTag(self, name): """Returns true iff the given string is the name of a self-closing tag according to this parser.""" return self.SELF_CLOSING_TAGS.has_key(name) \ or self.instanceSelfClosingTags.has_key(name) def reset(self): Tag.__init__(self, self, self.ROOT_TAG_NAME) self.hidden = 1 SGMLParser.reset(self) self.currentData = [] self.currentTag = None self.tagStack = [] self.quoteStack = [] self.pushTag(self) def popTag(self): tag = self.tagStack.pop() # Tags with just one string-owning child get the child as a # 'string' property, so that soup.tag.string is shorthand for # soup.tag.contents[0] if len(self.currentTag.contents) == 1 and \ isinstance(self.currentTag.contents[0], NavigableString): self.currentTag.string = self.currentTag.contents[0] #print "Pop", tag.name if self.tagStack: self.currentTag = self.tagStack[-1] return self.currentTag def pushTag(self, tag): #print "Push", tag.name if self.currentTag: self.currentTag.append(tag) self.tagStack.append(tag) self.currentTag = self.tagStack[-1] def endData(self, containerClass=NavigableString): if self.currentData: currentData = ''.join(self.currentData) if not currentData.strip(): if '\n' in currentData: currentData = '\n' else: currentData = ' ' self.currentData = [] if self.parseOnlyThese and len(self.tagStack) <= 1 and \ (not self.parseOnlyThese.text or \ not self.parseOnlyThese.search(currentData)): return o = containerClass(currentData) o.setup(self.currentTag, self.previous) if self.previous: self.previous.next = o self.previous = o self.currentTag.contents.append(o) def _popToTag(self, name, inclusivePop=True): """Pops the tag stack up to and including the most recent instance of the given tag. If inclusivePop is false, pops the tag stack up to but *not* including the most recent instqance of the given tag.""" #print "Popping to %s" % name if name == self.ROOT_TAG_NAME: return numPops = 0 mostRecentTag = None for i in range(len(self.tagStack)-1, 0, -1): if name == self.tagStack[i].name: numPops = len(self.tagStack)-i break if not inclusivePop: numPops = numPops - 1 for i in range(0, numPops): mostRecentTag = self.popTag() return mostRecentTag def _smartPop(self, name): """We need to pop up to the previous tag of this type, unless one of this tag's nesting reset triggers comes between this tag and the previous tag of this type, OR unless this tag is a generic nesting trigger and another generic nesting trigger comes between this tag and the previous tag of this type. Examples: <p>Foo<b>Bar<p> should pop to 'p', not 'b'. <p>Foo<table>Bar<p> should pop to 'table', not 'p'. <p>Foo<table><tr>Bar<p> should pop to 'tr', not 'p'. <p>Foo<b>Bar<p> should pop to 'p', not 'b'. <li><ul><li> *<li>* should pop to 'ul', not the first 'li'. <tr><table><tr> *<tr>* should pop to 'table', not the first 'tr' <td><tr><td> *<td>* should pop to 'tr', not the first 'td' """ nestingResetTriggers = self.NESTABLE_TAGS.get(name) isNestable = nestingResetTriggers != None isResetNesting = self.RESET_NESTING_TAGS.has_key(name) popTo = None inclusive = True for i in range(len(self.tagStack)-1, 0, -1): p = self.tagStack[i] if (not p or p.name == name) and not isNestable: #Non-nestable tags get popped to the top or to their #last occurance. popTo = name break if (nestingResetTriggers != None and p.name in nestingResetTriggers) \ or (nestingResetTriggers == None and isResetNesting and self.RESET_NESTING_TAGS.has_key(p.name)): #If we encounter one of the nesting reset triggers #peculiar to this tag, or we encounter another tag #that causes nesting to reset, pop up to but not #including that tag. popTo = p.name inclusive = False break p = p.parent if popTo: self._popToTag(popTo, inclusive) def unknown_starttag(self, name, attrs, selfClosing=0): #print "Start tag %s: %s" % (name, attrs) if self.quoteStack: #This is not a real tag. #print "<%s> is not real!" % name attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs)) self.handle_data('<%s%s>' % (name, attrs)) return self.endData() if not self.isSelfClosingTag(name) and not selfClosing: self._smartPop(name) if self.parseOnlyThese and len(self.tagStack) <= 1 \ and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)): return tag = Tag(self, name, attrs, self.currentTag, self.previous) if self.previous: self.previous.next = tag self.previous = tag self.pushTag(tag) if selfClosing or self.isSelfClosingTag(name): self.popTag() if name in self.QUOTE_TAGS: #print "Beginning quote (%s)" % name self.quoteStack.append(name) self.literal = 1 return tag def unknown_endtag(self, name): #print "End tag %s" % name if self.quoteStack and self.quoteStack[-1] != name: #This is not a real end tag. #print "</%s> is not real!" % name self.handle_data('</%s>' % name) return self.endData() self._popToTag(name) if self.quoteStack and self.quoteStack[-1] == name: self.quoteStack.pop() self.literal = (len(self.quoteStack) > 0) def handle_data(self, data): self.currentData.append(data) def _toStringSubclass(self, text, subclass): """Adds a certain piece of text to the tree as a NavigableString subclass.""" self.endData() self.handle_data(text) self.endData(subclass) def handle_pi(self, text): """Handle a processing instruction as a ProcessingInstruction object, possibly one with a %SOUP-ENCODING% slot into which an encoding will be plugged later.""" if text[:3] == "xml": text = "xml version='1.0' encoding='%SOUP-ENCODING%'" self._toStringSubclass(text, ProcessingInstruction) def handle_comment(self, text): "Handle comments as Comment objects." self._toStringSubclass(text, Comment) def handle_charref(self, ref): "Handle character references as data." if self.convertEntities in [self.HTML_ENTITIES, self.XML_ENTITIES]: data = unichr(int(ref)) else: data = '&#%s;' % ref self.handle_data(data) def handle_entityref(self, ref): """Handle entity references as data, possibly converting known HTML entity references to the corresponding Unicode characters.""" data = None if self.convertEntities == self.HTML_ENTITIES or \ (self.convertEntities == self.XML_ENTITIES and \ self.XML_ENTITY_LIST.get(ref)): try: data = unichr(name2codepoint[ref]) except KeyError: pass if not data: data = '&%s;' % ref self.handle_data(data) def handle_decl(self, data): "Handle DOCTYPEs and the like as Declaration objects." self._toStringSubclass(data, Declaration) def parse_declaration(self, i): """Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.""" j = None if self.rawdata[i:i+9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: k = len(self.rawdata) data = self.rawdata[i+9:k] j = k+3 self._toStringSubclass(data, CData) else: try: j = SGMLParser.parse_declaration(self, i) except SGMLParseError: toHandle = self.rawdata[i:] self.handle_data(toHandle) j = i + len(toHandle) return j class BeautifulSoup(BeautifulStoneSoup): """This parser knows the following facts about HTML: * Some tags have no closing tag and should be interpreted as being closed as soon as they are encountered. * The text inside some tags (ie. 'script') may contain tags which are not really part of the document and which should be parsed as text, not tags. If you want to parse the text as tags, you can always fetch it and parse it explicitly. * Tag nesting rules: Most tags can't be nested at all. For instance, the occurance of a <p> tag should implicitly close the previous <p> tag. <p>Para1<p>Para2 should be transformed into: <p>Para1</p><p>Para2 Some tags can be nested arbitrarily. For instance, the occurance of a <blockquote> tag should _not_ implicitly close the previous <blockquote> tag. Alice said: <blockquote>Bob said: <blockquote>Blah should NOT be transformed into: Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah Some tags can be nested, but the nesting is reset by the interposition of other tags. For instance, a <tr> tag should implicitly close the previous <tr> tag within the same <table>, but not close a <tr> tag in another table. <table><tr>Blah<tr>Blah should be transformed into: <table><tr>Blah</tr><tr>Blah but, <tr>Blah<table><tr>Blah should NOT be transformed into <tr>Blah<table></tr><tr>Blah Differing assumptions about tag nesting rules are a major source of problems with the BeautifulSoup class. If BeautifulSoup is not treating as nestable a tag your page author treats as nestable, try ICantBelieveItsBeautifulSoup, MinimalSoup, or BeautifulStoneSoup before writing your own subclass.""" def __init__(self, *args, **kwargs): if not kwargs.has_key('smartQuotesTo'): kwargs['smartQuotesTo'] = self.HTML_ENTITIES BeautifulStoneSoup.__init__(self, *args, **kwargs) SELF_CLOSING_TAGS = buildTagMap(None, ['br' , 'hr', 'input', 'img', 'meta', 'spacer', 'link', 'frame', 'base']) QUOTE_TAGS = {'script': None} #According to the HTML standard, each of these inline tags can #contain another tag of the same type. Furthermore, it's common #to actually use these tags this way. NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup', 'center'] #According to the HTML standard, these block tags can contain #another tag of the same type. Furthermore, it's common #to actually use these tags this way. NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del'] #Lists can contain other lists, but there are restrictions. NESTABLE_LIST_TAGS = { 'ol' : [], 'ul' : [], 'li' : ['ul', 'ol'], 'dl' : [], 'dd' : ['dl'], 'dt' : ['dl'] } #Tables can contain other tables, but there are restrictions. NESTABLE_TABLE_TAGS = {'table' : [], 'tr' : ['table', 'tbody', 'tfoot', 'thead'], 'td' : ['tr'], 'th' : ['tr'], 'thead' : ['table'], 'tbody' : ['table'], 'tfoot' : ['table'], } NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre'] #If one of these tags is encountered, all tags up to the next tag of #this type are popped. RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript', NON_NESTABLE_BLOCK_TAGS, NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS, NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) # Used to detect the charset in a META tag; see start_meta CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)") def start_meta(self, attrs): """Beautiful Soup can detect a charset included in a META tag, try to convert the document to that charset, and re-parse the document from the beginning.""" httpEquiv = None contentType = None contentTypeIndex = None tagNeedsEncodingSubstitution = False for i in range(0, len(attrs)): key, value = attrs[i] key = key.lower() if key == 'http-equiv': httpEquiv = value elif key == 'content': contentType = value contentTypeIndex = i if httpEquiv and contentType: # It's an interesting meta tag. match = self.CHARSET_RE.search(contentType) if match: if getattr(self, 'declaredHTMLEncoding') or \ (self.originalEncoding == self.fromEncoding): # This is our second pass through the document, or # else an encoding was specified explicitly and it # worked. Rewrite the meta tag. newAttr = self.CHARSET_RE.sub\ (lambda(match):match.group(1) + "%SOUP-ENCODING%", value) attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], newAttr) tagNeedsEncodingSubstitution = True else: # This is our first pass through the document. # Go through it again with the new information. newCharset = match.group(3) if newCharset and newCharset != self.originalEncoding: self.declaredHTMLEncoding = newCharset self._feed(self.declaredHTMLEncoding) raise StopParsing tag = self.unknown_starttag("meta", attrs) if tag and tagNeedsEncodingSubstitution: tag.containsSubstitutions = True class StopParsing(Exception): pass class ICantBelieveItsBeautifulSoup(BeautifulSoup): """The BeautifulSoup class is oriented towards skipping over common HTML errors like unclosed tags. However, sometimes it makes errors of its own. For instance, consider this fragment: <b>Foo<b>Bar</b></b> This is perfectly valid (if bizarre) HTML. However, the BeautifulSoup class will implicitly close the first b tag when it encounters the second 'b'. It will think the author wrote "<b>Foo<b>Bar", and didn't close the first 'b' tag, because there's no real-world reason to bold something that's already bold. When it encounters '</b></b>' it will close two more 'b' tags, for a grand total of three tags closed instead of two. This can throw off the rest of your document structure. The same is true of a number of other tags, listed below. It's much more common for someone to forget to close a 'b' tag than to actually use nested 'b' tags, and the BeautifulSoup class handles the common case. This class handles the not-co-common case: where you can't believe someone wrote what they did, but it's valid HTML and BeautifulSoup screwed up by assuming it wouldn't be.""" I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \ ['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong', 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b', 'big'] I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript'] NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS, I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS, I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS) class MinimalSoup(BeautifulSoup): """The MinimalSoup class is for parsing HTML that contains pathologically bad markup. It makes no assumptions about tag nesting, but it does know which tags are self-closing, that <script> tags contain Javascript and should not be parsed, that META tags may contain encoding information, and so on. This also makes it better for subclassing than BeautifulStoneSoup or BeautifulSoup.""" RESET_NESTING_TAGS = buildTagMap('noscript') NESTABLE_TAGS = {} class BeautifulSOAP(BeautifulStoneSoup): """This class will push a tag with only a single string child into the tag's parent as an attribute. The attribute's name is the tag name, and the value is the string child. An example should give the flavor of the change: <foo><bar>baz</bar></foo> => <foo bar="baz"><bar>baz</bar></foo> You can then access fooTag['bar'] instead of fooTag.barTag.string. This is, of course, useful for scraping structures that tend to use subelements instead of attributes, such as SOAP messages. Note that it modifies its input, so don't print the modified version out. I'm not sure how many people really want to use this class; let me know if you do. Mainly I like the name.""" def popTag(self): if len(self.tagStack) > 1: tag = self.tagStack[-1] parent = self.tagStack[-2] parent._getAttrMap() if (isinstance(tag, Tag) and len(tag.contents) == 1 and isinstance(tag.contents[0], NavigableString) and not parent.attrMap.has_key(tag.name)): parent[tag.name] = tag.contents[0] BeautifulStoneSoup.popTag(self) #Enterprise class names! It has come to our attention that some people #think the names of the Beautiful Soup parser classes are too silly #and "unprofessional" for use in enterprise screen-scraping. We feel #your pain! For such-minded folk, the Beautiful Soup Consortium And #All-Night Kosher Bakery recommends renaming this file to #"RobustParser.py" (or, in cases of extreme enterprisness, #"RobustParserBeanInterface.class") and using the following #enterprise-friendly class aliases: class RobustXMLParser(BeautifulStoneSoup): pass class RobustHTMLParser(BeautifulSoup): pass class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup): pass class RobustInsanelyWackAssHTMLParser(MinimalSoup): pass class SimplifyingSOAPParser(BeautifulSOAP): pass ###################################################### # # Bonus library: Unicode, Dammit # # This class forces XML data into a standard format (usually to UTF-8 # or Unicode). It is heavily based on code from Mark Pilgrim's # Universal Feed Parser. It does not rewrite the XML or HTML to # reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi # (XML) and BeautifulSoup.start_meta (HTML). # Autodetects character encodings. # Download from http://chardet.feedparser.org/ try: import chardet # import chardet.constants # chardet.constants._debug = 1 except: chardet = None chardet = None # cjkcodecs and iconv_codec make Python know about more character encodings. # Both are available from http://cjkpython.i18n.org/ # They're built in if you use Python 2.4. try: import cjkcodecs.aliases except: pass try: import iconv_codec except: pass class UnicodeDammit: """A class for detecting the encoding of a *ML document and converting it to a Unicode string. If the source encoding is windows-1252, can replace MS smart quotes with their HTML or XML equivalents.""" # This dictionary maps commonly seen values for "charset" in HTML # meta tags to the corresponding Python codec names. It only covers # values that aren't in Python's aliases and can't be determined # by the heuristics in find_codec. CHARSET_ALIASES = { "macintosh" : "mac-roman", "x-sjis" : "shift-jis" } def __init__(self, markup, overrideEncodings=[], smartQuotesTo='xml'): self.markup, documentEncoding, sniffedEncoding = \ self._detectEncoding(markup) self.smartQuotesTo = smartQuotesTo self.triedEncodings = [] if markup == '' or isinstance(markup, unicode): self.originalEncoding = None self.unicode = unicode(markup) return u = None for proposedEncoding in overrideEncodings: u = self._convertFrom(proposedEncoding) if u: break if not u: for proposedEncoding in (documentEncoding, sniffedEncoding): u = self._convertFrom(proposedEncoding) if u: break # If no luck and we have auto-detection library, try that: if not u and chardet and not isinstance(self.markup, unicode): u = self._convertFrom(chardet.detect(self.markup)['encoding']) # As a last resort, try utf-8 and windows-1252: if not u: for proposed_encoding in ("utf-8", "windows-1252"): u = self._convertFrom(proposed_encoding) if u: break self.unicode = u if not u: self.originalEncoding = None def _subMSChar(self, orig): """Changes a MS smart quote character to an XML or HTML entity.""" sub = self.MS_CHARS.get(orig) if type(sub) == types.TupleType: if self.smartQuotesTo == 'xml': sub = '&#x%s;' % sub[1] else: sub = '&%s;' % sub[0] return sub def _convertFrom(self, proposed): proposed = self.find_codec(proposed) if not proposed or proposed in self.triedEncodings: return None self.triedEncodings.append(proposed) markup = self.markup # Convert smart quotes to HTML if coming from an encoding # that might have them. if self.smartQuotesTo and proposed.lower() in("windows-1252", "iso-8859-1", "iso-8859-2"): markup = re.compile("([\x80-\x9f])").sub \ (lambda(x): self._subMSChar(x.group(1)), markup) try: # print "Trying to convert document to %s" % proposed u = self._toUnicode(markup, proposed) self.markup = u self.originalEncoding = proposed except Exception, e: # print "That didn't work!" # print e return None #print "Correct encoding: %s" % proposed return self.markup def _toUnicode(self, data, encoding): '''Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == '\xfe\xff') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16be' data = data[2:] elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16le' data = data[2:] elif data[:3] == '\xef\xbb\xbf': encoding = 'utf-8' data = data[3:] elif data[:4] == '\x00\x00\xfe\xff': encoding = 'utf-32be' data = data[4:] elif data[:4] == '\xff\xfe\x00\x00': encoding = 'utf-32le' data = data[4:] newdata = unicode(data, encoding) return newdata def _detectEncoding(self, xml_data): """Given a document, tries to detect its XML encoding.""" xml_encoding = sniffed_xml_encoding = None try: if xml_data[:4] == '\x4c\x6f\xa7\x94': # EBCDIC xml_data = self._ebcdic_to_ascii(xml_data) elif xml_data[:4] == '\x00\x3c\x00\x3f': # UTF-16BE sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \ and (xml_data[2:4] != '\x00\x00'): # UTF-16BE with BOM sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x3f\x00': # UTF-16LE sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data, 'utf-16le').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \ (xml_data[2:4] != '\x00\x00'): # UTF-16LE with BOM sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8') elif xml_data[:4] == '\x00\x00\x00\x3c': # UTF-32BE sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data, 'utf-32be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x00\x00': # UTF-32LE sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data, 'utf-32le').encode('utf-8') elif xml_data[:4] == '\x00\x00\xfe\xff': # UTF-32BE with BOM sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8') elif xml_data[:4] == '\xff\xfe\x00\x00': # UTF-32LE with BOM sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8') elif xml_data[:3] == '\xef\xbb\xbf': # UTF-8 with BOM sniffed_xml_encoding = 'utf-8' xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8') else: sniffed_xml_encoding = 'ascii' pass xml_encoding_match = re.compile \ ('^<\?.*encoding=[\'"](.*?)[\'"].*\?>')\ .match(xml_data) except: xml_encoding_match = None if xml_encoding_match: xml_encoding = xml_encoding_match.groups()[0].lower() if sniffed_xml_encoding and \ (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16')): xml_encoding = sniffed_xml_encoding return xml_data, xml_encoding, sniffed_xml_encoding def find_codec(self, charset): return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \ or (charset and self._codec(charset.replace("-", ""))) \ or (charset and self._codec(charset.replace("-", "_"))) \ or charset def _codec(self, charset): if not charset: return charset codec = None try: codecs.lookup(charset) codec = charset except LookupError: pass return codec EBCDIC_TO_ASCII_MAP = None def _ebcdic_to_ascii(self, s): c = self.__class__ if not c.EBCDIC_TO_ASCII_MAP: emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15, 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31, 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7, 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26, 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33, 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94, 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63, 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34, 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200, 201,202,106,107,108,109,110,111,112,113,114,203,204,205, 206,207,208,209,126,115,116,117,118,119,120,121,122,210, 211,212,213,214,215,216,217,218,219,220,221,222,223,224, 225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72, 73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81, 82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89, 90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57, 250,251,252,253,254,255) import string c.EBCDIC_TO_ASCII_MAP = string.maketrans( \ ''.join(map(chr, range(256))), ''.join(map(chr, emap))) return s.translate(c.EBCDIC_TO_ASCII_MAP) MS_CHARS = { '\x80' : ('euro', '20AC'), '\x81' : ' ', '\x82' : ('sbquo', '201A'), '\x83' : ('fnof', '192'), '\x84' : ('bdquo', '201E'), '\x85' : ('hellip', '2026'), '\x86' : ('dagger', '2020'), '\x87' : ('Dagger', '2021'), '\x88' : ('circ', '2C6'), '\x89' : ('permil', '2030'), '\x8A' : ('Scaron', '160'), '\x8B' : ('lsaquo', '2039'), '\x8C' : ('OElig', '152'), '\x8D' : '?', '\x8E' : ('#x17D', '17D'), '\x8F' : '?', '\x90' : '?', '\x91' : ('lsquo', '2018'), '\x92' : ('rsquo', '2019'), '\x93' : ('ldquo', '201C'), '\x94' : ('rdquo', '201D'), '\x95' : ('bull', '2022'), '\x96' : ('ndash', '2013'), '\x97' : ('mdash', '2014'), '\x98' : ('tilde', '2DC'), '\x99' : ('trade', '2122'), '\x9a' : ('scaron', '161'), '\x9b' : ('rsaquo', '203A'), '\x9c' : ('oelig', '153'), '\x9d' : '?', '\x9e' : ('#x17E', '17E'), '\x9f' : ('Yuml', ''),} ####################################################################### #By default, act as an HTML pretty-printer. if __name__ == '__main__': import sys soup = BeautifulSoup(sys.stdin.read()) print soup.prettify()
sdpython/cvxpy
refs/heads/master
cvxpy/tests/test_curvature.py
11
""" Copyright 2013 Steven Diamond This file is part of CVXPY. CVXPY 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. CVXPY 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 CVXPY. If not, see <http://www.gnu.org/licenses/>. """ from cvxpy.utilities import Curvature from cvxpy.utilities import Sign from nose.tools import assert_equals class TestCurvature(object): """ Unit tests for the expression/curvature class. """ def test_add(self): assert_equals(Curvature.CONSTANT + Curvature.CONVEX, Curvature.CONVEX) assert_equals(Curvature.UNKNOWN + Curvature.CONCAVE, Curvature.UNKNOWN) assert_equals(Curvature.CONVEX + Curvature.CONCAVE, Curvature.UNKNOWN) assert_equals(Curvature.CONVEX + Curvature.CONVEX, Curvature.CONVEX) assert_equals(Curvature.AFFINE + Curvature.CONCAVE, Curvature.CONCAVE) def test_sub(self): assert_equals(Curvature.CONSTANT - Curvature.CONVEX, Curvature.CONCAVE) assert_equals(Curvature.UNKNOWN - Curvature.CONCAVE, Curvature.UNKNOWN) assert_equals(Curvature.CONVEX - Curvature.CONCAVE, Curvature.CONVEX) assert_equals(Curvature.CONVEX - Curvature.CONVEX, Curvature.UNKNOWN) assert_equals(Curvature.AFFINE - Curvature.CONCAVE, Curvature.CONVEX) def test_sign_mult(self): assert_equals(Curvature.sign_mul(Sign.ZERO, Curvature.CONVEX), Curvature.CONSTANT) assert_equals(Curvature.sign_mul(Sign.NEGATIVE, Curvature.CONVEX), Curvature.CONCAVE) assert_equals(Curvature.sign_mul(Sign.NEGATIVE, Curvature.CONCAVE), Curvature.CONVEX) assert_equals(Curvature.sign_mul(Sign.NEGATIVE, Curvature.UNKNOWN), Curvature.UNKNOWN) assert_equals(Curvature.sign_mul(Sign.POSITIVE, Curvature.AFFINE), Curvature.AFFINE) assert_equals(Curvature.sign_mul(Sign.POSITIVE, Curvature.CONCAVE), Curvature.CONCAVE) assert_equals(Curvature.sign_mul(Sign.UNKNOWN, Curvature.CONSTANT), Curvature.CONSTANT) assert_equals(Curvature.sign_mul(Sign.UNKNOWN, Curvature.CONCAVE), Curvature.UNKNOWN) def test_neg(self): assert_equals(-Curvature.CONVEX, Curvature.CONCAVE) assert_equals(-Curvature.AFFINE, Curvature.AFFINE) # Tests the is_affine, is_convex, and is_concave methods def test_is_curvature(self): assert Curvature.CONSTANT.is_affine() assert Curvature.AFFINE.is_affine() assert not Curvature.CONVEX.is_affine() assert not Curvature.CONCAVE.is_affine() assert not Curvature.UNKNOWN.is_affine() assert Curvature.CONSTANT.is_convex() assert Curvature.AFFINE.is_convex() assert Curvature.CONVEX.is_convex() assert not Curvature.CONCAVE.is_convex() assert not Curvature.UNKNOWN.is_convex() assert Curvature.CONSTANT.is_concave() assert Curvature.AFFINE.is_concave() assert not Curvature.CONVEX.is_concave() assert Curvature.CONCAVE.is_concave() assert not Curvature.UNKNOWN.is_concave()
moble/sympy
refs/heads/master
sympy/physics/tests/test_pring.py
98
from sympy.physics.pring import wavefunction, energy from sympy.core.compatibility import range from sympy import pi, integrate, sqrt, exp, simplify, I from sympy.abc import m, x, r from sympy.physics.quantum.constants import hbar def test_wavefunction(): Psi = { 0: (1/sqrt(2 * pi)), 1: (1/sqrt(2 * pi)) * exp(I * x), 2: (1/sqrt(2 * pi)) * exp(2 * I * x), 3: (1/sqrt(2 * pi)) * exp(3 * I * x) } for n in Psi: assert simplify(wavefunction(n, x) - Psi[n]) == 0 def test_norm(n=1): # Maximum "n" which is tested: for i in range(n + 1): assert integrate( wavefunction(i, x) * wavefunction(-i, x), (x, 0, 2 * pi)) == 1 def test_orthogonality(n=1): # Maximum "n" which is tested: for i in range(n + 1): for j in range(i+1, n+1): assert integrate( wavefunction(i, x) * wavefunction(j, x), (x, 0, 2 * pi)) == 0 def test_energy(n=1): # Maximum "n" which is tested: for i in range(n+1): assert simplify( energy(i, m, r) - ((i**2 * hbar**2) / (2 * m * r**2))) == 0
datakortet/django-cms
refs/heads/master
cms/plugins/text/widgets/tinymce_widget.py
6
from cms.utils import cms_static_url from cms.utils.conf import get_cms_setting from django.forms.widgets import flatatt from django.template.defaultfilters import escape from django.template.loader import render_to_string from django.utils import simplejson from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe from django.utils.translation import get_language from tinymce.widgets import TinyMCE, get_language_config import cms.plugins.text.settings import tinymce.settings class TinyMCEEditor(TinyMCE): def __init__(self, installed_plugins=None, **kwargs): super(TinyMCEEditor, self).__init__(**kwargs) self.installed_plugins = installed_plugins def render_additions(self, name, value, attrs=None): language = get_language() context = { 'name': name, 'language': language, 'CMS_MEDIA_URL': get_cms_setting('MEDIA_URL'), 'installed_plugins': self.installed_plugins, } return mark_safe(render_to_string( 'cms/plugins/widgets/tinymce.html', context)) def _media(self): media = super(TinyMCEEditor, self)._media() media.add_js([cms_static_url(path) for path in ( 'js/tinymce.placeholdereditor.js', 'js/libs/jquery.ui.core.js', 'js/placeholder_editor_registry.js', )]) media.add_css({ "all": [ cms_static_url(path) for path in ('css/jquery/cupertino/jquery-ui.css', 'css/tinymce_toolbar.css') ] }) return media media = property(_media) def render(self, name, value, attrs=None): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs) final_attrs['name'] = name assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'" mce_config = cms.plugins.text.settings.TINYMCE_CONFIG.copy() mce_config.update(get_language_config(self.content_language)) if tinymce.settings.USE_FILEBROWSER: mce_config['file_browser_callback'] = "djangoFileBrowser" mce_config.update(self.mce_attrs) mce_config['mode'] = 'exact' mce_config['elements'] = final_attrs['id'] mce_config['strict_loading_mode'] = 1 plugins = mce_config.get("plugins", "") if len(plugins): plugins += "," plugins += "-cmsplugins" mce_config['plugins'] = plugins if mce_config['theme'] == "simple": mce_config['theme'] = "advanced" # Add cmsplugin to first toolbar, if not already present all_tools = [] idx = 0 while True: idx += 1 buttons = mce_config.get('theme_advanced_buttons%d' % (idx,), None) if buttons is None: break all_tools.extend(buttons.split(',')) if 'cmsplugins' not in all_tools and 'cmspluginsedit' not in all_tools: mce_config['theme_advanced_buttons1_add_before'] = "cmsplugins,cmspluginsedit" json = simplejson.dumps(mce_config) html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))] if tinymce.settings.USE_COMPRESSOR: compressor_config = { 'plugins': mce_config.get('plugins', ''), 'themes': mce_config.get('theme', 'advanced'), 'languages': mce_config.get('language', ''), 'diskcache': True, 'debug': False, } c_json = simplejson.dumps(compressor_config) html.append(u'<script type="text/javascript">//<![CDATA[\ntinyMCE_GZ.init(%s);\n//]]></script>' % (c_json)) html.append(u'<script type="text/javascript">//<![CDATA[\n%s;\ntinyMCE.init(%s);\n//]]></script>' % (self.render_additions(name, value, attrs), json)) return mark_safe(u'\n'.join(html))
HuimingCheng/AutoGrading
refs/heads/master
learning/web_Haotian/venv/Lib/site-packages/click/_winconsole.py
197
# -*- coding: utf-8 -*- # This module is based on the excellent work by Adam Bartoš who # provided a lot of what went into the implementation here in # the discussion to issue1602 in the Python bug tracker. # # There are some general differences in regards to how this works # compared to the original patches as we do not need to patch # the entire interpreter but just work in our little world of # echo and prmopt. import io import os import sys import zlib import time import ctypes import msvcrt from click._compat import _NonClosingTextIOWrapper, text_type, PY2 from ctypes import byref, POINTER, c_int, c_char, c_char_p, \ c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE try: from ctypes import pythonapi PyObject_GetBuffer = pythonapi.PyObject_GetBuffer PyBuffer_Release = pythonapi.PyBuffer_Release except ImportError: pythonapi = None from ctypes.wintypes import LPWSTR, LPCWSTR c_ssize_p = POINTER(c_ssize_t) kernel32 = windll.kernel32 GetStdHandle = kernel32.GetStdHandle ReadConsoleW = kernel32.ReadConsoleW WriteConsoleW = kernel32.WriteConsoleW GetLastError = kernel32.GetLastError GetCommandLineW = WINFUNCTYPE(LPWSTR)( ('GetCommandLineW', windll.kernel32)) CommandLineToArgvW = WINFUNCTYPE( POINTER(LPWSTR), LPCWSTR, POINTER(c_int))( ('CommandLineToArgvW', windll.shell32)) STDIN_HANDLE = GetStdHandle(-10) STDOUT_HANDLE = GetStdHandle(-11) STDERR_HANDLE = GetStdHandle(-12) PyBUF_SIMPLE = 0 PyBUF_WRITABLE = 1 ERROR_SUCCESS = 0 ERROR_NOT_ENOUGH_MEMORY = 8 ERROR_OPERATION_ABORTED = 995 STDIN_FILENO = 0 STDOUT_FILENO = 1 STDERR_FILENO = 2 EOF = b'\x1a' MAX_BYTES_WRITTEN = 32767 class Py_buffer(ctypes.Structure): _fields_ = [ ('buf', c_void_p), ('obj', py_object), ('len', c_ssize_t), ('itemsize', c_ssize_t), ('readonly', c_int), ('ndim', c_int), ('format', c_char_p), ('shape', c_ssize_p), ('strides', c_ssize_p), ('suboffsets', c_ssize_p), ('internal', c_void_p) ] if PY2: _fields_.insert(-1, ('smalltable', c_ssize_t * 2)) # On PyPy we cannot get buffers so our ability to operate here is # serverly limited. if pythonapi is None: get_buffer = None else: def get_buffer(obj, writable=False): buf = Py_buffer() flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE PyObject_GetBuffer(py_object(obj), byref(buf), flags) try: buffer_type = c_char * buf.len return buffer_type.from_address(buf.buf) finally: PyBuffer_Release(byref(buf)) class _WindowsConsoleRawIOBase(io.RawIOBase): def __init__(self, handle): self.handle = handle def isatty(self): io.RawIOBase.isatty(self) return True class _WindowsConsoleReader(_WindowsConsoleRawIOBase): def readable(self): return True def readinto(self, b): bytes_to_be_read = len(b) if not bytes_to_be_read: return 0 elif bytes_to_be_read % 2: raise ValueError('cannot read odd number of bytes from ' 'UTF-16-LE encoded console') buffer = get_buffer(b, writable=True) code_units_to_be_read = bytes_to_be_read // 2 code_units_read = c_ulong() rv = ReadConsoleW(self.handle, buffer, code_units_to_be_read, byref(code_units_read), None) if GetLastError() == ERROR_OPERATION_ABORTED: # wait for KeyboardInterrupt time.sleep(0.1) if not rv: raise OSError('Windows error: %s' % GetLastError()) if buffer[0] == EOF: return 0 return 2 * code_units_read.value class _WindowsConsoleWriter(_WindowsConsoleRawIOBase): def writable(self): return True @staticmethod def _get_error_message(errno): if errno == ERROR_SUCCESS: return 'ERROR_SUCCESS' elif errno == ERROR_NOT_ENOUGH_MEMORY: return 'ERROR_NOT_ENOUGH_MEMORY' return 'Windows error %s' % errno def write(self, b): bytes_to_be_written = len(b) buf = get_buffer(b) code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2 code_units_written = c_ulong() WriteConsoleW(self.handle, buf, code_units_to_be_written, byref(code_units_written), None) bytes_written = 2 * code_units_written.value if bytes_written == 0 and bytes_to_be_written > 0: raise OSError(self._get_error_message(GetLastError())) return bytes_written class ConsoleStream(object): def __init__(self, text_stream, byte_stream): self._text_stream = text_stream self.buffer = byte_stream @property def name(self): return self.buffer.name def write(self, x): if isinstance(x, text_type): return self._text_stream.write(x) try: self.flush() except Exception: pass return self.buffer.write(x) def writelines(self, lines): for line in lines: self.write(line) def __getattr__(self, name): return getattr(self._text_stream, name) def isatty(self): return self.buffer.isatty() def __repr__(self): return '<ConsoleStream name=%r encoding=%r>' % ( self.name, self.encoding, ) def _get_text_stdin(buffer_stream): text_stream = _NonClosingTextIOWrapper( io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)), 'utf-16-le', 'strict', line_buffering=True) return ConsoleStream(text_stream, buffer_stream) def _get_text_stdout(buffer_stream): text_stream = _NonClosingTextIOWrapper( _WindowsConsoleWriter(STDOUT_HANDLE), 'utf-16-le', 'strict', line_buffering=True) return ConsoleStream(text_stream, buffer_stream) def _get_text_stderr(buffer_stream): text_stream = _NonClosingTextIOWrapper( _WindowsConsoleWriter(STDERR_HANDLE), 'utf-16-le', 'strict', line_buffering=True) return ConsoleStream(text_stream, buffer_stream) if PY2: def _hash_py_argv(): return zlib.crc32('\x00'.join(sys.argv[1:])) _initial_argv_hash = _hash_py_argv() def _get_windows_argv(): argc = c_int(0) argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc)) argv = [argv_unicode[i] for i in range(0, argc.value)] if not hasattr(sys, 'frozen'): argv = argv[1:] while len(argv) > 0: arg = argv[0] if not arg.startswith('-') or arg == '-': break argv = argv[1:] if arg.startswith(('-c', '-m')): break return argv[1:] _stream_factories = { 0: _get_text_stdin, 1: _get_text_stdout, 2: _get_text_stderr, } def _get_windows_console_stream(f, encoding, errors): if get_buffer is not None and \ encoding in ('utf-16-le', None) \ and errors in ('strict', None) and \ hasattr(f, 'isatty') and f.isatty(): func = _stream_factories.get(f.fileno()) if func is not None: if not PY2: f = getattr(f, 'buffer') if f is None: return None else: # If we are on Python 2 we need to set the stream that we # deal with to binary mode as otherwise the exercise if a # bit moot. The same problems apply as for # get_binary_stdin and friends from _compat. msvcrt.setmode(f.fileno(), os.O_BINARY) return func(f)
geminateCoder/Character-Archive-Website
refs/heads/master
Lib/site-packages/sqlalchemy/engine/url.py
34
# engine/url.py # Copyright (C) 2005-2016 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 """Provides the :class:`~sqlalchemy.engine.url.URL` class which encapsulates information about a database connection specification. The URL object is created automatically when :func:`~sqlalchemy.engine.create_engine` is called with a string argument; alternatively, the URL is a public-facing construct which can be used directly and is also accepted directly by ``create_engine()``. """ import re from .. import exc, util from . import Dialect from ..dialects import registry class URL(object): """ Represent the components of a URL used to connect to a database. This object is suitable to be passed directly to a :func:`~sqlalchemy.create_engine` call. The fields of the URL are parsed from a string by the :func:`.make_url` function. the string format of the URL is an RFC-1738-style string. All initialization parameters are available as public attributes. :param drivername: the name of the database backend. This name will correspond to a module in sqlalchemy/databases or a third party plug-in. :param username: The user name. :param password: database password. :param host: The name of the host. :param port: The port number. :param database: The database name. :param query: A dictionary of options to be passed to the dialect and/or the DBAPI upon connect. """ def __init__(self, drivername, username=None, password=None, host=None, port=None, database=None, query=None): self.drivername = drivername self.username = username self.password = password self.host = host if port is not None: self.port = int(port) else: self.port = None self.database = database self.query = query or {} def __to_string__(self, hide_password=True): s = self.drivername + "://" if self.username is not None: s += _rfc_1738_quote(self.username) if self.password is not None: s += ':' + ('***' if hide_password else _rfc_1738_quote(self.password)) s += "@" if self.host is not None: if ':' in self.host: s += "[%s]" % self.host else: s += self.host if self.port is not None: s += ':' + str(self.port) if self.database is not None: s += '/' + self.database if self.query: keys = list(self.query) keys.sort() s += '?' + "&".join("%s=%s" % (k, self.query[k]) for k in keys) return s def __str__(self): return self.__to_string__(hide_password=False) def __repr__(self): return self.__to_string__() def __hash__(self): return hash(str(self)) def __eq__(self, other): return \ isinstance(other, URL) and \ self.drivername == other.drivername and \ self.username == other.username and \ self.password == other.password and \ self.host == other.host and \ self.database == other.database and \ self.query == other.query def get_backend_name(self): if '+' not in self.drivername: return self.drivername else: return self.drivername.split('+')[0] def get_driver_name(self): if '+' not in self.drivername: return self.get_dialect().driver else: return self.drivername.split('+')[1] def _get_entrypoint(self): """Return the "entry point" dialect class. This is normally the dialect itself except in the case when the returned class implements the get_dialect_cls() method. """ if '+' not in self.drivername: name = self.drivername else: name = self.drivername.replace('+', '.') cls = registry.load(name) # check for legacy dialects that # would return a module with 'dialect' as the # actual class if hasattr(cls, 'dialect') and \ isinstance(cls.dialect, type) and \ issubclass(cls.dialect, Dialect): return cls.dialect else: return cls def get_dialect(self): """Return the SQLAlchemy database dialect class corresponding to this URL's driver name. """ entrypoint = self._get_entrypoint() dialect_cls = entrypoint.get_dialect_cls(self) return dialect_cls def translate_connect_args(self, names=[], **kw): """Translate url attributes into a dictionary of connection arguments. Returns attributes of this url (`host`, `database`, `username`, `password`, `port`) as a plain dictionary. The attribute names are used as the keys by default. Unset or false attributes are omitted from the final dictionary. :param \**kw: Optional, alternate key names for url attributes. :param names: Deprecated. Same purpose as the keyword-based alternate names, but correlates the name to the original positionally. """ translated = {} attribute_names = ['host', 'database', 'username', 'password', 'port'] for sname in attribute_names: if names: name = names.pop(0) elif sname in kw: name = kw[sname] else: name = sname if name is not None and getattr(self, sname, False): translated[name] = getattr(self, sname) return translated def make_url(name_or_url): """Given a string or unicode instance, produce a new URL instance. The given string is parsed according to the RFC 1738 spec. If an existing URL object is passed, just returns the object. """ if isinstance(name_or_url, util.string_types): return _parse_rfc1738_args(name_or_url) else: return name_or_url def _parse_rfc1738_args(name): pattern = re.compile(r''' (?P<name>[\w\+]+):// (?: (?P<username>[^:/]*) (?::(?P<password>.*))? @)? (?: (?: \[(?P<ipv6host>[^/]+)\] | (?P<ipv4host>[^/:]+) )? (?::(?P<port>[^/]*))? )? (?:/(?P<database>.*))? ''', re.X) m = pattern.match(name) if m is not None: components = m.groupdict() if components['database'] is not None: tokens = components['database'].split('?', 2) components['database'] = tokens[0] query = ( len(tokens) > 1 and dict(util.parse_qsl(tokens[1]))) or None if util.py2k and query is not None: query = dict((k.encode('ascii'), query[k]) for k in query) else: query = None components['query'] = query if components['username'] is not None: components['username'] = _rfc_1738_unquote(components['username']) if components['password'] is not None: components['password'] = _rfc_1738_unquote(components['password']) ipv4host = components.pop('ipv4host') ipv6host = components.pop('ipv6host') components['host'] = ipv4host or ipv6host name = components.pop('name') return URL(name, **components) else: raise exc.ArgumentError( "Could not parse rfc1738 URL from string '%s'" % name) def _rfc_1738_quote(text): return re.sub(r'[:@/]', lambda m: "%%%X" % ord(m.group(0)), text) def _rfc_1738_unquote(text): return util.unquote(text) def _parse_keyvalue_args(name): m = re.match(r'(\w+)://(.*)', name) if m is not None: (name, args) = m.group(1, 2) opts = dict(util.parse_qsl(args)) return URL(name, *opts) else: return None
LingxiaoJIA/gem5
refs/heads/master
src/mem/cache/BaseCache.py
4
# Copyright (c) 2012-2013 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Copyright (c) 2005-2007 The Regents of The University of Michigan # 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 the copyright holders 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. # # Authors: Nathan Binkert from m5.params import * from m5.proxy import * from MemObject import MemObject from Prefetcher import BasePrefetcher from Tags import * class BaseCache(MemObject): type = 'BaseCache' cxx_header = "mem/cache/base.hh" assoc = Param.Int("associativity") hit_latency = Param.Cycles("The hit latency for this cache") response_latency = Param.Cycles( "Additional cache latency for the return path to core on a miss"); max_miss_count = Param.Counter(0, "number of misses to handle before calling exit") mshrs = Param.Int("number of MSHRs (max outstanding requests)") demand_mshr_reserve = Param.Int(1, "mshrs to reserve for demand access") size = Param.MemorySize("capacity in bytes") forward_snoops = Param.Bool(True, "forward snoops from mem side to cpu side") is_top_level = Param.Bool(False, "Is this cache at the top level (e.g. L1)") tgts_per_mshr = Param.Int("max number of accesses per MSHR") two_queue = Param.Bool(False, "whether the lifo should have two queue replacement") write_buffers = Param.Int(8, "number of write buffers") prefetch_on_access = Param.Bool(False, "notify the hardware prefetcher on every access (not just misses)") prefetcher = Param.BasePrefetcher(NULL,"Prefetcher attached to cache") cpu_side = SlavePort("Port on side closer to CPU") mem_side = MasterPort("Port on side closer to MEM") addr_ranges = VectorParam.AddrRange([AllMemory], "The address range for the CPU-side port") system = Param.System(Parent.any, "System we belong to") sequential_access = Param.Bool(False, "Whether to access tags and data sequentially") tags = Param.BaseTags(LRU(), "Tag Store for LRU caches")
CourseTalk/edx-platform
refs/heads/master
common/lib/symmath/symmath/test_symmath_check.py
166
from unittest import TestCase from .symmath_check import symmath_check class SymmathCheckTest(TestCase): def test_symmath_check_integers(self): number_list = [i for i in range(-100, 100)] self._symmath_check_numbers(number_list) def test_symmath_check_floats(self): number_list = [i + 0.01 for i in range(-100, 100)] self._symmath_check_numbers(number_list) def test_symmath_check_same_symbols(self): expected_str = "x+2*y" dynamath = ''' <math xmlns="http://www.w3.org/1998/Math/MathML"> <mstyle displaystyle="true"> <mrow> <mi>x</mi> <mo>+</mo> <mn>2</mn> <mo>*</mo> <mi>y</mi> </mrow> </mstyle> </math>'''.strip() # Expect that the exact same symbolic string is marked correct result = symmath_check(expected_str, expected_str, dynamath=[dynamath]) self.assertTrue('ok' in result and result['ok']) def test_symmath_check_equivalent_symbols(self): expected_str = "x+2*y" input_str = "x+y+y" dynamath = ''' <math xmlns="http://www.w3.org/1998/Math/MathML"> <mstyle displaystyle="true"> <mrow> <mi>x</mi> <mo>+</mo> <mi>y</mi> <mo>+</mo> <mi>y</mi> </mrow> </mstyle> </math>'''.strip() # Expect that equivalent symbolic strings are marked correct result = symmath_check(expected_str, input_str, dynamath=[dynamath]) self.assertTrue('ok' in result and result['ok']) def test_symmath_check_different_symbols(self): expected_str = "0" input_str = "x+y" dynamath = ''' <math xmlns="http://www.w3.org/1998/Math/MathML"> <mstyle displaystyle="true"> <mrow> <mi>x</mi> <mo>+</mo> <mi>y</mi> </mrow> </mstyle> </math>'''.strip() # Expect that an incorrect response is marked incorrect result = symmath_check(expected_str, input_str, dynamath=[dynamath]) self.assertTrue('ok' in result and not result['ok']) self.assertFalse('fail' in result['msg']) def _symmath_check_numbers(self, number_list): for n in number_list: # expect = ans, so should say the answer is correct expect = n ans = n result = symmath_check(str(expect), str(ans)) self.assertTrue('ok' in result and result['ok'], "%f should == %f" % (expect, ans)) # Change expect so that it != ans expect += 0.1 result = symmath_check(str(expect), str(ans)) self.assertTrue('ok' in result and not result['ok'], "%f should != %f" % (expect, ans))
harrisonfeng/locust
refs/heads/master
locust/test/test_taskratio.py
32
import unittest from locust.core import Locust, TaskSet, task from locust.inspectlocust import get_task_ratio_dict class TestTaskRatio(unittest.TestCase): def test_task_ratio_command(self): class Tasks(TaskSet): @task def root_task1(self): pass @task class SubTasks(TaskSet): @task def task1(self): pass @task def task2(self): pass class User(Locust): task_set = Tasks ratio_dict = get_task_ratio_dict(User.task_set.tasks, total=True) self.assertEqual({ 'SubTasks': { 'tasks': { 'task1': {'ratio': 0.25}, 'task2': {'ratio': 0.25} }, 'ratio': 0.5 }, 'root_task1': {'ratio': 0.5} }, ratio_dict) def test_task_ratio_command_with_locust_weight(self): class Tasks(TaskSet): @task(1) def task1(self): pass @task(3) def task3(self): pass class UnlikelyLocust(Locust): weight = 1 task_set = Tasks class MoreLikelyLocust(Locust): weight = 3 task_set = Tasks ratio_dict = get_task_ratio_dict([UnlikelyLocust, MoreLikelyLocust], total=True) self.assertEquals({ 'UnlikelyLocust': {'tasks': {'task1': {'ratio': 0.25*0.25}, 'task3': {'ratio': 0.25*0.75}}, 'ratio': 0.25}, 'MoreLikelyLocust': {'tasks': {'task1': {'ratio': 0.75*0.25}, 'task3': {'ratio': 0.75*0.75}}, 'ratio': 0.75} }, ratio_dict) unlikely = ratio_dict['UnlikelyLocust']['tasks'] likely = ratio_dict['MoreLikelyLocust']['tasks'] assert unlikely['task1']['ratio'] + unlikely['task3']['ratio'] + likely['task1']['ratio'] + likely['task3']['ratio'] == 1
chrispitzer/toucan-sam
refs/heads/master
toucansam/core/urls.py
1
from django.conf.urls import patterns, url from core import views urlpatterns = patterns('', url(r'^/?$', views.SongListView.as_view(), name='song_list'), url(r'^songs/?$', views.SongListView.as_view(), name='song_list'), url(r'^set_list/(?P<set_list_id>\d+|new)/?$', views.SetListView.as_view(), name='set_list'), url(r'^songs/(?P<song_id>[0-9]+)/??$', views.SongView.as_view(), name='song'), url(r'^songs/(?P<song_id>[0-9]+)/print/?$', views.PrintSongView.as_view(), name='print_song'), url(r'^set_list_list/', 'core.views.set_list_list', name='set_list_list'), url(r'^cheat_sheet/(?P<set_list_id>\d+)/?$', views.CheatSheetView.as_view(), name="cheat_sheet"), url(r'^print_songs_in/(?P<set_list_id>\d+)/?$', views.PrintSongsView.as_view(), name="print_songs_in"), url(r'^master_cheat_sheet/', views.CheatSheetView.as_view(), name="master_cheat_sheet"), url(r'^print_all_songs/', views.PrintSongsView.as_view(), name="print_all_songs"), url(r'^api/save_set_list/(?P<set_list_id>\d+|new)/?$', views.SetListAjax.as_view(), name="set_list_ajax"), url(r'^api/randocolor/?$', views.RandoColor.as_view(), name="rando_color"), url(r'^api/setlist_runtime/(?P<set_list_id>\d+|new)/?$', views.SetListSecondsjaxView.as_view(), name="set_list_time"), url(r'^api/add_to_setlist/(?P<set_list_id>\d+|new)/?$', views.UpdateSetListAjax.as_view(), name="add_to_setlist"), )
public-ink/public-ink
refs/heads/master
server/appengine/lib/graphql_relay/node/plural.py
2
from collections import OrderedDict from promise import Promise from graphql.type import ( GraphQLArgument, GraphQLList, GraphQLNonNull, GraphQLField ) def plural_identifying_root_field(arg_name, input_type, output_type, resolve_single_input, description=None): input_args = OrderedDict() input_args[arg_name] = GraphQLArgument( GraphQLNonNull( GraphQLList( GraphQLNonNull(input_type) ) ) ) def resolver(obj, args, context, info): inputs = args[arg_name] return Promise.all([ resolve_single_input(input, context, info) for input in inputs ]) return GraphQLField( GraphQLList(output_type), description=description, args=input_args, resolver=resolver )
KDra/SU2
refs/heads/master
TestCases/parallel_regression_AD.py
3
#!/usr/bin/env python ## \file parallel_regression.py # \brief Python script for automated regression testing of SU2 examples # \author A. Aranake, A. Campos, T. Economon, T. Lukaczyk, S. Padron # \version 5.0.0 "Raven" # # SU2 Lead Developers: Dr. Francisco Palacios (Francisco.D.Palacios@boeing.com). # Dr. Thomas D. Economon (economon@stanford.edu). # # SU2 Developers: Prof. Juan J. Alonso's group at Stanford University. # Prof. Piero Colonna's group at Delft University of Technology. # Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology. # Prof. Alberto Guardone's group at Polytechnic University of Milan. # Prof. Rafael Palacios' group at Imperial College London. # Prof. Edwin van der Weide's group at the University of Twente. # Prof. Vincent Terrapon's group at the University of Liege. # # Copyright (C) 2012-2017 SU2, the open-source CFD code. # # SU2 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. # # SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>. import sys from TestCase import TestCase def main(): '''This program runs SU2 and ensures that the output matches specified values. This will be used to do checks when code is pushed to github to make sure nothing is broken. ''' test_list = [] ##################################### ### Disc. adj. compressible Euler ### ##################################### # Inviscid NACA0012 discadj_naca0012 = TestCase('discadj_naca0012') discadj_naca0012.cfg_dir = "cont_adj_euler/naca0012" discadj_naca0012.cfg_file = "inv_NACA0012_discadj.cfg" discadj_naca0012.test_iter = 100 discadj_naca0012.test_vals = [-3.606963, -9.034619, -0.000000, 0.005688] #last 4 columns discadj_naca0012.su2_exec = "parallel_computation.py -f" discadj_naca0012.timeout = 1600 discadj_naca0012.tol = 0.00001 test_list.append(discadj_naca0012) #################################### ### Disc. adj. compressible RANS ### #################################### # Adjoint turbulent NACA0012 SA discadj_rans_naca0012_sa = TestCase('discadj_rans_naca0012_sa') discadj_rans_naca0012_sa.cfg_dir = "disc_adj_rans/naca0012" discadj_rans_naca0012_sa.cfg_file = "turb_NACA0012_sa.cfg" discadj_rans_naca0012_sa.test_iter = 10 discadj_rans_naca0012_sa.test_vals = [-1.751997, 0.485368, 0.182890, -0.000018] #last 4 columns discadj_rans_naca0012_sa.su2_exec = "parallel_computation.py -f" discadj_rans_naca0012_sa.timeout = 1600 discadj_rans_naca0012_sa.tol = 0.00001 test_list.append(discadj_rans_naca0012_sa) # Adjoint turbulent NACA0012 SST discadj_rans_naca0012_sst = TestCase('discadj_rans_naca0012_sst') discadj_rans_naca0012_sst.cfg_dir = "disc_adj_rans/naca0012" discadj_rans_naca0012_sst.cfg_file = "turb_NACA0012_sst.cfg" discadj_rans_naca0012_sst.test_iter = 10 discadj_rans_naca0012_sst.test_vals = [-1.655243, -0.507187, 0.129010, -0.000013] #last 4 columns discadj_rans_naca0012_sst.su2_exec = "parallel_computation.py -f" discadj_rans_naca0012_sst.timeout = 1600 discadj_rans_naca0012_sst.tol = 0.00001 test_list.append(discadj_rans_naca0012_sst) ####################################################### ### Unsteady Disc. adj. compressible RANS ### ####################################################### # Turbulent Cylinder discadj_cylinder = TestCase('unsteady_cylinder') discadj_cylinder.cfg_dir = "disc_adj_rans/cylinder" discadj_cylinder.cfg_file = "cylinder.cfg" discadj_cylinder.test_iter = 10 discadj_cylinder.test_vals = [3.522085, -1.787791, -0.012031, 0.000017] #last 4 columns discadj_cylinder.su2_exec = "parallel_computation.py -f" discadj_cylinder.timeout = 1600 discadj_cylinder.tol = 0.00001 discadj_cylinder.unsteady = True test_list.append(discadj_cylinder ) ###################################### ### RUN TESTS ### ###################################### pass_list = [ test.run_test() for test in test_list ] # Tests summary print '==================================================================' print 'Summary of the parallel tests' for i, test in enumerate(test_list): if (pass_list[i]): print ' passed - %s'%test.tag else: print '* FAILED - %s'%test.tag if all(pass_list): sys.exit(0) else: sys.exit(1) # done if __name__ == '__main__': main()
vorwerkc/pymatgen
refs/heads/master
pymatgen/util/tests/test_coord.py
5
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import random from pymatgen.core.lattice import Lattice from pymatgen.util.coord import * from pymatgen.util.testing import PymatgenTest class CoordUtilsTest(PymatgenTest): def test_get_linear_interpolated_value(self): xvals = [0, 1, 2, 3, 4, 5] yvals = [3, 6, 7, 8, 10, 12] self.assertEqual(get_linear_interpolated_value(xvals, yvals, 3.6), 9.2) self.assertRaises(ValueError, get_linear_interpolated_value, xvals, yvals, 6) def test_in_coord_list(self): coords = [[0, 0, 0], [0.5, 0.5, 0.5]] test_coord = [0.1, 0.1, 0.1] self.assertFalse(in_coord_list(coords, test_coord)) self.assertTrue(in_coord_list(coords, test_coord, atol=0.15)) self.assertFalse(in_coord_list([0.99, 0.99, 0.99], test_coord, atol=0.15)) def test_is_coord_subset(self): c1 = [0, 0, 0] c2 = [0, 1.2, -1] c3 = [3, 2, 1] c4 = [3 - 9e-9, 2 - 9e-9, 1 - 9e-9] self.assertTrue(is_coord_subset([c1, c2, c3], [c1, c4, c2])) self.assertTrue(is_coord_subset([c1], [c2, c1])) self.assertTrue(is_coord_subset([c1, c2], [c2, c1])) self.assertFalse(is_coord_subset([c1, c2], [c2, c3])) self.assertFalse(is_coord_subset([c1, c2], [c2])) def test_coord_list_mapping(self): c1 = [0, 0.124, 0] c2 = [0, 1.2, -1] c3 = [3, 2, 1] a = np.array([c1, c2]) b = np.array([c3, c2, c1]) inds = coord_list_mapping(a, b) self.assertTrue(np.allclose(a, b[inds])) self.assertRaises(Exception, coord_list_mapping, [c1, c2], [c2, c3]) self.assertRaises(Exception, coord_list_mapping, [c2], [c2, c2]) def test_coord_list_mapping_pbc(self): c1 = [0.1, 0.2, 0.3] c2 = [0.2, 0.3, 0.3] c3 = [0.5, 0.3, 0.6] c4 = [1.5, -0.7, -1.4] a = np.array([c1, c3, c2]) b = np.array([c4, c2, c1]) inds = coord_list_mapping_pbc(a, b) diff = a - b[inds] diff -= np.round(diff) self.assertTrue(np.allclose(diff, 0)) self.assertRaises(Exception, coord_list_mapping_pbc, [c1, c2], [c2, c3]) self.assertRaises(Exception, coord_list_mapping_pbc, [c2], [c2, c2]) def test_find_in_coord_list(self): coords = [[0, 0, 0], [0.5, 0.5, 0.5]] test_coord = [0.1, 0.1, 0.1] self.assertEqual(find_in_coord_list(coords, test_coord).size, 0) self.assertEqual(find_in_coord_list(coords, test_coord, atol=0.15)[0], 0) self.assertEqual(find_in_coord_list([0.99, 0.99, 0.99], test_coord, atol=0.15).size, 0) coords = [[0, 0, 0], [0.5, 0.5, 0.5], [0.1, 0.1, 0.1]] self.assertArrayEqual(find_in_coord_list(coords, test_coord, atol=0.15), [0, 2]) def test_all_distances(self): coords1 = [[0, 0, 0], [0.5, 0.5, 0.5]] coords2 = [[1, 2, -1], [1, 0, 0], [1, 0, 0]] result = [[2.44948974, 1, 1], [2.17944947, 0.8660254, 0.8660254]] self.assertArrayAlmostEqual(all_distances(coords1, coords2), result, 4) def test_pbc_diff(self): self.assertArrayAlmostEqual(pbc_diff([0.1, 0.1, 0.1], [0.3, 0.5, 0.9]), [-0.2, -0.4, 0.2]) self.assertArrayAlmostEqual(pbc_diff([0.9, 0.1, 1.01], [0.3, 0.5, 0.9]), [-0.4, -0.4, 0.11]) self.assertArrayAlmostEqual(pbc_diff([0.1, 0.6, 1.01], [0.6, 0.1, 0.9]), [-0.5, 0.5, 0.11]) self.assertArrayAlmostEqual(pbc_diff([100.1, 0.2, 0.3], [0123123.4, 0.5, 502312.6]), [-0.3, -0.3, -0.3]) def test_in_coord_list_pbc(self): coords = [[0, 0, 0], [0.5, 0.5, 0.5]] test_coord = [0.1, 0.1, 0.1] self.assertFalse(in_coord_list_pbc(coords, test_coord)) self.assertTrue(in_coord_list_pbc(coords, test_coord, atol=0.15)) test_coord = [0.99, 0.99, 0.99] self.assertFalse(in_coord_list_pbc(coords, test_coord, atol=0.01)) def test_find_in_coord_list_pbc(self): coords = [[0, 0, 0], [0.5, 0.5, 0.5]] test_coord = [0.1, 0.1, 0.1] self.assertEqual(find_in_coord_list_pbc(coords, test_coord).size, 0) self.assertEqual(find_in_coord_list_pbc(coords, test_coord, atol=0.15)[0], 0) test_coord = [0.99, 0.99, 0.99] self.assertEqual(find_in_coord_list_pbc(coords, test_coord, atol=0.02)[0], 0) test_coord = [-0.499, -0.499, -0.499] self.assertEqual(find_in_coord_list_pbc(coords, test_coord, atol=0.01)[0], 1) def test_is_coord_subset_pbc(self): c1 = [0, 0, 0] c2 = [0, 1.2, -1] c3 = [2.3, 0, 1] c4 = [1.3 - 9e-9, -1 - 9e-9, 1 - 9e-9] self.assertTrue(is_coord_subset_pbc([c1, c2, c3], [c1, c4, c2])) self.assertTrue(is_coord_subset_pbc([c1], [c2, c1])) self.assertTrue(is_coord_subset_pbc([c1, c2], [c2, c1])) self.assertFalse(is_coord_subset_pbc([c1, c2], [c2, c3])) self.assertFalse(is_coord_subset_pbc([c1, c2], [c2])) # test tolerances c5 = [0.1, 0.1, 0.2] atol1 = [0.25, 0.15, 0.15] atol2 = [0.15, 0.15, 0.25] self.assertFalse(is_coord_subset_pbc([c1], [c5], atol1)) self.assertTrue(is_coord_subset_pbc([c1], [c5], atol2)) # test mask mask1 = [[True]] self.assertFalse(is_coord_subset_pbc([c1], [c5], atol2, mask1)) mask2 = [[True, False]] self.assertTrue(is_coord_subset_pbc([c1], [c2, c1], mask=mask2)) self.assertFalse(is_coord_subset_pbc([c1], [c1, c2], mask=mask2)) mask3 = [[False, True]] self.assertFalse(is_coord_subset_pbc([c1], [c2, c1], mask=mask3)) self.assertTrue(is_coord_subset_pbc([c1], [c1, c2], mask=mask3)) def test_lattice_points_in_supercell(self): supercell = np.array([[1, 3, 5], [-3, 2, 3], [-5, 3, 1]]) points = lattice_points_in_supercell(supercell) self.assertAlmostEqual(len(points), abs(np.linalg.det(supercell))) self.assertGreaterEqual(np.min(points), -1e-10) self.assertLessEqual(np.max(points), 1 - 1e-10) supercell = np.array([[-5, -5, -3], [0, -4, -2], [0, -5, -2]]) points = lattice_points_in_supercell(supercell) self.assertAlmostEqual(len(points), abs(np.linalg.det(supercell))) self.assertGreaterEqual(np.min(points), -1e-10) self.assertLessEqual(np.max(points), 1 - 1e-10) def test_barycentric(self): # 2d test simplex1 = np.array([[0.3, 0.1], [0.2, -1.2], [1.3, 2.3]]) pts1 = np.array([[0.6, 0.1], [1.3, 2.3], [0.5, 0.5], [0.7, 1]]) output1 = barycentric_coords(pts1, simplex1) # do back conversion to cartesian o_dot_s = np.sum(output1[:, :, None] * simplex1[None, :, :], axis=1) self.assertTrue(np.allclose(pts1, o_dot_s)) # do 3d tests simplex2 = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 0]]) pts2 = np.array([[0, 0, 1], [0, 0.5, 0.5], [1.0 / 3, 1.0 / 3, 1.0 / 3]]) output2 = barycentric_coords(pts2, simplex2) self.assertTrue(np.allclose(output2[1], [0.5, 0.5, 0, 0])) # do back conversion to cartesian o_dot_s = np.sum(output2[:, :, None] * simplex2[None, :, :], axis=1) self.assertTrue(np.allclose(pts2, o_dot_s)) # test single point self.assertTrue(np.allclose(output2[2], barycentric_coords(pts2[2], simplex2))) def test_pbc_shortest_vectors(self): fcoords = np.array( [ [0.3, 0.3, 0.5], [0.1, 0.1, 0.3], [0.9, 0.9, 0.8], [0.1, 0.0, 0.5], [0.9, 0.7, 0.0], ] ) lattice = Lattice.from_parameters(8, 8, 4, 90, 76, 58) expected = np.array( [ [0.000, 3.015, 4.072, 3.519, 3.245], [3.015, 0.000, 3.207, 1.131, 4.453], [4.072, 3.207, 0.000, 2.251, 1.788], [3.519, 1.131, 2.251, 0.000, 3.852], ] ) vectors = pbc_shortest_vectors(lattice, fcoords[:-1], fcoords) dists = np.sum(vectors ** 2, axis=-1) ** 0.5 self.assertArrayAlmostEqual(dists, expected, 3) # now try with small loop threshold from pymatgen.util import coord prev_threshold = coord.LOOP_THRESHOLD coord.LOOP_THRESHOLD = 0 vectors = pbc_shortest_vectors(lattice, fcoords[:-1], fcoords) dists = np.sum(vectors ** 2, axis=-1) ** 0.5 self.assertArrayAlmostEqual(dists, expected, 3) coord.LOOP_THRESHOLD = prev_threshold def test_get_angle(self): v1 = (1, 0, 0) v2 = (1, 1, 1) self.assertAlmostEqual(get_angle(v1, v2), 54.7356103172) self.assertAlmostEqual(get_angle(v1, v2, units="radians"), 0.9553166181245092) class SimplexTest(PymatgenTest): def setUp(self): coords = [] coords.append([0, 0, 0]) coords.append([0, 1, 0]) coords.append([0, 0, 1]) coords.append([1, 0, 0]) self.simplex = Simplex(coords) def test_equal(self): c2 = list(self.simplex.coords) random.shuffle(c2) self.assertEqual(Simplex(c2), self.simplex) def test_in_simplex(self): self.assertTrue(self.simplex.in_simplex([0.1, 0.1, 0.1])) self.assertFalse(self.simplex.in_simplex([0.6, 0.6, 0.6])) for i in range(10): coord = np.random.random_sample(size=3) / 3 self.assertTrue(self.simplex.in_simplex(coord)) def test_2dtriangle(self): s = Simplex([[0, 1], [1, 1], [1, 0]]) self.assertArrayAlmostEqual(s.bary_coords([0.5, 0.5]), [0.5, 0, 0.5]) self.assertArrayAlmostEqual(s.bary_coords([0.5, 1]), [0.5, 0.5, 0]) self.assertArrayAlmostEqual(s.bary_coords([0.5, 0.75]), [0.5, 0.25, 0.25]) self.assertArrayAlmostEqual(s.bary_coords([0.75, 0.75]), [0.25, 0.5, 0.25]) s = Simplex([[1, 1], [1, 0]]) self.assertRaises(ValueError, s.bary_coords, [0.5, 0.5]) def test_volume(self): # Should be value of a right tetrahedron. self.assertAlmostEqual(self.simplex.volume, 1 / 6) def test_str(self): self.assertTrue(str(self.simplex).startswith("3-simplex in 4D space")) self.assertTrue(repr(self.simplex).startswith("3-simplex in 4D space")) def test_bary_coords(self): s = Simplex([[0, 2], [3, 1], [1, 0]]) point = [0.7, 0.5] bc = s.bary_coords(point) self.assertArrayAlmostEqual(bc, [0.26, -0.02, 0.76]) new_point = s.point_from_bary_coords(bc) self.assertArrayAlmostEqual(point, new_point) def test_intersection(self): # simple test, with 2 intersections at faces s = Simplex([[0, 2], [3, 1], [1, 0]]) point1 = [0.7, 0.5] point2 = [0.5, 0.7] intersections = s.line_intersection(point1, point2) expected = np.array([[1.13333333, 0.06666667], [0.8, 0.4]]) self.assertArrayAlmostEqual(intersections, expected) # intersection through point and face point1 = [0, 2] # simplex point point2 = [1, 1] # inside simplex expected = np.array([[1.66666667, 0.33333333], [0, 2]]) intersections = s.line_intersection(point1, point2) self.assertArrayAlmostEqual(intersections, expected) # intersection through point only point1 = [0, 2] # simplex point point2 = [0.5, 0.7] expected = np.array([[0, 2]]) intersections = s.line_intersection(point1, point2) self.assertArrayAlmostEqual(intersections, expected) # 3d intersection through edge and face point1 = [0.5, 0, 0] # edge point point2 = [0.5, 0.5, 0.5] # in simplex expected = np.array([[0.5, 0.25, 0.25], [0.5, 0.0, 0.0]]) intersections = self.simplex.line_intersection(point1, point2) self.assertArrayAlmostEqual(intersections, expected) # 3d intersection through edge only point1 = [0.5, 0, 0] # edge point point2 = [0.5, 0.5, -0.5] # outside simplex expected = np.array([[0.5, 0.0, 0.0]]) intersections = self.simplex.line_intersection(point1, point2) self.assertArrayAlmostEqual(intersections, expected) # coplanar to face (no intersection) point1 = [-1, 2] point2 = [0, 0] expected = np.array([]) intersections = s.line_intersection(point1, point2) self.assertArrayAlmostEqual(intersections, expected) # coplanar to face (with intersection line) point1 = [0, 2] # simplex point point2 = [1, 0] expected = np.array([[1, 0], [0, 2]]) intersections = s.line_intersection(point1, point2) self.assertArrayAlmostEqual(intersections, expected) # coplanar to face (with intersection points) point1 = [0.1, 2] point2 = [1.1, 0] expected = np.array([[1.08, 0.04], [0.12, 1.96]]) intersections = s.line_intersection(point1, point2) self.assertArrayAlmostEqual(intersections, expected) if __name__ == "__main__": import unittest unittest.main()
pigshell/nhnick
refs/heads/vnc-websocket
src/qt/qtwebkit/Tools/Scripts/webkitpy/port/factory_unittest.py
118
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest2 as unittest from webkitpy.tool.mocktool import MockOptions from webkitpy.common.system.systemhost_mock import MockSystemHost from webkitpy.port import factory from webkitpy.port import gtk from webkitpy.port import mac from webkitpy.port import qt from webkitpy.port import test from webkitpy.port import win class FactoryTest(unittest.TestCase): """Test that the factory creates the proper port object for given combination of port_name, host.platform, and options.""" # FIXME: The ports themselves should expose what options they require, # instead of passing generic "options". def setUp(self): self.webkit_options = MockOptions(pixel_tests=False) def assert_port(self, port_name=None, os_name=None, os_version=None, options=None, cls=None): host = MockSystemHost(os_name=os_name, os_version=os_version) port = factory.PortFactory(host).get(port_name, options=options) self.assertIsInstance(port, cls) def test_mac(self): self.assert_port(port_name='mac-lion', cls=mac.MacPort) self.assert_port(port_name='mac-lion-wk2', cls=mac.MacPort) self.assert_port(port_name='mac', os_name='mac', os_version='lion', cls=mac.MacPort) self.assert_port(port_name=None, os_name='mac', os_version='lion', cls=mac.MacPort) def test_win(self): self.assert_port(port_name='win-xp', cls=win.WinPort) self.assert_port(port_name='win-xp-wk2', cls=win.WinPort) self.assert_port(port_name='win', os_name='win', os_version='xp', cls=win.WinPort) self.assert_port(port_name=None, os_name='win', os_version='xp', cls=win.WinPort) self.assert_port(port_name=None, os_name='win', os_version='xp', options=self.webkit_options, cls=win.WinPort) def test_gtk(self): self.assert_port(port_name='gtk', cls=gtk.GtkPort) def test_qt(self): self.assert_port(port_name='qt', cls=qt.QtPort) def test_unknown_specified(self): self.assertRaises(NotImplementedError, factory.PortFactory(MockSystemHost()).get, port_name='unknown') def test_unknown_default(self): self.assertRaises(NotImplementedError, factory.PortFactory(MockSystemHost(os_name='vms')).get) def test_get_from_builder_name(self): self.assertEqual(factory.PortFactory(MockSystemHost()).get_from_builder_name('Apple Lion Release WK1 (Tests)').name(), 'mac-lion')
DirtyUnicorns/android_external_chromium_org
refs/heads/lollipop
tools/telemetry/telemetry/core/platform/linux_platform_backend.py
25
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import subprocess import sys from telemetry import decorators from telemetry.core.platform import linux_based_platform_backend from telemetry.core.platform import platform_backend from telemetry.core.platform import posix_platform_backend from telemetry.core.platform.power_monitor import msr_power_monitor from telemetry.util import cloud_storage from telemetry.util import support_binaries _POSSIBLE_PERFHOST_APPLICATIONS = [ 'perfhost_precise', 'perfhost_trusty', ] class LinuxPlatformBackend( posix_platform_backend.PosixPlatformBackend, linux_based_platform_backend.LinuxBasedPlatformBackend): def __init__(self): super(LinuxPlatformBackend, self).__init__() self._power_monitor = msr_power_monitor.MsrPowerMonitor(self) def StartRawDisplayFrameRateMeasurement(self): raise NotImplementedError() def StopRawDisplayFrameRateMeasurement(self): raise NotImplementedError() def GetRawDisplayFrameRateMeasurements(self): raise NotImplementedError() def IsThermallyThrottled(self): raise NotImplementedError() def HasBeenThermallyThrottled(self): raise NotImplementedError() def GetOSName(self): return 'linux' @decorators.Cache def GetOSVersionName(self): if not os.path.exists('/etc/lsb-release'): raise NotImplementedError('Unknown Linux OS version') codename = None version = None for line in self.GetFileContents('/etc/lsb-release').splitlines(): key, _, value = line.partition('=') if key == 'DISTRIB_CODENAME': codename = value.strip() elif key == 'DISTRIB_RELEASE': try: version = float(value) except ValueError: version = 0 if codename and version: break return platform_backend.OSVersion(codename, version) def CanFlushIndividualFilesFromSystemCache(self): return True def FlushEntireSystemCache(self): p = subprocess.Popen(['/sbin/sysctl', '-w', 'vm.drop_caches=3']) p.wait() assert p.returncode == 0, 'Failed to flush system cache' def CanLaunchApplication(self, application): if application == 'ipfw' and not self._IsIpfwKernelModuleInstalled(): return False return super(LinuxPlatformBackend, self).CanLaunchApplication(application) def InstallApplication(self, application): if application == 'ipfw': self._InstallIpfw() elif application == 'avconv': self._InstallBinary(application, fallback_package='libav-tools') elif application in _POSSIBLE_PERFHOST_APPLICATIONS: self._InstallBinary(application) else: raise NotImplementedError( 'Please teach Telemetry how to install ' + application) def CanMonitorPower(self): return self._power_monitor.CanMonitorPower() def CanMeasurePerApplicationPower(self): return self._power_monitor.CanMeasurePerApplicationPower() def StartMonitoringPower(self, browser): self._power_monitor.StartMonitoringPower(browser) def StopMonitoringPower(self): return self._power_monitor.StopMonitoringPower() def ReadMsr(self, msr_number, start=0, length=64): cmd = ['/usr/sbin/rdmsr', '-d', str(msr_number)] (out, err) = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() if err: raise OSError(err) try: result = int(out) except ValueError: raise OSError('Cannot interpret rdmsr output: %s' % out) return result >> start & ((1 << length) - 1) def _IsIpfwKernelModuleInstalled(self): return 'ipfw_mod' in subprocess.Popen( ['lsmod'], stdout=subprocess.PIPE).communicate()[0] def _InstallIpfw(self): ipfw_bin = support_binaries.FindPath('ipfw', self.GetOSName()) ipfw_mod = support_binaries.FindPath('ipfw_mod.ko', self.GetOSName()) try: changed = cloud_storage.GetIfChanged( ipfw_bin, cloud_storage.INTERNAL_BUCKET) changed |= cloud_storage.GetIfChanged( ipfw_mod, cloud_storage.INTERNAL_BUCKET) except cloud_storage.CloudStorageError, e: logging.error(str(e)) logging.error('You may proceed by manually building and installing' 'dummynet for your kernel. See: ' 'http://info.iet.unipi.it/~luigi/dummynet/') sys.exit(1) if changed or not self.CanLaunchApplication('ipfw'): if not self._IsIpfwKernelModuleInstalled(): subprocess.check_call(['sudo', 'insmod', ipfw_mod]) os.chmod(ipfw_bin, 0755) subprocess.check_call(['sudo', 'cp', ipfw_bin, '/usr/local/sbin']) assert self.CanLaunchApplication('ipfw'), 'Failed to install ipfw. ' \ 'ipfw provided binaries are not supported for linux kernel < 3.13. ' \ 'You may proceed by manually building and installing dummynet for ' \ 'your kernel. See: http://info.iet.unipi.it/~luigi/dummynet/' def _InstallBinary(self, bin_name, fallback_package=None): bin_path = support_binaries.FindPath(bin_name, self.GetOSName()) if not bin_path: raise Exception('Could not find the binary package %s' % bin_name) os.environ['PATH'] += os.pathsep + os.path.dirname(bin_path) try: cloud_storage.GetIfChanged(bin_path, cloud_storage.INTERNAL_BUCKET) os.chmod(bin_path, 0755) except cloud_storage.CloudStorageError, e: logging.error(str(e)) if fallback_package: raise Exception('You may proceed by manually installing %s via:\n' 'sudo apt-get install %s' % (bin_name, fallback_package)) assert self.CanLaunchApplication(bin_name), 'Failed to install ' + bin_name
RenderBroken/Victara-CM-kernel
refs/heads/cm-12.1
scripts/gcc-wrapper.py
182
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011-2012, The Linux Foundation. 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 The Linux Foundation 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, FITNESS FOR A PARTICULAR PURPOSE AND # NON-INFRINGEMENT 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. # Invoke gcc, looking for warnings, and causing a failure if there are # non-whitelisted warnings. import errno import re import os import sys import subprocess # Note that gcc uses unicode, which may depend on the locale. TODO: # force LANG to be set to en_US.UTF-8 to get consistent warnings. allowed_warnings = set([ "return_address.c:62", "workqueue.c:480" ]) # Capture the name of the object file, can find it. ofile = None warning_re = re.compile(r'''(.*/|)([^/]+\.[a-z]+:\d+):(\d+:)? warning:''') def interpret_warning(line): """Decode the message from gcc. The messages we care about have a filename, and a warning""" line = line.rstrip('\n') m = warning_re.match(line) if m and m.group(2) not in allowed_warnings: print "error, forbidden warning:", m.group(2) # If there is a warning, remove any object if it exists. if ofile: try: os.remove(ofile) except OSError: pass sys.exit(1) def run_gcc(): args = sys.argv[1:] # Look for -o try: i = args.index('-o') global ofile ofile = args[i+1] except (ValueError, IndexError): pass compiler = sys.argv[0] try: proc = subprocess.Popen(args, stderr=subprocess.PIPE) for line in proc.stderr: print line, interpret_warning(line) result = proc.wait() except OSError as e: result = e.errno if result == errno.ENOENT: print args[0] + ':',e.strerror print 'Is your PATH set correctly?' else: print ' '.join(args), str(e) return result if __name__ == '__main__': status = run_gcc() sys.exit(status)
jonathonwalz/ansible
refs/heads/devel
lib/ansible/modules/cloud/amazon/rds.py
24
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['stableinterface'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: rds version_added: "1.3" short_description: create, delete, or modify an Amazon rds instance description: - Creates, deletes, or modifies rds instances. When creating an instance it can be either a new instance or a read-only replica of an existing instance. This module has a dependency on python-boto >= 2.5. The 'promote' command requires boto >= 2.18.0. Certain features such as tags rely on boto.rds2 (boto >= 2.26.0) options: command: description: - Specifies the action to take. The 'reboot' option is available starting at version 2.0 required: true choices: [ 'create', 'replicate', 'delete', 'facts', 'modify' , 'promote', 'snapshot', 'reboot', 'restore' ] instance_name: description: - Database instance identifier. Required except when using command=facts or command=delete on just a snapshot required: false default: null source_instance: description: - Name of the database to replicate. Used only when command=replicate. required: false default: null db_engine: description: - The type of database. Used only when command=create. - mariadb was added in version 2.2 required: false default: null choices: ['mariadb', 'MySQL', 'oracle-se1', 'oracle-se', 'oracle-ee', 'sqlserver-ee', 'sqlserver-se', 'sqlserver-ex', 'sqlserver-web', 'postgres', 'aurora'] size: description: - Size in gigabytes of the initial storage for the DB instance. Used only when command=create or command=modify. required: false default: null instance_type: description: - The instance type of the database. Must be specified when command=create. Optional when command=replicate, command=modify or command=restore. If not specified then the replica inherits the same instance type as the source instance. required: false default: null username: description: - Master database username. Used only when command=create. required: false default: null password: description: - Password for the master database username. Used only when command=create or command=modify. required: false default: null region: description: - The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used. required: true aliases: [ 'aws_region', 'ec2_region' ] db_name: description: - Name of a database to create within the instance. If not specified then no database is created. Used only when command=create. required: false default: null engine_version: description: - Version number of the database engine to use. Used only when command=create. If not specified then the current Amazon RDS default engine version is used required: false default: null parameter_group: description: - Name of the DB parameter group to associate with this instance. If omitted then the RDS default DBParameterGroup will be used. Used only when command=create or command=modify. required: false default: null license_model: description: - The license model for this DB instance. Used only when command=create or command=restore. required: false default: null choices: [ 'license-included', 'bring-your-own-license', 'general-public-license', 'postgresql-license' ] multi_zone: description: - Specifies if this is a Multi-availability-zone deployment. Can not be used in conjunction with zone parameter. Used only when command=create or command=modify. choices: [ "yes", "no" ] required: false default: null iops: description: - Specifies the number of IOPS for the instance. Used only when command=create or command=modify. Must be an integer greater than 1000. required: false default: null security_groups: description: - Comma separated list of one or more security groups. Used only when command=create or command=modify. required: false default: null vpc_security_groups: description: - Comma separated list of one or more vpc security group ids. Also requires `subnet` to be specified. Used only when command=create or command=modify. required: false default: null port: description: - Port number that the DB instance uses for connections. Used only when command=create or command=replicate. - Prior to 2.0 it always defaults to null and the API would use 3306, it had to be set to other DB default values when not using MySql. Starting at 2.0 it automatically defaults to what is expected for each c(db_engine). required: false default: 3306 for mysql, 1521 for Oracle, 1433 for SQL Server, 5432 for PostgreSQL. upgrade: description: - Indicates that minor version upgrades should be applied automatically. Used only when command=create or command=replicate. required: false default: no choices: [ "yes", "no" ] option_group: description: - The name of the option group to use. If not specified then the default option group is used. Used only when command=create. required: false default: null maint_window: description: - > Maintenance window in format of ddd:hh24:mi-ddd:hh24:mi. (Example: Mon:22:00-Mon:23:15) If not specified then a random maintenance window is assigned. Used only when command=create or command=modify. required: false default: null backup_window: description: - Backup window in format of hh24:mi-hh24:mi. If not specified then a random backup window is assigned. Used only when command=create or command=modify. required: false default: null backup_retention: description: - > Number of days backups are retained. Set to 0 to disable backups. Default is 1 day. Valid range: 0-35. Used only when command=create or command=modify. required: false default: null zone: description: - availability zone in which to launch the instance. Used only when command=create, command=replicate or command=restore. required: false default: null aliases: ['aws_zone', 'ec2_zone'] subnet: description: - VPC subnet group. If specified then a VPC instance is created. Used only when command=create. required: false default: null snapshot: description: - Name of snapshot to take. When command=delete, if no snapshot name is provided then no snapshot is taken. If used with command=delete with no instance_name, the snapshot is deleted. Used with command=facts, command=delete or command=snapshot. required: false default: null aws_secret_key: description: - AWS secret key. If not set then the value of the AWS_SECRET_KEY environment variable is used. required: false aliases: [ 'ec2_secret_key', 'secret_key' ] aws_access_key: description: - AWS access key. If not set then the value of the AWS_ACCESS_KEY environment variable is used. required: false default: null aliases: [ 'ec2_access_key', 'access_key' ] wait: description: - When command=create, replicate, modify or restore then wait for the database to enter the 'available' state. When command=delete wait for the database to be terminated. required: false default: "no" choices: [ "yes", "no" ] wait_timeout: description: - how long before wait gives up, in seconds default: 300 apply_immediately: description: - Used only when command=modify. If enabled, the modifications will be applied as soon as possible rather than waiting for the next preferred maintenance window. default: no choices: [ "yes", "no" ] force_failover: description: - Used only when command=reboot. If enabled, the reboot is done using a MultiAZ failover. required: false default: "no" choices: [ "yes", "no" ] version_added: "2.0" new_instance_name: description: - Name to rename an instance to. Used only when command=modify. required: false default: null version_added: "1.5" character_set_name: description: - Associate the DB instance with a specified character set. Used with command=create. required: false default: null version_added: "1.9" publicly_accessible: description: - explicitly set whether the resource should be publicly accessible or not. Used with command=create, command=replicate. Requires boto >= 2.26.0 required: false default: null version_added: "1.9" tags: description: - tags dict to apply to a resource. Used with command=create, command=replicate, command=restore. Requires boto >= 2.26.0 required: false default: null version_added: "1.9" requirements: - "python >= 2.6" - "boto" author: - "Bruce Pennypacker (@bpennypacker)" - "Will Thames (@willthames)" extends_documentation_fragment: - aws - ec2 ''' # FIXME: the command stuff needs a 'state' like alias to make things consistent -- MPD EXAMPLES = ''' # Basic mysql provisioning example - rds: command: create instance_name: new-database db_engine: MySQL size: 10 instance_type: db.m1.small username: mysql_admin password: 1nsecure tags: Environment: testing Application: cms # Create a read-only replica and wait for it to become available - rds: command: replicate instance_name: new-database-replica source_instance: new_database wait: yes wait_timeout: 600 # Delete an instance, but create a snapshot before doing so - rds: command: delete instance_name: new-database snapshot: new_database_snapshot # Get facts about an instance - rds: command: facts instance_name: new-database register: new_database_facts # Rename an instance and wait for the change to take effect - rds: command: modify instance_name: new-database new_instance_name: renamed-database wait: yes # Reboot an instance and wait for it to become available again - rds: command: reboot instance_name: database wait: yes # Restore a Postgres db instance from a snapshot, wait for it to become available again, and # then modify it to add your security group. Also, display the new endpoint. # Note that the "publicly_accessible" option is allowed here just as it is in the AWS CLI - local_action: module: rds command: restore snapshot: mypostgres-snapshot instance_name: MyNewInstanceName region: us-west-2 zone: us-west-2b subnet: default-vpc-xx441xxx publicly_accessible: yes wait: yes wait_timeout: 600 tags: Name: pg1_test_name_tag register: rds - local_action: module: rds command: modify instance_name: MyNewInstanceName region: us-west-2 vpc_security_groups: sg-xxx945xx - debug: msg: "The new db endpoint is {{ rds.instance.endpoint }}" ''' import sys import time from ansible.module_utils.ec2 import AWSRetry try: import boto.rds HAS_BOTO = True except ImportError: HAS_BOTO = False try: import boto.rds2 has_rds2 = True except ImportError: has_rds2 = False DEFAULT_PORTS = { 'aurora': 3306, 'mariadb': 3306, 'mysql': 3306, 'oracle': 1521, 'sqlserver': 1433, 'postgres': 5432, } class RDSException(Exception): def __init__(self, exc): if hasattr(exc, 'error_message') and exc.error_message: self.message = exc.error_message self.code = exc.error_code elif hasattr(exc, 'body') and 'Error' in exc.body: self.message = exc.body['Error']['Message'] self.code = exc.body['Error']['Code'] else: self.message = str(exc) self.code = 'Unknown Error' class RDSConnection: def __init__(self, module, region, **aws_connect_params): try: self.connection = connect_to_aws(boto.rds, region, **aws_connect_params) except boto.exception.BotoServerError as e: module.fail_json(msg=e.error_message) def get_db_instance(self, instancename): try: return RDSDBInstance(self.connection.get_all_dbinstances(instancename)[0]) except boto.exception.BotoServerError as e: return None def get_db_snapshot(self, snapshotid): try: return RDSSnapshot(self.connection.get_all_dbsnapshots(snapshot_id=snapshotid)[0]) except boto.exception.BotoServerError as e: return None def create_db_instance(self, instance_name, size, instance_class, db_engine, username, password, **params): params['engine'] = db_engine try: result = self.connection.create_dbinstance(instance_name, size, instance_class, username, password, **params) return RDSDBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def create_db_instance_read_replica(self, instance_name, source_instance, **params): try: result = self.connection.createdb_instance_read_replica(instance_name, source_instance, **params) return RDSDBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def delete_db_instance(self, instance_name, **params): try: result = self.connection.delete_dbinstance(instance_name, **params) return RDSDBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def delete_db_snapshot(self, snapshot): try: result = self.connection.delete_dbsnapshot(snapshot) return RDSSnapshot(result) except boto.exception.BotoServerError as e: raise RDSException(e) def modify_db_instance(self, instance_name, **params): try: result = self.connection.modify_dbinstance(instance_name, **params) return RDSDBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def reboot_db_instance(self, instance_name, **params): try: result = self.connection.reboot_dbinstance(instance_name) return RDSDBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def restore_db_instance_from_db_snapshot(self, instance_name, snapshot, instance_type, **params): try: result = self.connection.restore_dbinstance_from_dbsnapshot(snapshot, instance_name, instance_type, **params) return RDSDBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def create_db_snapshot(self, snapshot, instance_name, **params): try: result = self.connection.create_dbsnapshot(snapshot, instance_name) return RDSSnapshot(result) except boto.exception.BotoServerError as e: raise RDSException(e) def promote_read_replica(self, instance_name, **params): try: result = self.connection.promote_read_replica(instance_name, **params) return RDSDBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) class RDS2Connection: def __init__(self, module, region, **aws_connect_params): try: self.connection = connect_to_aws(boto.rds2, region, **aws_connect_params) except boto.exception.BotoServerError as e: module.fail_json(msg=e.error_message) def get_db_instance(self, instancename): try: dbinstances = self.connection.describe_db_instances( db_instance_identifier=instancename )['DescribeDBInstancesResponse']['DescribeDBInstancesResult']['DBInstances'] result = RDS2DBInstance(dbinstances[0]) return result except boto.rds2.exceptions.DBInstanceNotFound as e: return None except Exception as e: raise e def get_db_snapshot(self, snapshotid): try: snapshots = self.connection.describe_db_snapshots( db_snapshot_identifier=snapshotid, snapshot_type='manual' )['DescribeDBSnapshotsResponse']['DescribeDBSnapshotsResult']['DBSnapshots'] result = RDS2Snapshot(snapshots[0]) return result except boto.rds2.exceptions.DBSnapshotNotFound as e: return None def create_db_instance(self, instance_name, size, instance_class, db_engine, username, password, **params): try: result = self.connection.create_db_instance(instance_name, size, instance_class, db_engine, username, password, **params)['CreateDBInstanceResponse']['CreateDBInstanceResult']['DBInstance'] return RDS2DBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def create_db_instance_read_replica(self, instance_name, source_instance, **params): try: result = self.connection.create_db_instance_read_replica( instance_name, source_instance, **params )['CreateDBInstanceReadReplicaResponse']['CreateDBInstanceReadReplicaResult']['DBInstance'] return RDS2DBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def delete_db_instance(self, instance_name, **params): try: result = self.connection.delete_db_instance(instance_name, **params)['DeleteDBInstanceResponse']['DeleteDBInstanceResult']['DBInstance'] return RDS2DBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def delete_db_snapshot(self, snapshot): try: result = self.connection.delete_db_snapshot(snapshot)['DeleteDBSnapshotResponse']['DeleteDBSnapshotResult']['DBSnapshot'] return RDS2Snapshot(result) except boto.exception.BotoServerError as e: raise RDSException(e) def modify_db_instance(self, instance_name, **params): try: result = self.connection.modify_db_instance(instance_name, **params)['ModifyDBInstanceResponse']['ModifyDBInstanceResult']['DBInstance'] return RDS2DBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def reboot_db_instance(self, instance_name, **params): try: result = self.connection.reboot_db_instance(instance_name, **params)['RebootDBInstanceResponse']['RebootDBInstanceResult']['DBInstance'] return RDS2DBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def restore_db_instance_from_db_snapshot(self, instance_name, snapshot, instance_type, **params): try: result = self.connection.restore_db_instance_from_db_snapshot( instance_name, snapshot, **params )['RestoreDBInstanceFromDBSnapshotResponse']['RestoreDBInstanceFromDBSnapshotResult']['DBInstance'] return RDS2DBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) def create_db_snapshot(self, snapshot, instance_name, **params): try: result = self.connection.create_db_snapshot(snapshot, instance_name, **params)['CreateDBSnapshotResponse']['CreateDBSnapshotResult']['DBSnapshot'] return RDS2Snapshot(result) except boto.exception.BotoServerError as e: raise RDSException(e) def promote_read_replica(self, instance_name, **params): try: result = self.connection.promote_read_replica(instance_name, **params)['PromoteReadReplicaResponse']['PromoteReadReplicaResult']['DBInstance'] return RDS2DBInstance(result) except boto.exception.BotoServerError as e: raise RDSException(e) class RDSDBInstance: def __init__(self, dbinstance): self.instance = dbinstance self.name = dbinstance.id self.status = dbinstance.status def get_data(self): d = { 'id': self.name, 'create_time': self.instance.create_time, 'status': self.status, 'availability_zone': self.instance.availability_zone, 'backup_retention': self.instance.backup_retention_period, 'backup_window': self.instance.preferred_backup_window, 'maintenance_window': self.instance.preferred_maintenance_window, 'multi_zone': self.instance.multi_az, 'instance_type': self.instance.instance_class, 'username': self.instance.master_username, 'iops': self.instance.iops } # Only assign an Endpoint if one is available if hasattr(self.instance, 'endpoint'): d["endpoint"] = self.instance.endpoint[0] d["port"] = self.instance.endpoint[1] if self.instance.vpc_security_groups is not None: d["vpc_security_groups"] = ','.join(x.vpc_group for x in self.instance.vpc_security_groups) else: d["vpc_security_groups"] = None else: d["endpoint"] = None d["port"] = None d["vpc_security_groups"] = None # ReadReplicaSourceDBInstanceIdentifier may or may not exist try: d["replication_source"] = self.instance.ReadReplicaSourceDBInstanceIdentifier except Exception as e: d["replication_source"] = None return d class RDS2DBInstance: def __init__(self, dbinstance): self.instance = dbinstance if 'DBInstanceIdentifier' not in dbinstance: self.name = None else: self.name = self.instance.get('DBInstanceIdentifier') self.status = self.instance.get('DBInstanceStatus') def get_data(self): d = { 'id': self.name, 'create_time': self.instance['InstanceCreateTime'], 'status': self.status, 'availability_zone': self.instance['AvailabilityZone'], 'backup_retention': self.instance['BackupRetentionPeriod'], 'maintenance_window': self.instance['PreferredMaintenanceWindow'], 'multi_zone': self.instance['MultiAZ'], 'instance_type': self.instance['DBInstanceClass'], 'username': self.instance['MasterUsername'], 'iops': self.instance['Iops'], 'replication_source': self.instance['ReadReplicaSourceDBInstanceIdentifier'] } if self.instance["VpcSecurityGroups"] is not None: d['vpc_security_groups'] = ','.join(x['VpcSecurityGroupId'] for x in self.instance['VpcSecurityGroups']) if "Endpoint" in self.instance and self.instance["Endpoint"] is not None: d['endpoint'] = self.instance["Endpoint"].get('Address', None) d['port'] = self.instance["Endpoint"].get('Port', None) else: d['endpoint'] = None d['port'] = None return d class RDSSnapshot: def __init__(self, snapshot): self.snapshot = snapshot self.name = snapshot.id self.status = snapshot.status def get_data(self): d = { 'id': self.name, 'create_time': self.snapshot.snapshot_create_time, 'status': self.status, 'availability_zone': self.snapshot.availability_zone, 'instance_id': self.snapshot.instance_id, 'instance_created': self.snapshot.instance_create_time, } # needs boto >= 2.21.0 if hasattr(self.snapshot, 'snapshot_type'): d["snapshot_type"] = self.snapshot.snapshot_type if hasattr(self.snapshot, 'iops'): d["iops"] = self.snapshot.iops return d class RDS2Snapshot: def __init__(self, snapshot): if 'DeleteDBSnapshotResponse' in snapshot: self.snapshot = snapshot['DeleteDBSnapshotResponse']['DeleteDBSnapshotResult']['DBSnapshot'] else: self.snapshot = snapshot self.name = self.snapshot.get('DBSnapshotIdentifier') self.status = self.snapshot.get('Status') def get_data(self): d = { 'id': self.name, 'create_time': self.snapshot['SnapshotCreateTime'], 'status': self.status, 'availability_zone': self.snapshot['AvailabilityZone'], 'instance_id': self.snapshot['DBInstanceIdentifier'], 'instance_created': self.snapshot['InstanceCreateTime'], 'snapshot_type': self.snapshot['SnapshotType'], 'iops': self.snapshot['Iops'], } return d def await_resource(conn, resource, status, module): start_time = time.time() wait_timeout = module.params.get('wait_timeout') + start_time check_interval = 5 while wait_timeout > time.time() and resource.status != status: time.sleep(check_interval) if wait_timeout <= time.time(): module.fail_json(msg="Timeout waiting for RDS resource %s" % resource.name) if module.params.get('command') == 'snapshot': # Temporary until all the rds2 commands have their responses parsed if resource.name is None: module.fail_json(msg="There was a problem waiting for RDS snapshot %s" % resource.snapshot) # Back off if we're getting throttled, since we're just waiting anyway resource = AWSRetry.backoff(tries=5, delay=20, backoff=1.5)(conn.get_db_snapshot)(resource.name) else: # Temporary until all the rds2 commands have their responses parsed if resource.name is None: module.fail_json(msg="There was a problem waiting for RDS instance %s" % resource.instance) # Back off if we're getting throttled, since we're just waiting anyway resource = AWSRetry.backoff(tries=5, delay=20, backoff=1.5)(conn.get_db_instance)(resource.name) if resource is None: break # Some RDS resources take much longer than others to be ready. Check # less aggressively for slow ones to avoid throttling. if time.time() > start_time + 90: check_interval = 20 return resource def create_db_instance(module, conn): subnet = module.params.get('subnet') required_vars = ['instance_name', 'db_engine', 'size', 'instance_type', 'username', 'password'] valid_vars = ['backup_retention', 'backup_window', 'character_set_name', 'db_name', 'engine_version', 'instance_type', 'iops', 'license_model', 'maint_window', 'multi_zone', 'option_group', 'parameter_group', 'port', 'subnet', 'upgrade', 'zone'] if module.params.get('subnet'): valid_vars.append('vpc_security_groups') else: valid_vars.append('security_groups') if has_rds2: valid_vars.extend(['publicly_accessible', 'tags']) params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') result = conn.get_db_instance(instance_name) if result: changed = False else: try: result = conn.create_db_instance(instance_name, module.params.get('size'), module.params.get('instance_type'), module.params.get('db_engine'), module.params.get('username'), module.params.get('password'), **params) changed = True except RDSException as e: module.fail_json(msg="Failed to create instance: %s" % e.message) if module.params.get('wait'): resource = await_resource(conn, result, 'available', module) else: resource = conn.get_db_instance(instance_name) module.exit_json(changed=changed, instance=resource.get_data()) def replicate_db_instance(module, conn): required_vars = ['instance_name', 'source_instance'] valid_vars = ['instance_type', 'port', 'upgrade', 'zone'] if has_rds2: valid_vars.extend(['iops', 'option_group', 'publicly_accessible', 'tags']) params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') source_instance = module.params.get('source_instance') result = conn.get_db_instance(instance_name) if result: changed = False else: try: result = conn.create_db_instance_read_replica(instance_name, source_instance, **params) changed = True except RDSException as e: module.fail_json(msg="Failed to create replica instance: %s " % e.message) if module.params.get('wait'): resource = await_resource(conn, result, 'available', module) else: resource = conn.get_db_instance(instance_name) module.exit_json(changed=changed, instance=resource.get_data()) def delete_db_instance_or_snapshot(module, conn): required_vars = [] valid_vars = ['instance_name', 'snapshot', 'skip_final_snapshot'] params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') snapshot = module.params.get('snapshot') if not instance_name: result = conn.get_db_snapshot(snapshot) else: result = conn.get_db_instance(instance_name) if not result: module.exit_json(changed=False) if result.status == 'deleting': module.exit_json(changed=False) try: if instance_name: if snapshot: params["skip_final_snapshot"] = False if has_rds2: params["final_db_snapshot_identifier"] = snapshot else: params["final_snapshot_id"] = snapshot else: params["skip_final_snapshot"] = True result = conn.delete_db_instance(instance_name, **params) else: result = conn.delete_db_snapshot(snapshot) except RDSException as e: module.fail_json(msg="Failed to delete instance: %s" % e.message) # If we're not waiting for a delete to complete then we're all done # so just return if not module.params.get('wait'): module.exit_json(changed=True) try: resource = await_resource(conn, result, 'deleted', module) module.exit_json(changed=True) except RDSException as e: if e.code == 'DBInstanceNotFound': module.exit_json(changed=True) else: module.fail_json(msg=e.message) except Exception as e: module.fail_json(msg=str(e)) def facts_db_instance_or_snapshot(module, conn): required_vars = [] valid_vars = ['instance_name', 'snapshot'] params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') snapshot = module.params.get('snapshot') if instance_name and snapshot: module.fail_json(msg="Facts must be called with either instance_name or snapshot, not both") if instance_name: resource = conn.get_db_instance(instance_name) if not resource: module.fail_json(msg="DB instance %s does not exist" % instance_name) if snapshot: resource = conn.get_db_snapshot(snapshot) if not resource: module.fail_json(msg="DB snapshot %s does not exist" % snapshot) module.exit_json(changed=False, instance=resource.get_data()) def modify_db_instance(module, conn): required_vars = ['instance_name'] valid_vars = ['apply_immediately', 'backup_retention', 'backup_window', 'db_name', 'engine_version', 'instance_type', 'iops', 'license_model', 'maint_window', 'multi_zone', 'new_instance_name', 'option_group', 'parameter_group', 'password', 'size', 'upgrade'] params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') new_instance_name = module.params.get('new_instance_name') try: result = conn.modify_db_instance(instance_name, **params) except RDSException as e: module.fail_json(msg=e.message) if params.get('apply_immediately'): if new_instance_name: # Wait until the new instance name is valid new_instance = None while not new_instance: new_instance = conn.get_db_instance(new_instance_name) time.sleep(5) # Found instance but it briefly flicks to available # before rebooting so let's wait until we see it rebooting # before we check whether to 'wait' result = await_resource(conn, new_instance, 'rebooting', module) if module.params.get('wait'): resource = await_resource(conn, result, 'available', module) else: resource = conn.get_db_instance(instance_name) # guess that this changed the DB, need a way to check module.exit_json(changed=True, instance=resource.get_data()) def promote_db_instance(module, conn): required_vars = ['instance_name'] valid_vars = ['backup_retention', 'backup_window'] params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') result = conn.get_db_instance(instance_name) if not result: module.fail_json(msg="DB Instance %s does not exist" % instance_name) if result.get_data().get('replication_source'): try: result = conn.promote_read_replica(instance_name, **params) changed = True except RDSException as e: module.fail_json(msg=e.message) else: changed = False if module.params.get('wait'): resource = await_resource(conn, result, 'available', module) else: resource = conn.get_db_instance(instance_name) module.exit_json(changed=changed, instance=resource.get_data()) def snapshot_db_instance(module, conn): required_vars = ['instance_name', 'snapshot'] valid_vars = ['tags'] params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') snapshot = module.params.get('snapshot') changed = False result = conn.get_db_snapshot(snapshot) if not result: try: result = conn.create_db_snapshot(snapshot, instance_name, **params) changed = True except RDSException as e: module.fail_json(msg=e.message) if module.params.get('wait'): resource = await_resource(conn, result, 'available', module) else: resource = conn.get_db_snapshot(snapshot) module.exit_json(changed=changed, snapshot=resource.get_data()) def reboot_db_instance(module, conn): required_vars = ['instance_name'] valid_vars = [] if has_rds2: valid_vars.append('force_failover') params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') result = conn.get_db_instance(instance_name) changed = False try: result = conn.reboot_db_instance(instance_name, **params) changed = True except RDSException as e: module.fail_json(msg=e.message) if module.params.get('wait'): resource = await_resource(conn, result, 'available', module) else: resource = conn.get_db_instance(instance_name) module.exit_json(changed=changed, instance=resource.get_data()) def restore_db_instance(module, conn): required_vars = ['instance_name', 'snapshot'] valid_vars = ['db_name', 'iops', 'license_model', 'multi_zone', 'option_group', 'port', 'publicly_accessible', 'subnet', 'tags', 'upgrade', 'zone'] if has_rds2: valid_vars.append('instance_type') else: required_vars.append('instance_type') params = validate_parameters(required_vars, valid_vars, module) instance_name = module.params.get('instance_name') instance_type = module.params.get('instance_type') snapshot = module.params.get('snapshot') changed = False result = conn.get_db_instance(instance_name) if not result: try: result = conn.restore_db_instance_from_db_snapshot(instance_name, snapshot, instance_type, **params) changed = True except RDSException as e: module.fail_json(msg=e.message) if module.params.get('wait'): resource = await_resource(conn, result, 'available', module) else: resource = conn.get_db_instance(instance_name) module.exit_json(changed=changed, instance=resource.get_data()) def validate_parameters(required_vars, valid_vars, module): command = module.params.get('command') for v in required_vars: if not module.params.get(v): module.fail_json(msg="Parameter %s required for %s command" % (v, command)) # map to convert rds module options to boto rds and rds2 options optional_params = { 'port': 'port', 'db_name': 'db_name', 'zone': 'availability_zone', 'maint_window': 'preferred_maintenance_window', 'backup_window': 'preferred_backup_window', 'backup_retention': 'backup_retention_period', 'multi_zone': 'multi_az', 'engine_version': 'engine_version', 'upgrade': 'auto_minor_version_upgrade', 'subnet': 'db_subnet_group_name', 'license_model': 'license_model', 'option_group': 'option_group_name', 'size': 'allocated_storage', 'iops': 'iops', 'new_instance_name': 'new_instance_id', 'apply_immediately': 'apply_immediately', } # map to convert rds module options to boto rds options optional_params_rds = { 'db_engine': 'engine', 'password': 'master_password', 'parameter_group': 'param_group', 'instance_type': 'instance_class', } # map to convert rds module options to boto rds2 options optional_params_rds2 = { 'tags': 'tags', 'publicly_accessible': 'publicly_accessible', 'parameter_group': 'db_parameter_group_name', 'character_set_name': 'character_set_name', 'instance_type': 'db_instance_class', 'password': 'master_user_password', 'new_instance_name': 'new_db_instance_identifier', 'force_failover': 'force_failover', } if has_rds2: optional_params.update(optional_params_rds2) sec_group = 'db_security_groups' else: optional_params.update(optional_params_rds) sec_group = 'security_groups' # Check for options only supported with rds2 for k in set(optional_params_rds2.keys()) - set(optional_params_rds.keys()): if module.params.get(k): module.fail_json(msg="Parameter %s requires boto.rds (boto >= 2.26.0)" % k) params = {} for (k, v) in optional_params.items(): if module.params.get(k) is not None and k not in required_vars: if k in valid_vars: params[v] = module.params[k] else: if module.params.get(k) is False: pass else: module.fail_json(msg="Parameter %s is not valid for %s command" % (k, command)) if module.params.get('security_groups'): params[sec_group] = module.params.get('security_groups').split(',') vpc_groups = module.params.get('vpc_security_groups') if vpc_groups: if has_rds2: params['vpc_security_group_ids'] = vpc_groups else: groups_list = [] for x in vpc_groups: groups_list.append(boto.rds.VPCSecurityGroupMembership(vpc_group=x)) params['vpc_security_groups'] = groups_list # Convert tags dict to list of tuples that rds2 expects if 'tags' in params: params['tags'] = module.params['tags'].items() return params def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( command=dict(choices=['create', 'replicate', 'delete', 'facts', 'modify', 'promote', 'snapshot', 'reboot', 'restore'], required=True), instance_name=dict(required=False), source_instance=dict(required=False), db_engine=dict(choices=['mariadb', 'MySQL', 'oracle-se1', 'oracle-se', 'oracle-ee', 'sqlserver-ee', 'sqlserver-se', 'sqlserver-ex', 'sqlserver-web', 'postgres', 'aurora'], required=False), size=dict(required=False), instance_type=dict(aliases=['type'], required=False), username=dict(required=False), password=dict(no_log=True, required=False), db_name=dict(required=False), engine_version=dict(required=False), parameter_group=dict(required=False), license_model=dict(choices=['license-included', 'bring-your-own-license', 'general-public-license', 'postgresql-license'], required=False), multi_zone=dict(type='bool', required=False), iops=dict(required=False), security_groups=dict(required=False), vpc_security_groups=dict(type='list', required=False), port=dict(required=False, type='int'), upgrade=dict(type='bool', default=False), option_group=dict(required=False), maint_window=dict(required=False), backup_window=dict(required=False), backup_retention=dict(required=False), zone=dict(aliases=['aws_zone', 'ec2_zone'], required=False), subnet=dict(required=False), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=300), snapshot=dict(required=False), apply_immediately=dict(type='bool', default=False), new_instance_name=dict(required=False), tags=dict(type='dict', required=False), publicly_accessible=dict(required=False), character_set_name=dict(required=False), force_failover=dict(type='bool', required=False, default=False) ) ) module = AnsibleModule( argument_spec=argument_spec, ) if not HAS_BOTO: module.fail_json(msg='boto required for this module') invocations = { 'create': create_db_instance, 'replicate': replicate_db_instance, 'delete': delete_db_instance_or_snapshot, 'facts': facts_db_instance_or_snapshot, 'modify': modify_db_instance, 'promote': promote_db_instance, 'snapshot': snapshot_db_instance, 'reboot': reboot_db_instance, 'restore': restore_db_instance, } region, ec2_url, aws_connect_params = get_aws_connection_info(module) if not region: module.fail_json(msg="Region not specified. Unable to determine region from EC2_REGION.") # set port to per db defaults if not specified if module.params['port'] is None and module.params['db_engine'] is not None and module.params['command'] == 'create': if '-' in module.params['db_engine']: engine = module.params['db_engine'].split('-')[0] else: engine = module.params['db_engine'] module.params['port'] = DEFAULT_PORTS[engine.lower()] # connect to the rds endpoint if has_rds2: conn = RDS2Connection(module, region, **aws_connect_params) else: conn = RDSConnection(module, region, **aws_connect_params) invocations[module.params.get('command')](module, conn) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * if __name__ == '__main__': main()
sergio-incaser/odoo
refs/heads/8.0
addons/l10n_fr/wizard/fr_report_compute_resultant.py
374
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2008 JAILLET Simon - CrysaLEAD - www.crysalead.fr # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # 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 openerp.osv import fields, osv class account_cdr_report(osv.osv_memory): _name = 'account.cdr.report' _description = 'Account CDR Report' def _get_defaults(self, cr, uid, context=None): fiscalyear_id = self.pool.get('account.fiscalyear').find(cr, uid) return fiscalyear_id _columns = { 'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal Year', required=True), } _defaults = { 'fiscalyear_id': _get_defaults } def print_cdr_report(self, cr, uid, ids, context=None): active_ids = context.get('active_ids', []) data = {} data['form'] = {} data['ids'] = active_ids data['form']['fiscalyear_id'] = self.browse(cr, uid, ids)[0].fiscalyear_id.id return self.pool['report'].get_action( cr, uid, ids, 'l10n_fr.report_l10nfrresultat', data=data, context=context ) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
GaZ3ll3/scikit-image
refs/heads/master
skimage/feature/tests/__init__.py
672
from ..._shared.testing import setup_test, teardown_test def setup(): setup_test() def teardown(): teardown_test()
bradleyy/django-sqlserver
refs/heads/master
sqlserver/compiler.py
1
from __future__ import absolute_import, unicode_literals import django from django.db.utils import DatabaseError from django.db.transaction import TransactionManagementError from django.db.models.sql import compiler import re import six import sqlserver_ado.compiler NEEDS_AGGREGATES_FIX = django.VERSION[:2] < (1, 7) _re_order_limit_offset = re.compile( r'(?:ORDER BY\s+(.+?))?\s*(?:LIMIT\s+(\d+))?\s*(?:OFFSET\s+(\d+))?$') def _get_order_limit_offset(sql): return _re_order_limit_offset.search(sql).groups() def _remove_order_limit_offset(sql): return _re_order_limit_offset.sub('', sql).split(None, 1)[1] class SQLCompiler(sqlserver_ado.compiler.SQLCompiler): pass class SQLInsertCompiler(sqlserver_ado.compiler.SQLInsertCompiler, SQLCompiler): pass class SQLDeleteCompiler(sqlserver_ado.compiler.SQLDeleteCompiler, SQLCompiler): pass class SQLUpdateCompiler(sqlserver_ado.compiler.SQLUpdateCompiler, SQLCompiler): pass class SQLAggregateCompiler(sqlserver_ado.compiler.SQLAggregateCompiler, SQLCompiler): pass
zerolab/wagtail
refs/heads/main
wagtail/contrib/styleguide/tests.py
24
from django.test import TestCase from django.urls import reverse from wagtail.tests.utils import WagtailTestUtils class TestStyleGuide(TestCase, WagtailTestUtils): def setUp(self): self.login() def test_styleguide(self): response = self.client.get(reverse('wagtailstyleguide')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailstyleguide/base.html')
portableant/open-context-py
refs/heads/master
opencontext_py/apps/ldata/linkannotations/recursion.py
1
import hashlib from django.db import models from django.db.models import Q from opencontext_py.libs.general import LastUpdatedOrderedDict from opencontext_py.apps.entities.uri.models import URImanagement from opencontext_py.apps.entities.entity.models import Entity from opencontext_py.apps.ldata.linkannotations.models import LinkAnnotation from opencontext_py.apps.ldata.linkannotations.equivalence import LinkEquivalence from opencontext_py.apps.ocitems.predicates.models import Predicate from opencontext_py.apps.ocitems.octypes.models import OCtype class LinkRecursion(): """ Does recursive look ups on link annotations, especially to find hierarchies """ def __init__(self): self.parent_entities = [] self.child_entities = LastUpdatedOrderedDict() self.loop_count = 0 def get_jsonldish_entity_parents(self, identifier, add_original=True): """ Gets parent concepts for a given URI or UUID identified entity returns a list of dictionary objects similar to JSON-LD expectations This is useful for faceted search If add_original is true, add the original UUID for the entity that's the childmost item, at the bottom of the hierarchy """ output = False raw_parents = self.get_entity_parents(identifier) if(add_original): # add the original identifer to the list of parents, at lowest rank raw_parents.insert(0, identifier) if(len(raw_parents) > 0): output = [] # reverse the order of the list, to make top most concept # first parents = raw_parents[::-1] for par_id in parents: ent = Entity() found = ent.dereference(par_id) if(found): p_item = LastUpdatedOrderedDict() p_item['id'] = ent.uri p_item['slug'] = ent.slug p_item['label'] = ent.label if(ent.data_type is not False): p_item['type'] = ent.data_type else: p_item['type'] = '@id' p_item['ld_object_ok'] = ent.ld_object_ok output.append(p_item) return output def get_entity_parents(self, identifier): """ Gets parent concepts for a given URI or UUID identified entity """ self.loop_count += 1 lequiv = LinkEquivalence() identifiers = lequiv.get_identifier_list_variants(identifier) p_for_superobjs = LinkAnnotation.PREDS_SBJ_IS_SUB_OF_OBJ preds_for_superobjs = lequiv.get_identifier_list_variants(p_for_superobjs) p_for_subobjs = LinkAnnotation.PREDS_SBJ_IS_SUPER_OF_OBJ preds_for_subobjs = lequiv.get_identifier_list_variants(p_for_subobjs) try: # look for superior items in the objects of the assertion superobjs_anno = LinkAnnotation.objects.filter(subject__in=identifiers, predicate_uri__in=preds_for_superobjs)\ .exclude(object_uri__in=identifiers)[:1] if(len(superobjs_anno) < 1): superobjs_anno = False except LinkAnnotation.DoesNotExist: superobjs_anno = False if(superobjs_anno is not False): parent_id = superobjs_anno[0].object_uri if(parent_id.count('/') > 1): oc_uuid = URImanagement.get_uuid_from_oc_uri(parent_id) if(oc_uuid is not False): parent_id = oc_uuid if(parent_id not in self.parent_entities): self.parent_entities.append(parent_id) if self.loop_count <= 50: self.parent_entities = self.get_entity_parents(parent_id) try: """ Now look for superior entities in the subject, not the object """ supersubj_anno = LinkAnnotation.objects.filter(object_uri__in=identifiers, predicate_uri__in=preds_for_subobjs)\ .exclude(subject__in=identifiers)[:1] if(len(supersubj_anno) < 1): supersubj_anno = False except LinkAnnotation.DoesNotExist: supersubj_anno = False if(supersubj_anno is not False): parent_id = supersubj_anno[0].subject if(parent_id.count('/') > 1): oc_uuid = URImanagement.get_uuid_from_oc_uri(parent_id) if(oc_uuid is not False): parent_id = oc_uuid if(parent_id not in self.parent_entities): self.parent_entities.append(parent_id) if self.loop_count <= 50: self.parent_entities = self.get_entity_parents(parent_id) return self.parent_entities def get_entity_children(self, identifier, recurive=True): """ Gets child concepts for a given URI or UUID identified entity """ act_children = [] p_for_superobjs = LinkAnnotation.PREDS_SBJ_IS_SUB_OF_OBJ p_for_subobjs = LinkAnnotation.PREDS_SBJ_IS_SUPER_OF_OBJ lequiv = LinkEquivalence() identifiers = lequiv.get_identifier_list_variants(identifier) try: # look for child items in the objects of the assertion subobjs_anno = LinkAnnotation.objects.filter(subject__in=identifiers, predicate_uri__in=p_for_subobjs) if(len(subobjs_anno) < 1): subobjs_anno = False except LinkAnnotation.DoesNotExist: subobjs_anno = False if subobjs_anno is not False: for sub_obj in subobjs_anno: child_id = sub_obj.object_uri act_children.append(child_id) try: """ Now look for subordinate entities in the subject, not the object """ subsubj_anno = LinkAnnotation.objects.filter(object_uri__in=identifiers, predicate_uri__in=p_for_superobjs) if len(subsubj_anno) < 1: subsubj_anno = False except LinkAnnotation.DoesNotExist: subsubj_anno = False if subsubj_anno is not False: for sub_sub in subsubj_anno: child_id = sub_sub.subject act_children.append(child_id) if len(act_children) > 0: identifier_children = [] for child_id in act_children: if child_id.count('/') > 1: oc_uuid = URImanagement.get_uuid_from_oc_uri(child_id) if oc_uuid is not False: child_id = oc_uuid identifier_children.append(child_id) # recursively get the children of the child self.get_entity_children(child_id, recurive) # same the list of children of the current identified item if identifier not in self.child_entities: self.child_entities[identifier] = identifier_children else: # save a False for the current identified item. it has no children if identifier not in self.child_entities: self.child_entities[identifier] = False def get_pred_top_rank_types(self, predicate_uuid): """ gets the top ranked (not a subordinate) of any other type for a predicate """ types = False try: pred_obj = Predicate.objects.get(uuid=predicate_uuid) except Predicate.DoesNotExist: pred_obj = False if pred_obj is not False: if pred_obj.data_type == 'id': types = [] id_list = [] pred_types = OCtype.objects\ .filter(predicate_uuid=predicate_uuid) for p_type in pred_types: type_pars = self.get_jsonldish_entity_parents(p_type.uuid) self.parent_entities = [] self.loop_count = 0 if type_pars[0]['id'] not in id_list: # so the top parent is only listed once id_list.append(type_pars[0]['id']) types.append(type_pars[0]) return types
byakatat/selenium-training
refs/heads/master
test_task14.py
1
import pytest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait @pytest.fixture def driver(request): wd = webdriver.Chrome() wd.maximize_window() # Login to admin wd.get("http://localhost/litecart/admin/") wd.find_element_by_xpath("//input[@name='username']").send_keys("admin") wd.find_element_by_xpath("//input[@name='password']").send_keys("admin") wd.find_element_by_xpath("//button[@name='login']").click() request.addfinalizer(wd.quit) return wd def test(driver): wait = WebDriverWait(driver, 10) # Open Countries list driver.get("http://localhost/litecart/admin/?app=countries&doc=countries") # Edit the first country country_pencil_link = wait.until(EC.visibility_of_element_located(( By.XPATH, "(.//table[@class='dataTable']//i/parent::a)[1]"))) country_pencil_link.click() # Get all external links external_links = wait.until(EC.presence_of_all_elements_located(( By.XPATH, "//td[@id='content']//i[@class='fa fa-external-link']/parent::a"))) # Get id of current window main_window = driver.current_window_handle # Get a list of id-s of all opened windows old_windows = driver.window_handles # Click on every external link in external_links list for link in external_links: link.click() # Wait until new window opens and get it's id. new_window = wait.until(appearance_of_new_window(old_windows)) driver.switch_to_window(new_window) driver.close() driver.switch_to_window(main_window) # A class that takes a list of old_windows and returns id of new opened window # As example I took classes in selenium.webdriver.support.expected_conditions class appearance_of_new_window(object): def __init__(self, list_of_old_windows): self.list_of_old_windows = list_of_old_windows def __call__(self, driver): # Get list of all windows id's new_windows = driver.window_handles # Get length of new and old lists of id's len_new_windows = len(new_windows) len_old_windows = len(self.list_of_old_windows) # If new list's length greater than old one's # then return the first id that exists in new list and doesn't exist in old one if len_new_windows > len_old_windows: for item in new_windows: if item not in self.list_of_old_windows: return item else: return False
Endika/event
refs/heads/8.0
event_track_generate/wizards/wizard_generator.py
2
# -*- coding: utf-8 -*- # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). # © 2015 Grupo ESOC Ingeniería de Servicios, S.L.U. from datetime import datetime, timedelta from pytz import timezone from openerp import _, api, fields, models from openerp.exceptions import ValidationError class Generator(models.TransientModel): _name = "event.track.generator" event_id = fields.Many2one( "event.event", string="Event", default=lambda self: self.env.context["active_id"], required=True) event_date_begin = fields.Datetime( related="event_id.date_begin", help="Change it in the event form. " "No tracks before this date will be generated.") event_date_end = fields.Datetime( related="event_id.date_end", help="Change it in the event form. " "No tracks after this date will be generated.") event_date_tz = fields.Selection( related="event_id.date_tz", help="Change it in the event form. Timezone of the generated tracks.") name = fields.Char( "Track title", required=True, help="Title that will be assigned to all created tracks.") location_id = fields.Many2one("event.track.location", "Location") speaker_ids = fields.Many2many( "res.partner", string="Speakers", relation="event_track_generate_generator_speaker_ids") tag_ids = fields.Many2many( "event.track.tag", string="Tags", relation="event_track_generate_generator_tag_ids") mondays = fields.Boolean(help="Create tracks on Mondays.") tuesdays = fields.Boolean(help="Create tracks on Tuesdays.") wednesdays = fields.Boolean(help="Create tracks on Wednesdays.") thursdays = fields.Boolean(help="Create tracks on Thursdays.") fridays = fields.Boolean(help="Create tracks on Fridays.") saturdays = fields.Boolean(help="Create tracks on Saturdays.") sundays = fields.Boolean(help="Create tracks on Sundays.") start_time = fields.Float( required=True, help="Each track will start at this time (in the event's timezone).") duration = fields.Float( required=True, help="Each track will have this duration.") end_time = fields.Float( compute="_compute_end_time", help="Each track will end at this time.") delete_existing_tracks = fields.Boolean() publish_tracks_in_website = fields.Boolean() adjust_start_time = fields.Boolean( default=True, help="Make event's start time match the start of the first track.") adjust_end_time = fields.Boolean( default=True, help="Make event's end time match the end of the last track.") @api.multi @api.depends("start_time", "duration") def _compute_end_time(self): self.end_time = self.start_time + self.duration @api.multi def action_generate(self): """Generate event tracks according to received data. This is the main method of this class, triggered by the UI. """ # You need at least one weekday weekdays = self.weekdays() if not any(weekdays): raise ValidationError(_("You must select at least one weekday.")) # Delete existing if self.delete_existing_tracks: self.event_id.track_ids.unlink() # Create new self.generate_tracks() # Adjust event's dates self.adjust_dates() @api.multi def adjust_dates(self): """Adjust event dates if asked to do so.""" # Cheek if the user wanted to adjust dates if self.event_id.track_ids.exists() and (self.adjust_start_time or self.adjust_end_time): sorted_ = self.event_id.track_ids.sorted(lambda r: r.date) # Start date if self.adjust_start_time: self.event_id.date_begin = sorted_[0].date # End date if self.adjust_end_time: self.event_id.date_end = fields.Datetime.to_string( fields.Datetime.from_string(sorted_[-1].date) + timedelta(hours=sorted_[-1].duration)) @api.multi def create_track(self, **values): """Create a new track record with the provided values.""" data = { "name": self.name, "event_id": self.event_id.id, "duration": self.duration, "location_id": self.location_id.id, "speaker_ids": [(6, False, self.speaker_ids.ids)], "tag_ids": [(6, False, self.tag_ids.ids)], "user_id": self.event_id.user_id.id, "website_published": self.publish_tracks_in_website} data.update(values) return self.env["event.track"].create(data) @api.multi def datetime_fields(self): """Fields converted to Python's Datetime-based objects.""" result = { "event_start": fields.Datetime.from_string(self.event_date_begin), "event_end": fields.Datetime.from_string(self.event_date_end), "duration_delta": timedelta(hours=self.duration), "day_delta": timedelta(days=1), "start_time": datetime.min + timedelta(hours=self.start_time), } # Needed to manually fix timezone offset, for start_time result["tzdiff"] = (timezone(self.event_id.date_tz or self.env.context["tz"] or self.env.user.tz or "UTC") .utcoffset(result["event_start"])) return result @api.multi def existing_tracks(self, date): """Return existing tracks that match some criteria.""" return self.env["event.track"].search( (("event_id", "=", self.event_id.id), ("date", "=", date), ("duration", "=", self.duration))) @api.multi def generate_tracks(self): """Know which tracks must be generated and do it.""" counter = 0 dt = self.datetime_fields() weekdays = self.weekdays() # Check that tracks fit between event start and end dates current = dt["event_start"] while current <= dt["event_end"]: # Get start date and time with fixed timezone offset current_start = datetime.combine( current.date(), dt["start_time"].time()) - dt["tzdiff"] if (current_start >= dt["event_start"] and weekdays[current.weekday()]): current_end = current_start + dt["duration_delta"] if current_end <= dt["event_end"]: # Need string for the ORM current_start = fields.Datetime.to_string(current_start) # Check that no track exists with this data if not self.existing_tracks(current_start): self.create_track(date=current_start) counter += 1 # Next day current += dt["day_delta"] @api.multi def weekdays(self): """Sorted weekdays user selection.""" return (self.mondays, self.tuesdays, self.wednesdays, self.thursdays, self.fridays, self.saturdays, self.sundays)
jimi-c/ansible
refs/heads/devel
lib/ansible/modules/cloud/vultr/vultr_startup_script_facts.py
27
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2018, Yanis Guenane <yanis+ansible@guenane.org> # 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 = r''' --- module: vultr_startup_script_facts short_description: Gather facts about the Vultr startup scripts available. description: - Gather facts about vultr_startup_scripts available. version_added: "2.7" author: "Yanis Guenane (@Spredzy)" extends_documentation_fragment: vultr ''' EXAMPLES = r''' - name: Gather Vultr startup scripts facts local_action: module: vultr_startup_script_facts - name: Print the gathered facts debug: var: ansible_facts.vultr_startup_script_facts ''' RETURN = r''' --- vultr_api: description: Response from Vultr API with a few additions/modification returned: success type: complex contains: api_account: description: Account used in the ini file to select the key returned: success type: string sample: default api_timeout: description: Timeout used for the API requests returned: success type: int sample: 60 api_retries: description: Amount of max retries for the API requests returned: success type: int sample: 5 api_endpoint: description: Endpoint used for the API requests returned: success type: string sample: "https://api.vultr.com" vultr_startup_script_facts: description: Response from Vultr API returned: success type: complex contains: "vultr_startup_script_facts": [ { "date_created": "2018-07-19 08:38:36", "date_modified": "2018-07-19 08:38:36", "id": 327133, "name": "lolo", "script": "#!/bin/bash\necho Hello World > /root/hello", "type": "boot" } ] ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.vultr import ( Vultr, vultr_argument_spec, ) class AnsibleVultrStartupScriptFacts(Vultr): def __init__(self, module): super(AnsibleVultrStartupScriptFacts, self).__init__(module, "vultr_startup_script_facts") self.returns = { "SCRIPTID": dict(key='id', convert_to='int'), "date_created": dict(), "date_modified": dict(), "name": dict(), "script": dict(), "type": dict(), } def get_startupscripts(self): return self.api_query(path="/v1/startupscript/list") def parse_startupscript_list(startupscipts_list): if not startupscipts_list: return [] return [startupscript for id, startupscript in startupscipts_list.items()] def main(): argument_spec = vultr_argument_spec() module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) startupscript_facts = AnsibleVultrStartupScriptFacts(module) result = startupscript_facts.get_result(parse_startupscript_list(startupscript_facts.get_startupscripts())) ansible_facts = { 'vultr_startup_script_facts': result['vultr_startup_script_facts'] } module.exit_json(ansible_facts=ansible_facts, **result) if __name__ == '__main__': main()
bcarroll/authmgr
refs/heads/master
python-3.6.2-Win64/Lib/site-packages/psycopg2/tests/test_types_basic.py
16
#!/usr/bin/env python # # types_basic.py - tests for basic types conversions # # Copyright (C) 2004-2010 Federico Di Gregorio <fog@debian.org> # # psycopg2 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 3 of the License, or # (at your option) any later version. # # In addition, as a special exception, the copyright holders give # permission to link this program with the OpenSSL library (or with # modified versions of OpenSSL that use the same license as OpenSSL), # and distribute linked combinations including the two. # # You must obey the GNU Lesser General Public License in all respects for # all of the code used other than OpenSSL. # # psycopg2 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. import decimal import sys from functools import wraps from . import testutils from .testutils import unittest, ConnectingTestCase, decorate_all_tests import psycopg2 class TypesBasicTests(ConnectingTestCase): """Test that all type conversions are working.""" def execute(self, *args): curs = self.conn.cursor() curs.execute(*args) return curs.fetchone()[0] def testQuoting(self): s = "Quote'this\\! ''ok?''" self.assertTrue(self.execute("SELECT %s AS foo", (s,)) == s, "wrong quoting: " + s) def testUnicode(self): s = "Quote'this\\! ''ok?''" self.assertTrue(self.execute("SELECT %s AS foo", (s,)) == s, "wrong unicode quoting: " + s) def testNumber(self): s = self.execute("SELECT %s AS foo", (1971,)) self.assertTrue(s == 1971, "wrong integer quoting: " + str(s)) s = self.execute("SELECT %s AS foo", (1971,)) self.assertTrue(s == 1971, "wrong integer quoting: " + str(s)) def testBoolean(self): x = self.execute("SELECT %s as foo", (False,)) self.assertTrue(x is False) x = self.execute("SELECT %s as foo", (True,)) self.assertTrue(x is True) def testDecimal(self): s = self.execute("SELECT %s AS foo", (decimal.Decimal("19.10"),)) self.assertTrue(s - decimal.Decimal("19.10") == 0, "wrong decimal quoting: " + str(s)) s = self.execute("SELECT %s AS foo", (decimal.Decimal("NaN"),)) self.assertTrue(str(s) == "NaN", "wrong decimal quoting: " + str(s)) self.assertTrue(type(s) == decimal.Decimal, "wrong decimal conversion: " + repr(s)) s = self.execute("SELECT %s AS foo", (decimal.Decimal("infinity"),)) self.assertTrue(str(s) == "NaN", "wrong decimal quoting: " + str(s)) self.assertTrue(type(s) == decimal.Decimal, "wrong decimal conversion: " + repr(s)) s = self.execute("SELECT %s AS foo", (decimal.Decimal("-infinity"),)) self.assertTrue(str(s) == "NaN", "wrong decimal quoting: " + str(s)) self.assertTrue(type(s) == decimal.Decimal, "wrong decimal conversion: " + repr(s)) def testFloatNan(self): try: float("nan") except ValueError: return self.skipTest("nan not available on this platform") s = self.execute("SELECT %s AS foo", (float("nan"),)) self.assertTrue(str(s) == "nan", "wrong float quoting: " + str(s)) self.assertTrue(type(s) == float, "wrong float conversion: " + repr(s)) def testFloatInf(self): try: self.execute("select 'inf'::float") except psycopg2.DataError: return self.skipTest("inf::float not available on the server") except ValueError: return self.skipTest("inf not available on this platform") s = self.execute("SELECT %s AS foo", (float("inf"),)) self.assertTrue(str(s) == "inf", "wrong float quoting: " + str(s)) self.assertTrue(type(s) == float, "wrong float conversion: " + repr(s)) s = self.execute("SELECT %s AS foo", (float("-inf"),)) self.assertTrue(str(s) == "-inf", "wrong float quoting: " + str(s)) def testBinary(self): if sys.version_info[0] < 3: s = ''.join([chr(x) for x in range(256)]) b = psycopg2.Binary(s) buf = self.execute("SELECT %s::bytea AS foo", (b,)) self.assertEqual(s, str(buf)) else: s = bytes(list(range(256))) b = psycopg2.Binary(s) buf = self.execute("SELECT %s::bytea AS foo", (b,)) self.assertEqual(s, buf.tobytes()) def testBinaryNone(self): b = psycopg2.Binary(None) buf = self.execute("SELECT %s::bytea AS foo", (b,)) self.assertEqual(buf, None) def testBinaryEmptyString(self): # test to make sure an empty Binary is converted to an empty string if sys.version_info[0] < 3: b = psycopg2.Binary('') self.assertEqual(str(b), "''::bytea") else: b = psycopg2.Binary(bytes([])) self.assertEqual(str(b), "''::bytea") def testBinaryRoundTrip(self): # test to make sure buffers returned by psycopg2 are # understood by execute: if sys.version_info[0] < 3: s = ''.join([chr(x) for x in range(256)]) buf = self.execute("SELECT %s::bytea AS foo", (psycopg2.Binary(s),)) buf2 = self.execute("SELECT %s::bytea AS foo", (buf,)) self.assertEqual(s, str(buf2)) else: s = bytes(list(range(256))) buf = self.execute("SELECT %s::bytea AS foo", (psycopg2.Binary(s),)) buf2 = self.execute("SELECT %s::bytea AS foo", (buf,)) self.assertEqual(s, buf2.tobytes()) def testArray(self): s = self.execute("SELECT %s AS foo", ([[1, 2], [3, 4]],)) self.assertEqual(s, [[1, 2], [3, 4]]) s = self.execute("SELECT %s AS foo", (['one', 'two', 'three'],)) self.assertEqual(s, ['one', 'two', 'three']) def testEmptyArrayRegression(self): # ticket #42 import datetime curs = self.conn.cursor() curs.execute( "create table array_test " "(id integer, col timestamp without time zone[])") curs.execute("insert into array_test values (%s, %s)", (1, [datetime.date(2011, 2, 14)])) curs.execute("select col from array_test where id = 1") self.assertEqual(curs.fetchone()[0], [datetime.datetime(2011, 2, 14, 0, 0)]) curs.execute("insert into array_test values (%s, %s)", (2, [])) curs.execute("select col from array_test where id = 2") self.assertEqual(curs.fetchone()[0], []) def testEmptyArrayNoCast(self): s = self.execute("SELECT '{}' AS foo") self.assertEqual(s, '{}') s = self.execute("SELECT %s AS foo", ([],)) self.assertEqual(s, '{}') def testEmptyArray(self): s = self.execute("SELECT '{}'::text[] AS foo") self.assertEqual(s, []) s = self.execute("SELECT 1 != ALL(%s)", ([],)) self.assertEqual(s, True) # but don't break the strings :) s = self.execute("SELECT '{}'::text AS foo") self.assertEqual(s, "{}") def testArrayEscape(self): ss = ['', '\\', '"', '\\\\', '\\"'] for s in ss: r = self.execute("SELECT %s AS foo", (s,)) self.assertEqual(s, r) r = self.execute("SELECT %s AS foo", ([s],)) self.assertEqual([s], r) r = self.execute("SELECT %s AS foo", (ss,)) self.assertEqual(ss, r) def testArrayMalformed(self): curs = self.conn.cursor() ss = ['', '{', '{}}', '{' * 20 + '}' * 20] for s in ss: self.assertRaises(psycopg2.DataError, psycopg2.extensions.STRINGARRAY, s.encode('utf8'), curs) @testutils.skip_before_postgres(8, 2) def testArrayOfNulls(self): curs = self.conn.cursor() curs.execute(""" create table na ( texta text[], inta int[], boola boolean[], textaa text[][], intaa int[][], boolaa boolean[][] )""") curs.execute("insert into na (texta) values (%s)", ([None],)) curs.execute("insert into na (texta) values (%s)", (['a', None],)) curs.execute("insert into na (texta) values (%s)", ([None, None],)) curs.execute("insert into na (inta) values (%s)", ([None],)) curs.execute("insert into na (inta) values (%s)", ([42, None],)) curs.execute("insert into na (inta) values (%s)", ([None, None],)) curs.execute("insert into na (boola) values (%s)", ([None],)) curs.execute("insert into na (boola) values (%s)", ([True, None],)) curs.execute("insert into na (boola) values (%s)", ([None, None],)) # TODO: array of array of nulls are not supported yet # curs.execute("insert into na (textaa) values (%s)", ([[None]],)) curs.execute("insert into na (textaa) values (%s)", ([['a', None]],)) # curs.execute("insert into na (textaa) values (%s)", ([[None, None]],)) # curs.execute("insert into na (intaa) values (%s)", ([[None]],)) curs.execute("insert into na (intaa) values (%s)", ([[42, None]],)) # curs.execute("insert into na (intaa) values (%s)", ([[None, None]],)) # curs.execute("insert into na (boolaa) values (%s)", ([[None]],)) curs.execute("insert into na (boolaa) values (%s)", ([[True, None]],)) # curs.execute("insert into na (boolaa) values (%s)", ([[None, None]],)) @testutils.skip_from_python(3) def testTypeRoundtripBuffer(self): o1 = buffer("".join(map(chr, list(range(256))))) o2 = self.execute("select %s;", (o1,)) self.assertEqual(type(o1), type(o2)) # Test with an empty buffer o1 = buffer("") o2 = self.execute("select %s;", (o1,)) self.assertEqual(type(o1), type(o2)) self.assertEqual(str(o1), str(o2)) @testutils.skip_from_python(3) def testTypeRoundtripBufferArray(self): o1 = buffer("".join(map(chr, list(range(256))))) o1 = [o1] o2 = self.execute("select %s;", (o1,)) self.assertEqual(type(o1[0]), type(o2[0])) self.assertEqual(str(o1[0]), str(o2[0])) @testutils.skip_before_python(3) def testTypeRoundtripBytes(self): o1 = bytes(list(range(256))) o2 = self.execute("select %s;", (o1,)) self.assertEqual(memoryview, type(o2)) # Test with an empty buffer o1 = bytes([]) o2 = self.execute("select %s;", (o1,)) self.assertEqual(memoryview, type(o2)) @testutils.skip_before_python(3) def testTypeRoundtripBytesArray(self): o1 = bytes(list(range(256))) o1 = [o1] o2 = self.execute("select %s;", (o1,)) self.assertEqual(memoryview, type(o2[0])) @testutils.skip_before_python(2, 6) def testAdaptBytearray(self): o1 = bytearray(list(range(256))) o2 = self.execute("select %s;", (o1,)) if sys.version_info[0] < 3: self.assertEqual(buffer, type(o2)) else: self.assertEqual(memoryview, type(o2)) self.assertEqual(len(o1), len(o2)) for c1, c2 in zip(o1, o2): self.assertEqual(c1, ord(c2)) # Test with an empty buffer o1 = bytearray([]) o2 = self.execute("select %s;", (o1,)) self.assertEqual(len(o2), 0) if sys.version_info[0] < 3: self.assertEqual(buffer, type(o2)) else: self.assertEqual(memoryview, type(o2)) @testutils.skip_before_python(2, 7) def testAdaptMemoryview(self): o1 = memoryview(bytearray(list(range(256)))) o2 = self.execute("select %s;", (o1,)) if sys.version_info[0] < 3: self.assertEqual(buffer, type(o2)) else: self.assertEqual(memoryview, type(o2)) # Test with an empty buffer o1 = memoryview(bytearray([])) o2 = self.execute("select %s;", (o1,)) if sys.version_info[0] < 3: self.assertEqual(buffer, type(o2)) else: self.assertEqual(memoryview, type(o2)) def testByteaHexCheckFalsePositive(self): # the check \x -> x to detect bad bytea decode # may be fooled if the first char is really an 'x' o1 = psycopg2.Binary(b'x') o2 = self.execute("SELECT %s::bytea AS foo", (o1,)) self.assertEqual(b'x', o2[0]) def testNegNumber(self): d1 = self.execute("select -%s;", (decimal.Decimal('-1.0'),)) self.assertEqual(1, d1) f1 = self.execute("select -%s;", (-1.0,)) self.assertEqual(1, f1) i1 = self.execute("select -%s;", (-1,)) self.assertEqual(1, i1) l1 = self.execute("select -%s;", (-1,)) self.assertEqual(1, l1) def testGenericArray(self): a = self.execute("select '{1, 2, 3}'::int4[]") self.assertEqual(a, [1, 2, 3]) a = self.execute("select array['a', 'b', '''']::text[]") self.assertEqual(a, ['a', 'b', "'"]) @testutils.skip_before_postgres(8, 2) def testGenericArrayNull(self): def caster(s, cur): if s is None: return "nada" return int(s) * 2 base = psycopg2.extensions.new_type((23,), "INT4", caster) array = psycopg2.extensions.new_array_type((1007,), "INT4ARRAY", base) psycopg2.extensions.register_type(array, self.conn) a = self.execute("select '{1, 2, 3}'::int4[]") self.assertEqual(a, [2, 4, 6]) a = self.execute("select '{1, 2, NULL}'::int4[]") self.assertEqual(a, [2, 4, 'nada']) @testutils.skip_before_postgres(8, 2) def testNetworkArray(self): # we don't know these types, but we know their arrays a = self.execute("select '{192.168.0.1/24}'::inet[]") self.assertEqual(a, ['192.168.0.1/24']) a = self.execute("select '{192.168.0.0/24}'::cidr[]") self.assertEqual(a, ['192.168.0.0/24']) a = self.execute("select '{10:20:30:40:50:60}'::macaddr[]") self.assertEqual(a, ['10:20:30:40:50:60']) class AdaptSubclassTest(unittest.TestCase): def test_adapt_subtype(self): from psycopg2.extensions import adapt class Sub(str): pass s1 = "hel'lo" s2 = Sub(s1) self.assertEqual(adapt(s1).getquoted(), adapt(s2).getquoted()) def test_adapt_most_specific(self): from psycopg2.extensions import adapt, register_adapter, AsIs class A(object): pass class B(A): pass class C(B): pass register_adapter(A, lambda a: AsIs("a")) register_adapter(B, lambda b: AsIs("b")) try: self.assertEqual(b'b', adapt(C()).getquoted()) finally: del psycopg2.extensions.adapters[A, psycopg2.extensions.ISQLQuote] del psycopg2.extensions.adapters[B, psycopg2.extensions.ISQLQuote] @testutils.skip_from_python(3) def test_no_mro_no_joy(self): from psycopg2.extensions import adapt, register_adapter, AsIs class A: pass class B(A): pass register_adapter(A, lambda a: AsIs("a")) try: self.assertRaises(psycopg2.ProgrammingError, adapt, B()) finally: del psycopg2.extensions.adapters[A, psycopg2.extensions.ISQLQuote] @testutils.skip_before_python(3) def test_adapt_subtype_3(self): from psycopg2.extensions import adapt, register_adapter, AsIs class A: pass class B(A): pass register_adapter(A, lambda a: AsIs("a")) try: self.assertEqual(b"a", adapt(B()).getquoted()) finally: del psycopg2.extensions.adapters[A, psycopg2.extensions.ISQLQuote] def test_conform_subclass_precedence(self): import psycopg2.extensions as ext class foo(tuple): def __conform__(self, proto): return self def getquoted(self): return 'bar' self.assertEqual(ext.adapt(foo((1, 2, 3))).getquoted(), 'bar') class ByteaParserTest(unittest.TestCase): """Unit test for our bytea format parser.""" def setUp(self): try: self._cast = self._import_cast() except Exception as e: self._cast = None self._exc = e def _import_cast(self): """Use ctypes to access the C function. Raise any sort of error: we just support this where ctypes works as expected. """ import ctypes lib = ctypes.pydll.LoadLibrary(psycopg2._psycopg.__file__) cast = lib.typecast_BINARY_cast cast.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.py_object] cast.restype = ctypes.py_object return cast def cast(self, buffer): """Cast a buffer from the output format""" l = buffer and len(buffer) or 0 rv = self._cast(buffer, l, None) if rv is None: return None if sys.version_info[0] < 3: return str(rv) else: return rv.tobytes() def test_null(self): rv = self.cast(None) self.assertEqual(rv, None) def test_blank(self): rv = self.cast(b'') self.assertEqual(rv, b'') def test_blank_hex(self): # Reported as problematic in ticket #48 rv = self.cast(b'\\x') self.assertEqual(rv, b'') def test_full_hex(self, upper=False): buf = ''.join(("%02x" % i) for i in range(256)) if upper: buf = buf.upper() buf = '\\x' + buf rv = self.cast(buf.encode('utf8')) if sys.version_info[0] < 3: self.assertEqual(rv, ''.join(map(chr, list(range(256))))) else: self.assertEqual(rv, bytes(list(range(256)))) def test_full_hex_upper(self): return self.test_full_hex(upper=True) def test_full_escaped_octal(self): buf = ''.join(("\\%03o" % i) for i in range(256)) rv = self.cast(buf.encode('utf8')) if sys.version_info[0] < 3: self.assertEqual(rv, ''.join(map(chr, list(range(256))))) else: self.assertEqual(rv, bytes(list(range(256)))) def test_escaped_mixed(self): import string buf = ''.join(("\\%03o" % i) for i in range(32)) buf += string.ascii_letters buf += ''.join('\\' + c for c in string.ascii_letters) buf += '\\\\' rv = self.cast(buf.encode('utf8')) if sys.version_info[0] < 3: tgt = ''.join(map(chr, list(range(32)))) \ + string.ascii_letters * 2 + '\\' else: tgt = bytes(list(range(32))) + \ (string.ascii_letters * 2 + '\\').encode('ascii') self.assertEqual(rv, tgt) def skip_if_cant_cast(f): @wraps(f) def skip_if_cant_cast_(self, *args, **kwargs): if self._cast is None: return self.skipTest("can't test bytea parser: %s - %s" % (self._exc.__class__.__name__, self._exc)) return f(self, *args, **kwargs) return skip_if_cant_cast_ decorate_all_tests(ByteaParserTest, skip_if_cant_cast) def test_suite(): return unittest.TestLoader().loadTestsFromName(__name__) if __name__ == "__main__": unittest.main()
ebar0n/django
refs/heads/master
django/templatetags/i18n.py
25
from django.conf import settings from django.template import Library, Node, TemplateSyntaxError, Variable from django.template.base import TOKEN_TEXT, TOKEN_VAR, render_value_in_context from django.template.defaulttags import token_kwargs from django.utils import translation from django.utils.safestring import SafeData, mark_safe register = Library() class GetAvailableLanguagesNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = [(k, translation.gettext(v)) for k, v in settings.LANGUAGES] return '' class GetLanguageInfoNode(Node): def __init__(self, lang_code, variable): self.lang_code = lang_code self.variable = variable def render(self, context): lang_code = self.lang_code.resolve(context) context[self.variable] = translation.get_language_info(lang_code) return '' class GetLanguageInfoListNode(Node): def __init__(self, languages, variable): self.languages = languages self.variable = variable def get_language_info(self, language): # ``language`` is either a language code string or a sequence # with the language code as its first item if len(language[0]) > 1: return translation.get_language_info(language[0]) else: return translation.get_language_info(str(language)) def render(self, context): langs = self.languages.resolve(context) context[self.variable] = [self.get_language_info(lang) for lang in langs] return '' class GetCurrentLanguageNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language() return '' class GetCurrentLanguageBidiNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language_bidi() return '' class TranslateNode(Node): def __init__(self, filter_expression, noop, asvar=None, message_context=None): self.noop = noop self.asvar = asvar self.message_context = message_context self.filter_expression = filter_expression if isinstance(self.filter_expression.var, str): self.filter_expression.var = Variable("'%s'" % self.filter_expression.var) def render(self, context): self.filter_expression.var.translate = not self.noop if self.message_context: self.filter_expression.var.message_context = ( self.message_context.resolve(context)) output = self.filter_expression.resolve(context) value = render_value_in_context(output, context) # Restore percent signs. Percent signs in template text are doubled # so they are not interpreted as string format flags. is_safe = isinstance(value, SafeData) value = value.replace('%%', '%') value = mark_safe(value) if is_safe else value if self.asvar: context[self.asvar] = value return '' else: return value class BlockTranslateNode(Node): def __init__(self, extra_context, singular, plural=None, countervar=None, counter=None, message_context=None, trimmed=False, asvar=None): self.extra_context = extra_context self.singular = singular self.plural = plural self.countervar = countervar self.counter = counter self.message_context = message_context self.trimmed = trimmed self.asvar = asvar def render_token_list(self, tokens): result = [] vars = [] for token in tokens: if token.token_type == TOKEN_TEXT: result.append(token.contents.replace('%', '%%')) elif token.token_type == TOKEN_VAR: result.append('%%(%s)s' % token.contents) vars.append(token.contents) msg = ''.join(result) if self.trimmed: msg = translation.trim_whitespace(msg) return msg, vars def render(self, context, nested=False): if self.message_context: message_context = self.message_context.resolve(context) else: message_context = None tmp_context = {} for var, val in self.extra_context.items(): tmp_context[var] = val.resolve(context) # Update() works like a push(), so corresponding context.pop() is at # the end of function context.update(tmp_context) singular, vars = self.render_token_list(self.singular) if self.plural and self.countervar and self.counter: count = self.counter.resolve(context) context[self.countervar] = count plural, plural_vars = self.render_token_list(self.plural) if message_context: result = translation.npgettext(message_context, singular, plural, count) else: result = translation.ngettext(singular, plural, count) vars.extend(plural_vars) else: if message_context: result = translation.pgettext(message_context, singular) else: result = translation.gettext(singular) default_value = context.template.engine.string_if_invalid def render_value(key): if key in context: val = context[key] else: val = default_value % key if '%s' in default_value else default_value return render_value_in_context(val, context) data = {v: render_value(v) for v in vars} context.pop() try: result = result % data except (KeyError, ValueError): if nested: # Either string is malformed, or it's a bug raise TemplateSyntaxError( "'blocktrans' is unable to format string returned by gettext: %r using %r" % (result, data) ) with translation.override(None): result = self.render(context, nested=True) if self.asvar: context[self.asvar] = result return '' else: return result class LanguageNode(Node): def __init__(self, nodelist, language): self.nodelist = nodelist self.language = language def render(self, context): with translation.override(self.language.resolve(context)): output = self.nodelist.render(context) return output @register.tag("get_available_languages") def do_get_available_languages(parser, token): """ This will store a list of available languages in the context. Usage:: {% get_available_languages as languages %} {% for language in languages %} ... {% endfor %} This will just pull the LANGUAGES setting from your setting file (or the default settings) and put it into the named variable. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args) return GetAvailableLanguagesNode(args[2]) @register.tag("get_language_info") def do_get_language_info(parser, token): """ This will store the language information dictionary for the given language code in a context variable. Usage:: {% get_language_info for LANGUAGE_CODE as l %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} """ args = token.split_contents() if len(args) != 5 or args[1] != 'for' or args[3] != 'as': raise TemplateSyntaxError("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])) return GetLanguageInfoNode(parser.compile_filter(args[2]), args[4]) @register.tag("get_language_info_list") def do_get_language_info_list(parser, token): """ This will store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items are language codes). Usage:: {% get_language_info_list for LANGUAGES as langs %} {% for l in langs %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} {% endfor %} """ args = token.split_contents() if len(args) != 5 or args[1] != 'for' or args[3] != 'as': raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:])) return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4]) @register.filter def language_name(lang_code): return translation.get_language_info(lang_code)['name'] @register.filter def language_name_translated(lang_code): english_name = translation.get_language_info(lang_code)['name'] return translation.gettext(english_name) @register.filter def language_name_local(lang_code): return translation.get_language_info(lang_code)['name_local'] @register.filter def language_bidi(lang_code): return translation.get_language_info(lang_code)['bidi'] @register.tag("get_current_language") def do_get_current_language(parser, token): """ This will store the current language in the context. Usage:: {% get_current_language as language %} This will fetch the currently active language and put it's value into the ``language`` context variable. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args) return GetCurrentLanguageNode(args[2]) @register.tag("get_current_language_bidi") def do_get_current_language_bidi(parser, token): """ This will store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This will fetch the currently active language's layout and put it's value into the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to-right """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args) return GetCurrentLanguageBidiNode(args[2]) @register.tag("trans") def do_translate(parser, token): """ This will mark a string for translation and will translate the string for the current language. Usage:: {% trans "this is a test" %} This will mark the string for translation so it will be pulled out by mark-messages.py into the .po files and will run the string through the translation engine. There is a second form:: {% trans "this is a test" noop %} This will only mark for translation, but will return the string unchanged. Use it when you need to store values into forms that should be translated later on. You can use variables instead of constant strings to translate stuff you marked somewhere else:: {% trans variable %} This will just try to translate the contents of the variable ``variable``. Make sure that the string in there is something that is in the .po file. It is possible to store the translated string into a variable:: {% trans "this is a test" as var %} {{ var }} Contextual translations are also supported:: {% trans "this is a test" context "greeting" %} This is equivalent to calling pgettext instead of (u)gettext. """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0]) message_string = parser.compile_filter(bits[1]) remaining = bits[2:] noop = False asvar = None message_context = None seen = set() invalid_context = {'as', 'noop'} while remaining: option = remaining.pop(0) if option in seen: raise TemplateSyntaxError( "The '%s' option was specified more than once." % option, ) elif option == 'noop': noop = True elif option == 'context': try: value = remaining.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the context option." % bits[0] ) if value in invalid_context: raise TemplateSyntaxError( "Invalid argument '%s' provided to the '%s' tag for the context option" % (value, bits[0]), ) message_context = parser.compile_filter(value) elif option == 'as': try: value = remaining.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the as option." % bits[0] ) asvar = value else: raise TemplateSyntaxError( "Unknown argument for '%s' tag: '%s'. The only options " "available are 'noop', 'context' \"xxx\", and 'as VAR'." % ( bits[0], option, ) ) seen.add(option) return TranslateNode(message_string, noop, asvar, message_context) @register.tag("blocktrans") def do_block_translate(parser, token): """ This will translate a block of text with parameters. Usage:: {% blocktrans with bar=foo|filter boo=baz|filter %} This is {{ bar }} and {{ boo }}. {% endblocktrans %} Additionally, this supports pluralization:: {% blocktrans count count=var|length %} There is {{ count }} object. {% plural %} There are {{ count }} objects. {% endblocktrans %} This is much like ngettext, only in template syntax. The "var as value" legacy format is still supported:: {% blocktrans with foo|filter as bar and baz|filter as boo %} {% blocktrans count var|length as count %} The translated string can be stored in a variable using `asvar`:: {% blocktrans with bar=foo|filter boo=baz|filter asvar var %} This is {{ bar }} and {{ boo }}. {% endblocktrans %} {{ var }} Contextual translations are supported:: {% blocktrans with bar=foo|filter context "greeting" %} This is {{ bar }}. {% endblocktrans %} This is equivalent to calling pgettext/npgettext instead of (u)gettext/(u)ngettext. """ bits = token.split_contents() options = {} remaining_bits = bits[1:] asvar = None while remaining_bits: option = remaining_bits.pop(0) if option in options: raise TemplateSyntaxError('The %r option was specified more ' 'than once.' % option) if option == 'with': value = token_kwargs(remaining_bits, parser, support_legacy=True) if not value: raise TemplateSyntaxError('"with" in %r tag needs at least ' 'one keyword argument.' % bits[0]) elif option == 'count': value = token_kwargs(remaining_bits, parser, support_legacy=True) if len(value) != 1: raise TemplateSyntaxError('"count" in %r tag expected exactly ' 'one keyword argument.' % bits[0]) elif option == "context": try: value = remaining_bits.pop(0) value = parser.compile_filter(value) except Exception: raise TemplateSyntaxError( '"context" in %r tag expected exactly one argument.' % bits[0] ) elif option == "trimmed": value = True elif option == "asvar": try: value = remaining_bits.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the asvar option." % bits[0] ) asvar = value else: raise TemplateSyntaxError('Unknown argument for %r tag: %r.' % (bits[0], option)) options[option] = value if 'count' in options: countervar, counter = next(iter(options['count'].items())) else: countervar, counter = None, None if 'context' in options: message_context = options['context'] else: message_context = None extra_context = options.get('with', {}) trimmed = options.get("trimmed", False) singular = [] plural = [] while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): singular.append(token) else: break if countervar and counter: if token.contents.strip() != 'plural': raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags inside it") while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): plural.append(token) else: break if token.contents.strip() != 'endblocktrans': raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents) return BlockTranslateNode(extra_context, singular, plural, countervar, counter, message_context, trimmed=trimmed, asvar=asvar) @register.tag def language(parser, token): """ This will enable the given language just for this block. Usage:: {% language "de" %} This is {{ bar }} and {{ boo }}. {% endlanguage %} """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0]) language = parser.compile_filter(bits[1]) nodelist = parser.parse(('endlanguage',)) parser.delete_first_token() return LanguageNode(nodelist, language)
tuhangdi/django
refs/heads/master
django/db/backends/oracle/client.py
518
import subprocess from django.db.backends.base.client import BaseDatabaseClient class DatabaseClient(BaseDatabaseClient): executable_name = 'sqlplus' def runshell(self): conn_string = self.connection._connect_string() args = [self.executable_name, "-L", conn_string] subprocess.call(args)
ulmon/hadoop1.2.1
refs/heads/master
src/contrib/hod/hodlib/ServiceProxy/serviceProxy.py
182
#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. """HOD Service Proxy Implementation""" # -*- python -*- import sys, time, signal, httplib, socket, threading import sha, base64, hmac import xml.dom.minidom from hodlib.Common.socketServers import hodHTTPServer from hodlib.Common.hodsvc import hodBaseService from hodlib.Common.threads import loop from hodlib.Common.tcp import tcpSocket from hodlib.Common.util import get_exception_string from hodlib.Common.AllocationManagerUtil import * class svcpxy(hodBaseService): def __init__(self, config): hodBaseService.__init__(self, 'serviceProxy', config['service_proxy'], xrtype='twisted') self.amcfg=config['allocation_manager'] def _xr_method_isProjectUserValid(self, userid, project, ignoreErrors = False, timeOut = 15): return self.isProjectUserValid(userid, project, ignoreErrors, timeOut) def isProjectUserValid(self, userid, project, ignoreErrors, timeOut): """Method thats called upon by the hodshell to verify if the specified (user, project) combination is valid""" self.logs['main'].info("Begin isProjectUserValid()") am = AllocationManagerUtil.getAllocationManager(self.amcfg['id'], self.amcfg, self.logs['main']) self.logs['main'].info("End isProjectUserValid()") return am.getQuote(userid, project)
mdietrichc2c/OCB
refs/heads/8.0
addons/account/wizard/account_report_common_account.py
371
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class account_common_account_report(osv.osv_memory): _name = 'account.common.account.report' _description = 'Account Common Account Report' _inherit = "account.common.report" _columns = { 'display_account': fields.selection([('all','All'), ('movement','With movements'), ('not_zero','With balance is not equal to 0'), ],'Display Accounts', required=True), } _defaults = { 'display_account': 'movement', } def pre_print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data['form'].update(self.read(cr, uid, ids, ['display_account'], context=context)[0]) return data #vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
cchanning/Impala
refs/heads/cdh5-trunk
thirdparty/thrift-0.9.0/lib/py/src/transport/TSSLSocket.py
28
# # 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 os import socket import ssl from thrift.transport import TSocket from thrift.transport.TTransport import TTransportException class TSSLSocket(TSocket.TSocket): """ SSL implementation of client-side TSocket This class creates outbound sockets wrapped using the python standard ssl module for encrypted connections. The protocol used is set using the class variable SSL_VERSION, which must be one of ssl.PROTOCOL_* and defaults to ssl.PROTOCOL_TLSv1 for greatest security. """ SSL_VERSION = ssl.PROTOCOL_TLSv1 def __init__(self, host='localhost', port=9090, validate=True, ca_certs=None, unix_socket=None): """Create SSL TSocket @param validate: Set to False to disable SSL certificate validation @type validate: bool @param ca_certs: Filename to the Certificate Authority pem file, possibly a file downloaded from: http://curl.haxx.se/ca/cacert.pem This is passed to the ssl_wrap function as the 'ca_certs' parameter. @type ca_certs: str Raises an IOError exception if validate is True and the ca_certs file is None, not present or unreadable. """ self.validate = validate self.is_valid = False self.peercert = None if not validate: self.cert_reqs = ssl.CERT_NONE else: self.cert_reqs = ssl.CERT_REQUIRED self.ca_certs = ca_certs if validate: if ca_certs is None or not os.access(ca_certs, os.R_OK): raise IOError('Certificate Authority ca_certs file "%s" ' 'is not readable, cannot validate SSL ' 'certificates.' % (ca_certs)) TSocket.TSocket.__init__(self, host, port, unix_socket) def open(self): try: res0 = self._resolveAddr() for res in res0: sock_family, sock_type = res[0:2] ip_port = res[4] plain_sock = socket.socket(sock_family, sock_type) self.handle = ssl.wrap_socket(plain_sock, ssl_version=self.SSL_VERSION, do_handshake_on_connect=True, ca_certs=self.ca_certs, cert_reqs=self.cert_reqs) self.handle.settimeout(self._timeout) try: self.handle.connect(ip_port) except socket.error, e: if res is not res0[-1]: continue else: raise e break except socket.error, e: if self._unix_socket: message = 'Could not connect to secure socket %s' % self._unix_socket else: message = 'Could not connect to %s:%d' % (self.host, self.port) raise TTransportException(type=TTransportException.NOT_OPEN, message=message) if self.validate: self._validate_cert() def _validate_cert(self): """internal method to validate the peer's SSL certificate, and to check the commonName of the certificate to ensure it matches the hostname we used to make this connection. Does not support subjectAltName records in certificates. raises TTransportException if the certificate fails validation. """ cert = self.handle.getpeercert() self.peercert = cert if 'subject' not in cert: raise TTransportException( type=TTransportException.NOT_OPEN, message='No SSL certificate found from %s:%s' % (self.host, self.port)) fields = cert['subject'] for field in fields: # ensure structure we get back is what we expect if not isinstance(field, tuple): continue cert_pair = field[0] if len(cert_pair) < 2: continue cert_key, cert_value = cert_pair[0:2] if cert_key != 'commonName': continue certhost = cert_value if certhost == self.host: # success, cert commonName matches desired hostname self.is_valid = True return else: raise TTransportException( type=TTransportException.UNKNOWN, message='Hostname we connected to "%s" doesn\'t match certificate ' 'provided commonName "%s"' % (self.host, certhost)) raise TTransportException( type=TTransportException.UNKNOWN, message='Could not validate SSL certificate from ' 'host "%s". Cert=%s' % (self.host, cert)) class TSSLServerSocket(TSocket.TServerSocket): """SSL implementation of TServerSocket This uses the ssl module's wrap_socket() method to provide SSL negotiated encryption. """ SSL_VERSION = ssl.PROTOCOL_TLSv1 def __init__(self, host=None, port=9090, certfile='cert.pem', unix_socket=None): """Initialize a TSSLServerSocket @param certfile: filename of the server certificate, defaults to cert.pem @type certfile: str @param host: The hostname or IP to bind the listen socket to, i.e. 'localhost' for only allowing local network connections. Pass None to bind to all interfaces. @type host: str @param port: The port to listen on for inbound connections. @type port: int """ self.setCertfile(certfile) TSocket.TServerSocket.__init__(self, host, port) def setCertfile(self, certfile): """Set or change the server certificate file used to wrap new connections. @param certfile: The filename of the server certificate, i.e. '/etc/certs/server.pem' @type certfile: str Raises an IOError exception if the certfile is not present or unreadable. """ if not os.access(certfile, os.R_OK): raise IOError('No such certfile found: %s' % (certfile)) self.certfile = certfile def accept(self): plain_client, addr = self.handle.accept() try: client = ssl.wrap_socket(plain_client, certfile=self.certfile, server_side=True, ssl_version=self.SSL_VERSION) except ssl.SSLError, ssl_exc: # failed handshake/ssl wrap, close socket to client plain_client.close() # raise ssl_exc # We can't raise the exception, because it kills most TServer derived # serve() methods. # Instead, return None, and let the TServer instance deal with it in # other exception handling. (but TSimpleServer dies anyway) return None result = TSocket.TSocket() result.setHandle(client) return result
mikewiebe-ansible/ansible
refs/heads/devel
test/units/modules/network/fortios/test_fortios_router_setting.py
21
# Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <https://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest from mock import ANY from ansible.module_utils.network.fortios.fortios import FortiOSHandler try: from ansible.modules.network.fortios import fortios_router_setting except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_router_setting.Connection') return connection_class_mock fos_instance = FortiOSHandler(connection_mock) def test_router_setting_creation(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'router_setting': { 'hostname': 'myhostname3', 'show_filter': 'test_value_4' }, 'vdom': 'root'} is_error, changed, response = fortios_router_setting.fortios_router(input_data, fos_instance) expected_data = { 'hostname': 'myhostname3', 'show-filter': 'test_value_4' } set_method_mock.assert_called_with('router', 'setting', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_router_setting_creation_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'router_setting': { 'hostname': 'myhostname3', 'show_filter': 'test_value_4' }, 'vdom': 'root'} is_error, changed, response = fortios_router_setting.fortios_router(input_data, fos_instance) expected_data = { 'hostname': 'myhostname3', 'show-filter': 'test_value_4' } set_method_mock.assert_called_with('router', 'setting', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_router_setting_idempotent(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'router_setting': { 'hostname': 'myhostname3', 'show_filter': 'test_value_4' }, 'vdom': 'root'} is_error, changed, response = fortios_router_setting.fortios_router(input_data, fos_instance) expected_data = { 'hostname': 'myhostname3', 'show-filter': 'test_value_4' } set_method_mock.assert_called_with('router', 'setting', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 404 def test_router_setting_filter_foreign_attributes(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'router_setting': { 'random_attribute_not_valid': 'tag', 'hostname': 'myhostname3', 'show_filter': 'test_value_4' }, 'vdom': 'root'} is_error, changed, response = fortios_router_setting.fortios_router(input_data, fos_instance) expected_data = { 'hostname': 'myhostname3', 'show-filter': 'test_value_4' } set_method_mock.assert_called_with('router', 'setting', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200
philchristensen/modu
refs/heads/master
src/modu/itemdefs/__init__.py
1
# modu # Copyright (c) 2006-2010 Phil Christensen # http://modu.bubblehouse.org # # # See LICENSE for details """ Base package for itemdef discovery. """ import os, sys __path__ = [os.path.abspath(os.path.join(x, 'modu', 'itemdefs')) for x in sys.path] __all__ = []
UstadMobile/eXePUB
refs/heads/master
twisted/trial/test/test_runner.py
14
# -*- test-case-name: twisted.trial.test.test_runner -*- # Copyright (c) 2005 Twisted Matrix Laboratories. # See LICENSE for details. # # Author: Robert Collins <robertc@robertcollins.net> import os from zope.interface import implements from twisted.trial.itrial import IReporter from twisted.trial import unittest, runner from twisted.python import reflect from twisted.scripts import trial from twisted.plugins import twisted_trial class CapturingDebugger(object): def __init__(self): self._calls = [] def runcall(self, *args, **kwargs): self._calls.append('runcall') args[0](*args[1:], **kwargs) class CapturingReporter(object): implements(IReporter) stream = None tbformat = None args = None separator = None testsRun = None def __init__(self, tbformat=None, args=None, realtime=None): """Create a capturing reporter.""" self._calls = [] self.shouldStop = False def setUpReporter(self): """performs reporter setup. DEPRECATED""" self._calls.append('setUp') def tearDownReporter(self): """performs reporter termination. DEPRECATED""" self._calls.append('tearDown') def reportImportError(self, name, exc): """report an import error @param name: the name that could not be imported @param exc: the exception @type exc: L{twisted.python.failure.Failure} """ self._calls.append('importError') def startTest(self, method): """report the beginning of a run of a single test method @param method: an object that is adaptable to ITestMethod """ self._calls.append('startTest') def stopTest(self, method): """report the status of a single test method @param method: an object that is adaptable to ITestMethod """ self._calls.append('stopTest') def startTrial(self, expectedTests): """kick off this trial run @param expectedTests: the number of tests we expect to run """ self._calls.append('startTrial') def startClass(self, klass): "called at the beginning of each TestCase with the class" self._calls.append('startClass') def endClass(self, klass): "called at the end of each TestCase with the class" self._calls.append('endClass') def startSuite(self, module): "called at the beginning of each module" self._calls.append('startSuite') def endSuite(self, module): "called at the end of each module" self._calls.append('endSuite') def cleanupErrors(self, errs): """called when the reactor has been left in a 'dirty' state @param errs: a list of L{twisted.python.failure.Failure}s """ self._calls.append('cleanupError') def upDownError(self, userMeth, warn=True, printStatus=True): """called when an error occurs in a setUp* or tearDown* method @param warn: indicates whether or not the reporter should emit a warning about the error @type warn: Boolean @param printStatus: indicates whether or not the reporter should print the name of the method and the status message appropriate for the type of error @type printStatus: Boolean """ self._calls.append('upDownError') def addSuccess(self, test): self._calls.append('addSuccess') def printErrors(self): pass def printSummary(self): pass def write(self, *args, **kw): pass def writeln(self, *args, **kw): pass class TestImports(unittest.TestCase): def test_imports(self): from twisted.trial.runner import TrialRunner class TestRunner(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.config = trial.Options() # whitebox hack a reporter in, because plugins are CACHED and will # only reload if the FILE gets changed. self.config.optToQual['capturing'] = reflect.qual(CapturingReporter) self.standardReport = [ 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', ] self.dryRunReport = [ 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', 'startTest', 'addSuccess', 'stopTest', ] def parseOptions(self, args): self.config.parseOptions(args) def getRunner(self): return trial._makeRunner(self.config) def test_runner_can_get_reporter(self): self.parseOptions([]) reporter = self.config['reporter'] my_runner = self.getRunner() self.assertEqual(reporter, my_runner._makeResult().__class__) def test_runner_get_result(self): self.parseOptions([]) my_runner = self.getRunner() result = my_runner._makeResult() self.assertEqual(result.__class__, self.config['reporter']) def test_runner_working_directory(self): self.parseOptions(['--temp-directory', 'some_path']) runner = self.getRunner() self.assertEquals(runner.workingDirectory, 'some_path') def test_runner_dry_run(self): self.parseOptions(['--dry-run', '--reporter', 'capturing', 'twisted.trial.test.sample']) my_runner = self.getRunner() loader = runner.TestLoader() suite = loader.loadByName('twisted.trial.test.sample', True) result = my_runner.run(suite) self.assertEqual(self.dryRunReport, result._calls) def test_runner_normal(self): self.parseOptions(['--temp-directory', self.mktemp(), '--reporter', 'capturing', 'twisted.trial.test.sample']) my_runner = self.getRunner() loader = runner.TestLoader() suite = loader.loadByName('twisted.trial.test.sample', True) result = my_runner.run(suite) self.assertEqual(self.standardReport, result._calls) def test_runner_debug(self): self.parseOptions(['--reporter', 'capturing', '--debug', 'twisted.trial.test.sample']) my_runner = self.getRunner() debugger = CapturingDebugger() def get_debugger(): return debugger my_runner._getDebugger = get_debugger loader = runner.TestLoader() suite = loader.loadByName('twisted.trial.test.sample', True) result = my_runner.run(suite) self.assertEqual(self.standardReport, result._calls) self.assertEqual(['runcall'], debugger._calls) class TestTrialSuite(unittest.TestCase): def test_imports(self): from twisted.trial.runner import TrialSuite # FIXME, HTF do you test the reactor can be cleaned up ?!!!
s40523127/2017springwcm_g4
refs/heads/gh-pages
plugin/liquid_tags/flickr.py
278
""" Flickr Tag ---------- This implements a Liquid-style flickr tag for Pelican. IMPORTANT: You have to create a API key to access the flickr api. You can do this `here <https://www.flickr.com/services/apps/create/apply>`_. Add the created key to your config under FLICKR_API_KEY. Syntax ------ {% flickr image_id [small|medium|large] ["alt text"|'alt text'] %} Example -------- {% flickr 18841055371 large "Fichte"} Output ------ <a href="https://www.flickr.com/photos/marvinxsteadfast/18841055371/"><img src="https://farm6.staticflickr.com/5552/18841055371_17ac287217_b.jpg" alt="Fichte"></a> """ import json import re try: from urllib.request import urlopen from urllib.parse import urlencode except ImportError: from urllib import urlopen, urlencode from .mdx_liquid_tags import LiquidTags SYNTAX = '''{% flickr image_id [small|medium|large] ["alt text"|'alt text'] %}''' PARSE_SYNTAX = re.compile(('''(?P<photo_id>\S+)''' '''(?:\s+(?P<size>large|medium|small))?''' '''(?:\s+(['"]{0,1})(?P<alt>.+)(\\3))?''')) def get_info(photo_id, api_key): ''' Get photo informations from flickr api. ''' query = urlencode({ 'method': 'flickr.photos.getInfo', 'api_key': api_key, 'photo_id': photo_id, 'format': 'json', 'nojsoncallback': '1' }) r = urlopen('https://api.flickr.com/services/rest/?' + query) info = json.loads(r.read().decode('utf-8')) if info['stat'] == 'fail': raise ValueError(info['message']) return info def source_url(farm, server, id, secret, size): ''' Url for direct jpg use. ''' if size == 'small': img_size = 'n' elif size == 'medium': img_size = 'c' elif size == 'large': img_size = 'b' return 'https://farm{}.staticflickr.com/{}/{}_{}_{}.jpg'.format( farm, server, id, secret, img_size) def generate_html(attrs, api_key): ''' Returns html code. ''' # getting flickr api data flickr_data = get_info(attrs['photo_id'], api_key) # if size is not defined it will use large as image size if 'size' not in attrs.keys(): attrs['size'] = 'large' # if no alt is defined it will use the flickr image title if 'alt' not in attrs.keys(): attrs['alt'] = flickr_data['photo']['title']['_content'] # return final html code return '<a href="{}"><img src="{}" alt="{}"></a>'.format( flickr_data['photo']['urls']['url'][0]['_content'], source_url(flickr_data['photo']['farm'], flickr_data['photo']['server'], attrs['photo_id'], flickr_data['photo']['secret'], attrs['size']), attrs['alt']) @LiquidTags.register('flickr') def flickr(preprocessor, tag, markup): # getting flickr api key out of config api_key = preprocessor.configs.getConfig('FLICKR_API_KEY') # parse markup and extract data attrs = None match = PARSE_SYNTAX.search(markup) if match: attrs = dict( [(key, value.strip()) for (key, value) in match.groupdict().items() if value]) else: raise ValueError('Error processing input. ' 'Expected syntax: {}'.format(SYNTAX)) return generate_html(attrs, api_key) # --------------------------------------------------- # This import allows image tag to be a Pelican plugin from liquid_tags import register
espressif/ESP8266_RTOS_SDK
refs/heads/master
tools/idf_tools.py
1
#!/usr/bin/env python # coding=utf-8 # # This script helps installing tools required to use the ESP-IDF, and updating PATH # to use the installed tools. It can also create a Python virtual environment, # and install Python requirements into it. # It does not install OS dependencies. It does install tools such as the Xtensa # GCC toolchain and ESP32 ULP coprocessor toolchain. # # By default, downloaded tools will be installed under $HOME/.espressif directory # (%USERPROFILE%/.espressif on Windows). This path can be modified by setting # IDF_TOOLS_PATH variable prior to running this tool. # # Users do not need to interact with this script directly. In IDF root directory, # install.sh (.bat) and export.sh (.bat) scripts are provided to invoke this script. # # Usage: # # * To install the tools, run `idf_tools.py install`. # # * To install the Python environment, run `idf_tools.py install-python-env`. # # * To start using the tools, run `eval "$(idf_tools.py export)"` — this will update # the PATH to point to the installed tools and set up other environment variables # needed by the tools. # ### # # Copyright 2019 Espressif Systems (Shanghai) PTE LTD # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import subprocess import sys import argparse import re import platform import hashlib import tarfile import zipfile import errno import shutil import functools from collections import OrderedDict, namedtuple try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve TOOLS_FILE = 'tools/tools.json' TOOLS_SCHEMA_FILE = 'tools/tools_schema.json' TOOLS_FILE_NEW = 'tools/tools.new.json' TOOLS_FILE_VERSION = 1 IDF_TOOLS_PATH_DEFAULT = os.path.join('~', '.espressif') UNKNOWN_VERSION = 'unknown' SUBST_TOOL_PATH_REGEX = re.compile(r'\${TOOL_PATH}') VERSION_REGEX_REPLACE_DEFAULT = r'\1' IDF_MAINTAINER = os.environ.get('IDF_MAINTAINER') or False TODO_MESSAGE = 'TODO' DOWNLOAD_RETRY_COUNT = 3 URL_PREFIX_MAP_SEPARATOR = ',' IDF_TOOLS_INSTALL_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD') IDF_TOOLS_EXPORT_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD') PYTHON_PLATFORM = platform.system() + '-' + platform.machine() # Identifiers used in tools.json for different platforms. PLATFORM_WIN32 = 'win32' PLATFORM_WIN64 = 'win64' PLATFORM_MACOS = 'macos' PLATFORM_LINUX32 = 'linux-i686' PLATFORM_LINUX64 = 'linux-amd64' PLATFORM_LINUX_ARM32 = 'linux-armel' PLATFORM_LINUX_ARM64 = 'linux-arm64' # Mappings from various other names these platforms are known as, to the identifiers above. # This includes strings produced from "platform.system() + '-' + platform.machine()", see PYTHON_PLATFORM # definition above. # This list also includes various strings used in release archives of xtensa-esp32-elf-gcc, OpenOCD, etc. PLATFORM_FROM_NAME = { # Windows PLATFORM_WIN32: PLATFORM_WIN32, 'Windows-i686': PLATFORM_WIN32, 'Windows-x86': PLATFORM_WIN32, PLATFORM_WIN64: PLATFORM_WIN64, 'Windows-x86_64': PLATFORM_WIN64, 'Windows-AMD64': PLATFORM_WIN64, # macOS PLATFORM_MACOS: PLATFORM_MACOS, 'osx': PLATFORM_MACOS, 'darwin': PLATFORM_MACOS, 'Darwin-x86_64': PLATFORM_MACOS, # Linux PLATFORM_LINUX64: PLATFORM_LINUX64, 'linux64': PLATFORM_LINUX64, 'Linux-x86_64': PLATFORM_LINUX64, PLATFORM_LINUX32: PLATFORM_LINUX32, 'linux32': PLATFORM_LINUX32, 'Linux-i686': PLATFORM_LINUX32, PLATFORM_LINUX_ARM32: PLATFORM_LINUX_ARM32, 'Linux-arm': PLATFORM_LINUX_ARM32, 'Linux-armv7l': PLATFORM_LINUX_ARM32, PLATFORM_LINUX_ARM64: PLATFORM_LINUX_ARM64, 'Linux-arm64': PLATFORM_LINUX_ARM64, 'Linux-aarch64': PLATFORM_LINUX_ARM64, 'Linux-armv8l': PLATFORM_LINUX_ARM64, } UNKNOWN_PLATFORM = 'unknown' CURRENT_PLATFORM = PLATFORM_FROM_NAME.get(PYTHON_PLATFORM, UNKNOWN_PLATFORM) EXPORT_SHELL = 'shell' EXPORT_KEY_VALUE = 'key-value' global_quiet = False global_non_interactive = False global_idf_path = None global_idf_tools_path = None global_tools_json = None def fatal(text, *args): if not global_quiet: sys.stderr.write('ERROR: ' + text + '\n', *args) def warn(text, *args): if not global_quiet: sys.stderr.write('WARNING: ' + text + '\n', *args) def info(text, f=None, *args): if not global_quiet: if f is None: f = sys.stdout f.write(text + '\n', *args) def run_cmd_check_output(cmd, input_text=None, extra_paths=None): # If extra_paths is given, locate the executable in one of these directories. # Note: it would seem logical to add extra_paths to env[PATH], instead, and let OS do the job of finding the # executable for us. However this does not work on Windows: https://bugs.python.org/issue8557. if extra_paths: found = False extensions = [''] if sys.platform == 'win32': extensions.append('.exe') for path in extra_paths: for ext in extensions: fullpath = os.path.join(path, cmd[0] + ext) if os.path.exists(fullpath): cmd[0] = fullpath found = True break if found: break try: if input_text: input_text = input_text.encode() result = subprocess.run(cmd, capture_output=True, check=True, input=input_text) return result.stdout + result.stderr except (AttributeError, TypeError): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate(input_text) if p.returncode != 0: try: raise subprocess.CalledProcessError(p.returncode, cmd, stdout, stderr) except TypeError: raise subprocess.CalledProcessError(p.returncode, cmd, stdout) return stdout + stderr def to_shell_specific_paths(paths_list): if sys.platform == 'win32': paths_list = [p.replace('/', os.path.sep) if os.path.sep in p else p for p in paths_list] if 'MSYSTEM' in os.environ: paths_msys = run_cmd_check_output(['cygpath', '-u', '-f', '-'], input_text='\n'.join(paths_list)) paths_list = paths_msys.decode().strip().split('\n') return paths_list def get_env_for_extra_paths(extra_paths): """ Return a copy of environment variables dict, prepending paths listed in extra_paths to the PATH environment variable. """ env_arg = os.environ.copy() new_path = os.pathsep.join(extra_paths) + os.pathsep + env_arg['PATH'] if sys.version_info.major == 2: env_arg['PATH'] = new_path.encode('utf8') else: env_arg['PATH'] = new_path return env_arg def get_file_size_sha256(filename, block_size=65536): sha256 = hashlib.sha256() size = 0 with open(filename, 'rb') as f: for block in iter(lambda: f.read(block_size), b''): sha256.update(block) size += len(block) return size, sha256.hexdigest() def report_progress(count, block_size, total_size): percent = int(count * block_size * 100 / total_size) percent = min(100, percent) sys.stdout.write("\r%d%%" % percent) sys.stdout.flush() def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if exc.errno != errno.EEXIST or not os.path.isdir(path): raise def unpack(filename, destination): info('Extracting {0} to {1}'.format(filename, destination)) if filename.endswith('tar.gz'): archive_obj = tarfile.open(filename, 'r:gz') elif filename.endswith('zip'): archive_obj = zipfile.ZipFile(filename) else: raise NotImplementedError('Unsupported archive type') if sys.version_info.major == 2: # This is a workaround for the issue that unicode destination is not handled: # https://bugs.python.org/issue17153 destination = str(destination) archive_obj.extractall(destination) def strip_container_dirs(path, levels): assert levels > 0 # move the original directory out of the way (add a .tmp suffix) tmp_path = path + '.tmp' if os.path.exists(tmp_path): shutil.rmtree(tmp_path) os.rename(path, tmp_path) os.mkdir(path) base_path = tmp_path # walk given number of levels down for level in range(levels): contents = os.listdir(base_path) if len(contents) > 1: raise RuntimeError('at level {}, expected 1 entry, got {}'.format(level, contents)) base_path = os.path.join(base_path, contents[0]) if not os.path.isdir(base_path): raise RuntimeError('at level {}, {} is not a directory'.format(level, contents[0])) # get the list of directories/files to move contents = os.listdir(base_path) for name in contents: move_from = os.path.join(base_path, name) move_to = os.path.join(path, name) os.rename(move_from, move_to) shutil.rmtree(tmp_path) class ToolNotFound(RuntimeError): pass class ToolExecError(RuntimeError): pass class DownloadError(RuntimeError): pass class IDFToolDownload(object): def __init__(self, platform_name, url, size, sha256): self.platform_name = platform_name self.url = url self.size = size self.sha256 = sha256 self.platform_name = platform_name @functools.total_ordering class IDFToolVersion(object): STATUS_RECOMMENDED = 'recommended' STATUS_SUPPORTED = 'supported' STATUS_DEPRECATED = 'deprecated' STATUS_VALUES = [STATUS_RECOMMENDED, STATUS_SUPPORTED, STATUS_DEPRECATED] def __init__(self, version, status): self.version = version self.status = status self.downloads = OrderedDict() self.latest = False def __lt__(self, other): if self.status != other.status: return self.status > other.status else: assert not (self.status == IDFToolVersion.STATUS_RECOMMENDED and other.status == IDFToolVersion.STATUS_RECOMMENDED) return self.version < other.version def __eq__(self, other): return self.status == other.status and self.version == other.version def add_download(self, platform_name, url, size, sha256): self.downloads[platform_name] = IDFToolDownload(platform_name, url, size, sha256) def get_download_for_platform(self, platform_name): if platform_name in PLATFORM_FROM_NAME.keys(): platform_name = PLATFORM_FROM_NAME[platform_name] if platform_name in self.downloads.keys(): return self.downloads[platform_name] if 'any' in self.downloads.keys(): return self.downloads['any'] return None def compatible_with_platform(self, platform_name=PYTHON_PLATFORM): return self.get_download_for_platform(platform_name) is not None OPTIONS_LIST = ['version_cmd', 'version_regex', 'version_regex_replace', 'export_paths', 'export_vars', 'install', 'info_url', 'license', 'strip_container_dirs'] IDFToolOptions = namedtuple('IDFToolOptions', OPTIONS_LIST) class IDFTool(object): # possible values of 'install' field INSTALL_ALWAYS = 'always' INSTALL_ON_REQUEST = 'on_request' INSTALL_NEVER = 'never' def __init__(self, name, description, install, info_url, license, version_cmd, version_regex, version_regex_replace=None, strip_container_dirs=0): self.name = name self.description = description self.versions = OrderedDict() self.version_in_path = None self.versions_installed = [] if version_regex_replace is None: version_regex_replace = VERSION_REGEX_REPLACE_DEFAULT self.options = IDFToolOptions(version_cmd, version_regex, version_regex_replace, [], OrderedDict(), install, info_url, license, strip_container_dirs) self.platform_overrides = [] self._update_current_options() def _update_current_options(self): self._current_options = IDFToolOptions(*self.options) for override in self.platform_overrides: if CURRENT_PLATFORM not in override['platforms']: continue override_dict = override.copy() del override_dict['platforms'] self._current_options = self._current_options._replace(**override_dict) def add_version(self, version): assert(type(version) is IDFToolVersion) self.versions[version.version] = version def get_path(self): return os.path.join(global_idf_tools_path, 'tools', self.name) def get_path_for_version(self, version): assert(version in self.versions) return os.path.join(self.get_path(), version) def get_export_paths(self, version): tool_path = self.get_path_for_version(version) return [os.path.join(tool_path, *p) for p in self._current_options.export_paths] def get_export_vars(self, version): """ Get the dictionary of environment variables to be exported, for the given version. Expands: - ${TOOL_PATH} => the actual path where the version is installed """ result = {} for k, v in self._current_options.export_vars.items(): replace_path = self.get_path_for_version(version).replace('\\', '\\\\') v_repl = re.sub(SUBST_TOOL_PATH_REGEX, replace_path, v) if v_repl != v: v_repl = to_shell_specific_paths([v_repl])[0] result[k] = v_repl return result def check_version(self, extra_paths=None): """ Execute the tool, optionally prepending extra_paths to PATH, extract the version string and return it as a result. Raises ToolNotFound if the tool is not found (not present in the paths). Raises ToolExecError if the tool returns with a non-zero exit code. Returns 'unknown' if tool returns something from which version string can not be extracted. """ cmd = self._current_options.version_cmd try: version_cmd_result = run_cmd_check_output(cmd, None, extra_paths) except OSError: # tool is not on the path raise ToolNotFound('Tool {} not found'.format(self.name)) except subprocess.CalledProcessError as e: raise ToolExecError('Command {} has returned non-zero exit code ({})\n'.format( ' '.join(self._current_options.version_cmd), e.returncode)) in_str = version_cmd_result.decode() match = re.search(self._current_options.version_regex, in_str) if not match: return UNKNOWN_VERSION return re.sub(self._current_options.version_regex, self._current_options.version_regex_replace, match.group(0)) def get_install_type(self): return self._current_options.install def get_recommended_version(self): recommended_versions = [k for k, v in self.versions.items() if v.status == IDFToolVersion.STATUS_RECOMMENDED and v.compatible_with_platform()] assert len(recommended_versions) <= 1 if recommended_versions: return recommended_versions[0] return None def get_preferred_installed_version(self): recommended_versions = [k for k in self.versions_installed if self.versions[k].status == IDFToolVersion.STATUS_RECOMMENDED and self.versions[k].compatible_with_platform()] assert len(recommended_versions) <= 1 if recommended_versions: return recommended_versions[0] return None def find_installed_versions(self): """ Checks whether the tool can be found in PATH and in global_idf_tools_path. Writes results to self.version_in_path and self.versions_installed. """ # First check if the tool is in system PATH try: ver_str = self.check_version() except ToolNotFound: # not in PATH pass except ToolExecError: warn('tool {} found in path, but failed to run'.format(self.name)) else: self.version_in_path = ver_str # Now check all the versions installed in global_idf_tools_path self.versions_installed = [] for version, version_obj in self.versions.items(): if not version_obj.compatible_with_platform(): continue tool_path = self.get_path_for_version(version) if not os.path.exists(tool_path): # version not installed continue try: ver_str = self.check_version(self.get_export_paths(version)) except ToolNotFound: warn('directory for tool {} version {} is present, but tool was not found'.format( self.name, version)) except ToolExecError: warn('tool {} version {} is installed, but the tool failed to run'.format( self.name, version)) else: if ver_str != version: warn('tool {} version {} is installed, but has reported version {}'.format( self.name, version, ver_str)) else: self.versions_installed.append(version) def download(self, version): assert(version in self.versions) download_obj = self.versions[version].get_download_for_platform(PYTHON_PLATFORM) if not download_obj: fatal('No packages for tool {} platform {}!'.format(self.name, PYTHON_PLATFORM)) raise DownloadError() url = download_obj.url archive_name = os.path.basename(url) local_path = os.path.join(global_idf_tools_path, 'dist', archive_name) mkdir_p(os.path.dirname(local_path)) if os.path.isfile(local_path): if not self.check_download_file(download_obj, local_path): warn('removing downloaded file {0} and downloading again'.format(archive_name)) os.unlink(local_path) else: info('file {0} is already downloaded'.format(archive_name)) return downloaded = False for retry in range(DOWNLOAD_RETRY_COUNT): local_temp_path = local_path + '.tmp' info('Downloading {} to {}'.format(archive_name, local_temp_path)) urlretrieve(url, local_temp_path, report_progress if not global_non_interactive else None) sys.stdout.write("\rDone\n") sys.stdout.flush() if not self.check_download_file(download_obj, local_temp_path): warn('Failed to download file {}'.format(local_temp_path)) continue os.rename(local_temp_path, local_path) downloaded = True break if not downloaded: fatal('Failed to download, and retry count has expired') raise DownloadError() def install(self, version): # Currently this is called after calling 'download' method, so here are a few asserts # for the conditions which should be true once that method is done. assert (version in self.versions) download_obj = self.versions[version].get_download_for_platform(PYTHON_PLATFORM) assert (download_obj is not None) archive_name = os.path.basename(download_obj.url) archive_path = os.path.join(global_idf_tools_path, 'dist', archive_name) assert (os.path.isfile(archive_path)) dest_dir = self.get_path_for_version(version) if os.path.exists(dest_dir): warn('destination path already exists, removing') shutil.rmtree(dest_dir) mkdir_p(dest_dir) unpack(archive_path, dest_dir) if self._current_options.strip_container_dirs: strip_container_dirs(dest_dir, self._current_options.strip_container_dirs) @staticmethod def check_download_file(download_obj, local_path): expected_sha256 = download_obj.sha256 expected_size = download_obj.size file_size, file_sha256 = get_file_size_sha256(local_path) if file_size != expected_size: warn('file size mismatch for {}, expected {}, got {}'.format(local_path, expected_size, file_size)) return False if file_sha256 != expected_sha256: warn('hash mismatch for {}, expected {}, got {}'.format(local_path, expected_sha256, file_sha256)) return False return True @classmethod def from_json(cls, tool_dict): # json.load will return 'str' types in Python 3 and 'unicode' in Python 2 expected_str_type = type(u'') # Validate json fields tool_name = tool_dict.get('name') if type(tool_name) is not expected_str_type: raise RuntimeError('tool_name is not a string') description = tool_dict.get('description') if type(description) is not expected_str_type: raise RuntimeError('description is not a string') version_cmd = tool_dict.get('version_cmd') if type(version_cmd) is not list: raise RuntimeError('version_cmd for tool %s is not a list of strings' % tool_name) version_regex = tool_dict.get('version_regex') if type(version_regex) is not expected_str_type or not version_regex: raise RuntimeError('version_regex for tool %s is not a non-empty string' % tool_name) version_regex_replace = tool_dict.get('version_regex_replace') if version_regex_replace and type(version_regex_replace) is not expected_str_type: raise RuntimeError('version_regex_replace for tool %s is not a string' % tool_name) export_paths = tool_dict.get('export_paths') if type(export_paths) is not list: raise RuntimeError('export_paths for tool %s is not a list' % tool_name) export_vars = tool_dict.get('export_vars', {}) if type(export_vars) is not dict: raise RuntimeError('export_vars for tool %s is not a mapping' % tool_name) versions = tool_dict.get('versions') if type(versions) is not list: raise RuntimeError('versions for tool %s is not an array' % tool_name) install = tool_dict.get('install', False) if type(install) is not expected_str_type: raise RuntimeError('install for tool %s is not a string' % tool_name) info_url = tool_dict.get('info_url', False) if type(info_url) is not expected_str_type: raise RuntimeError('info_url for tool %s is not a string' % tool_name) license = tool_dict.get('license', False) if type(license) is not expected_str_type: raise RuntimeError('license for tool %s is not a string' % tool_name) strip_container_dirs = tool_dict.get('strip_container_dirs', 0) if strip_container_dirs and type(strip_container_dirs) is not int: raise RuntimeError('strip_container_dirs for tool %s is not an int' % tool_name) overrides_list = tool_dict.get('platform_overrides', []) if type(overrides_list) is not list: raise RuntimeError('platform_overrides for tool %s is not a list' % tool_name) # Create the object tool_obj = cls(tool_name, description, install, info_url, license, version_cmd, version_regex, version_regex_replace, strip_container_dirs) for path in export_paths: tool_obj.options.export_paths.append(path) for name, value in export_vars.items(): tool_obj.options.export_vars[name] = value for index, override in enumerate(overrides_list): platforms_list = override.get('platforms') if type(platforms_list) is not list: raise RuntimeError('platforms for override %d of tool %s is not a list' % (index, tool_name)) install = override.get('install') if install is not None and type(install) is not expected_str_type: raise RuntimeError('install for override %d of tool %s is not a string' % (index, tool_name)) version_cmd = override.get('version_cmd') if version_cmd is not None and type(version_cmd) is not list: raise RuntimeError('version_cmd for override %d of tool %s is not a list of strings' % (index, tool_name)) version_regex = override.get('version_regex') if version_regex is not None and (type(version_regex) is not expected_str_type or not version_regex): raise RuntimeError('version_regex for override %d of tool %s is not a non-empty string' % (index, tool_name)) version_regex_replace = override.get('version_regex_replace') if version_regex_replace is not None and type(version_regex_replace) is not expected_str_type: raise RuntimeError('version_regex_replace for override %d of tool %s is not a string' % (index, tool_name)) export_paths = override.get('export_paths') if export_paths is not None and type(export_paths) is not list: raise RuntimeError('export_paths for override %d of tool %s is not a list' % (index, tool_name)) export_vars = override.get('export_vars') if export_vars is not None and type(export_vars) is not dict: raise RuntimeError('export_vars for override %d of tool %s is not a mapping' % (index, tool_name)) tool_obj.platform_overrides.append(override) recommended_versions = {} for version_dict in versions: version = version_dict.get('name') if type(version) is not expected_str_type: raise RuntimeError('version name for tool {} is not a string'.format(tool_name)) version_status = version_dict.get('status') if type(version_status) is not expected_str_type and version_status not in IDFToolVersion.STATUS_VALUES: raise RuntimeError('tool {} version {} status is not one of {}', tool_name, version, IDFToolVersion.STATUS_VALUES) version_obj = IDFToolVersion(version, version_status) for platform_id, platform_dict in version_dict.items(): if platform_id in ['name', 'status']: continue if platform_id not in PLATFORM_FROM_NAME.keys(): raise RuntimeError('invalid platform %s for tool %s version %s' % (platform_id, tool_name, version)) version_obj.add_download(platform_id, platform_dict['url'], platform_dict['size'], platform_dict['sha256']) if version_status == IDFToolVersion.STATUS_RECOMMENDED: if platform_id not in recommended_versions: recommended_versions[platform_id] = [] recommended_versions[platform_id].append(version) tool_obj.add_version(version_obj) for platform_id, version_list in recommended_versions.items(): if len(version_list) > 1: raise RuntimeError('tool {} for platform {} has {} recommended versions'.format( tool_name, platform_id, len(recommended_versions))) if install != IDFTool.INSTALL_NEVER and len(recommended_versions) == 0: raise RuntimeError('required/optional tool {} for platform {} has no recommended versions'.format( tool_name, platform_id)) tool_obj._update_current_options() return tool_obj def to_json(self): versions_array = [] for version, version_obj in self.versions.items(): version_json = { 'name': version, 'status': version_obj.status } for platform_id, download in version_obj.downloads.items(): version_json[platform_id] = { 'url': download.url, 'size': download.size, 'sha256': download.sha256 } versions_array.append(version_json) overrides_array = self.platform_overrides tool_json = { 'name': self.name, 'description': self.description, 'export_paths': self.options.export_paths, 'export_vars': self.options.export_vars, 'install': self.options.install, 'info_url': self.options.info_url, 'license': self.options.license, 'version_cmd': self.options.version_cmd, 'version_regex': self.options.version_regex, 'versions': versions_array, } if self.options.version_regex_replace != VERSION_REGEX_REPLACE_DEFAULT: tool_json['version_regex_replace'] = self.options.version_regex_replace if overrides_array: tool_json['platform_overrides'] = overrides_array if self.options.strip_container_dirs: tool_json['strip_container_dirs'] = self.options.strip_container_dirs return tool_json def load_tools_info(): """ Load tools metadata from tools.json, return a dictionary: tool name - tool info """ tool_versions_file_name = global_tools_json with open(tool_versions_file_name, 'r') as f: tools_info = json.load(f) return parse_tools_info_json(tools_info) def parse_tools_info_json(tools_info): """ Parse and validate the dictionary obtained by loading the tools.json file. Returns a dictionary of tools (key: tool name, value: IDFTool object). """ if tools_info['version'] != TOOLS_FILE_VERSION: raise RuntimeError('Invalid version') tools_dict = OrderedDict() tools_array = tools_info.get('tools') if type(tools_array) is not list: raise RuntimeError('tools property is missing or not an array') for tool_dict in tools_array: tool = IDFTool.from_json(tool_dict) tools_dict[tool.name] = tool return tools_dict def dump_tools_json(tools_info): tools_array = [] for tool_name, tool_obj in tools_info.items(): tool_json = tool_obj.to_json() tools_array.append(tool_json) file_json = {'version': TOOLS_FILE_VERSION, 'tools': tools_array} return json.dumps(file_json, indent=2, separators=(',', ': '), sort_keys=True) def get_python_env_path(): python_ver_major_minor = '{}.{}'.format(sys.version_info.major, sys.version_info.minor) version_file_path = os.path.join(global_idf_path, 'version.txt') if os.path.exists(version_file_path): with open(version_file_path, "r") as version_file: idf_version_str = version_file.read() else: idf_version_str = subprocess.check_output(['git', '-C', global_idf_path, 'describe', '--tags'], cwd=global_idf_path, env=os.environ).decode() match = re.search(r'v([0-9]+\.[0-9]+).*', idf_version_str) idf_version = match.group(1) idf_python_env_path = os.path.join(global_idf_tools_path, 'python_env', 'rtos{}_py{}_env'.format(idf_version, python_ver_major_minor)) if sys.platform == 'win32': subdir = 'Scripts' python_exe = 'python.exe' else: subdir = 'bin' python_exe = 'python' idf_python_export_path = os.path.join(idf_python_env_path, subdir) virtualenv_python = os.path.join(idf_python_export_path, python_exe) return idf_python_env_path, idf_python_export_path, virtualenv_python def action_list(args): tools_info = load_tools_info() for name, tool in tools_info.items(): if tool.get_install_type() == IDFTool.INSTALL_NEVER: continue optional_str = ' (optional)' if tool.get_install_type() == IDFTool.INSTALL_ON_REQUEST else '' info('* {}: {}{}'.format(name, tool.description, optional_str)) tool.find_installed_versions() versions_for_platform = {k: v for k, v in tool.versions.items() if v.compatible_with_platform()} if not versions_for_platform: info(' (no versions compatible with platform {})'.format(PYTHON_PLATFORM)) continue versions_sorted = sorted(versions_for_platform.keys(), key=tool.versions.get, reverse=True) for version in versions_sorted: version_obj = tool.versions[version] info(' - {} ({}{})'.format(version, version_obj.status, ', installed' if version in tool.versions_installed else '')) def action_check(args): tools_info = load_tools_info() not_found_list = [] info('Checking for installed tools...') for name, tool in tools_info.items(): if tool.get_install_type() == IDFTool.INSTALL_NEVER: continue tool_found_somewhere = False info('Checking tool %s' % name) tool.find_installed_versions() if tool.version_in_path: info(' version found in PATH: %s' % tool.version_in_path) tool_found_somewhere = True else: info(' no version found in PATH') for version in tool.versions_installed: info(' version installed in tools directory: %s' % version) tool_found_somewhere = True if not tool_found_somewhere and tool.get_install_type() == IDFTool.INSTALL_ALWAYS: not_found_list.append(name) if not_found_list: fatal('The following required tools were not found: ' + ' '.join(not_found_list)) raise SystemExit(1) def action_export(args): tools_info = load_tools_info() all_tools_found = True export_vars = {} paths_to_export = [] for name, tool in tools_info.items(): if tool.get_install_type() == IDFTool.INSTALL_NEVER: continue tool.find_installed_versions() if tool.version_in_path: if tool.version_in_path not in tool.versions: # unsupported version if args.prefer_system: warn('using an unsupported version of tool {} found in PATH: {}'.format( tool.name, tool.version_in_path)) continue else: # unsupported version in path pass else: # supported/deprecated version in PATH, use it version_obj = tool.versions[tool.version_in_path] if version_obj.status == IDFToolVersion.STATUS_SUPPORTED: info('Using a supported version of tool {} found in PATH: {}.'.format(name, tool.version_in_path), f=sys.stderr) info('However the recommended version is {}.'.format(tool.get_recommended_version()), f=sys.stderr) elif version_obj.status == IDFToolVersion.STATUS_DEPRECATED: warn('using a deprecated version of tool {} found in PATH: {}'.format(name, tool.version_in_path)) continue self_restart_cmd = '{} {}{}'.format(sys.executable, __file__, (' --tools-json ' + args.tools_json) if args.tools_json else '') self_restart_cmd = to_shell_specific_paths([self_restart_cmd])[0] if IDF_TOOLS_EXPORT_CMD: prefer_system_hint = '' else: prefer_system_hint = ' To use it, run \'{} export --prefer-system\''.format(self_restart_cmd) if IDF_TOOLS_INSTALL_CMD: install_cmd = to_shell_specific_paths([IDF_TOOLS_INSTALL_CMD])[0] else: install_cmd = self_restart_cmd + ' install' if not tool.versions_installed: if tool.get_install_type() == IDFTool.INSTALL_ALWAYS: all_tools_found = False fatal('tool {} has no installed versions. Please run \'{}\' to install it.'.format( tool.name, install_cmd)) if tool.version_in_path and tool.version_in_path not in tool.versions: info('An unsupported version of tool {} was found in PATH: {}. '.format(name, tool.version_in_path) + prefer_system_hint, f=sys.stderr) continue else: # tool is optional, and does not have versions installed # use whatever is available in PATH continue if tool.version_in_path and tool.version_in_path not in tool.versions: info('Not using an unsupported version of tool {} found in PATH: {}.'.format( tool.name, tool.version_in_path) + prefer_system_hint, f=sys.stderr) version_to_use = tool.get_preferred_installed_version() export_paths = tool.get_export_paths(version_to_use) if export_paths: paths_to_export += export_paths tool_export_vars = tool.get_export_vars(version_to_use) for k, v in tool_export_vars.items(): old_v = os.environ.get(k) if old_v is None or old_v != v: export_vars[k] = v current_path = os.getenv('PATH') idf_python_env_path, idf_python_export_path, virtualenv_python = get_python_env_path() if os.path.exists(virtualenv_python): idf_python_env_path = to_shell_specific_paths([idf_python_env_path])[0] if os.getenv('IDF_PYTHON_ENV_PATH') != idf_python_env_path: export_vars['IDF_PYTHON_ENV_PATH'] = to_shell_specific_paths([idf_python_env_path])[0] if idf_python_export_path not in current_path: paths_to_export.append(idf_python_export_path) idf_tools_dir = os.path.join(global_idf_path, 'tools') idf_tools_dir = to_shell_specific_paths([idf_tools_dir])[0] if idf_tools_dir not in current_path: paths_to_export.append(idf_tools_dir) if sys.platform == 'win32' and 'MSYSTEM' not in os.environ: old_path = '%PATH%' path_sep = ';' else: old_path = '$PATH' # can't trust os.pathsep here, since for Windows Python started from MSYS shell, # os.pathsep will be ';' path_sep = ':' if args.format == EXPORT_SHELL: if sys.platform == 'win32' and 'MSYSTEM' not in os.environ: export_format = 'SET "{}={}"' export_sep = '\n' else: export_format = 'export {}="{}"' export_sep = ';' elif args.format == EXPORT_KEY_VALUE: export_format = '{}={}' export_sep = '\n' else: raise NotImplementedError('unsupported export format {}'.format(args.format)) if paths_to_export: export_vars['PATH'] = path_sep.join(to_shell_specific_paths(paths_to_export) + [old_path]) export_statements = export_sep.join([export_format.format(k, v) for k, v in export_vars.items()]) if export_statements: print(export_statements) if not all_tools_found: raise SystemExit(1) def apply_mirror_prefix_map(args, tool_obj, tool_version): """Rewrite URL for given tool_obj, given tool_version, and current platform, if --mirror-prefix-map flag or IDF_MIRROR_PREFIX_MAP environment variable is given. """ mirror_prefix_map = None mirror_prefix_map_env = os.getenv('IDF_MIRROR_PREFIX_MAP') if mirror_prefix_map_env: mirror_prefix_map = mirror_prefix_map_env.split(';') if IDF_MAINTAINER and args.mirror_prefix_map: if mirror_prefix_map: warn('Both IDF_MIRROR_PREFIX_MAP environment variable and --mirror-prefix-map flag are specified, ' + 'will use the value from the command line.') mirror_prefix_map = args.mirror_prefix_map download_obj = tool_obj.versions[tool_version].get_download_for_platform(PYTHON_PLATFORM) if mirror_prefix_map and download_obj: for item in mirror_prefix_map: if URL_PREFIX_MAP_SEPARATOR not in item: warn('invalid mirror-prefix-map item (missing \'{}\') {}'.format(URL_PREFIX_MAP_SEPARATOR, item)) continue search, replace = item.split(URL_PREFIX_MAP_SEPARATOR, 1) old_url = download_obj.url new_url = re.sub(search, replace, old_url) if new_url != old_url: info('Changed download URL: {} => {}'.format(old_url, new_url)) download_obj.url = new_url break def action_install(args): tools_info = load_tools_info() tools_spec = args.tools if not tools_spec: tools_spec = [k for k, v in tools_info.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS] info('Installing tools: {}'.format(', '.join(tools_spec))) elif 'all' in tools_spec: tools_spec = [k for k, v in tools_info.items() if v.get_install_type() != IDFTool.INSTALL_NEVER] info('Installing tools: {}'.format(', '.join(tools_spec))) for tool_spec in tools_spec: if '@' not in tool_spec: tool_name = tool_spec tool_version = None else: tool_name, tool_version = tool_spec.split('@', 1) if tool_name not in tools_info: fatal('unknown tool name: {}'.format(tool_name)) raise SystemExit(1) tool_obj = tools_info[tool_name] if tool_version is not None and tool_version not in tool_obj.versions: fatal('unknown version for tool {}: {}'.format(tool_name, tool_version)) raise SystemExit(1) if tool_version is None: tool_version = tool_obj.get_recommended_version() assert tool_version is not None tool_obj.find_installed_versions() tool_spec = '{}@{}'.format(tool_name, tool_version) if tool_version in tool_obj.versions_installed: info('Skipping {} (already installed)'.format(tool_spec)) continue info('Installing {}'.format(tool_spec)) apply_mirror_prefix_map(args, tool_obj, tool_version) tool_obj.download(tool_version) tool_obj.install(tool_version) def action_install_python_env(args): idf_python_env_path, _, virtualenv_python = get_python_env_path() if args.reinstall and os.path.exists(idf_python_env_path): warn('Removing the existing Python environment in {}'.format(idf_python_env_path)) shutil.rmtree(idf_python_env_path) if not os.path.exists(virtualenv_python): info('Creating a new Python environment in {}'.format(idf_python_env_path)) try: import virtualenv # noqa: F401 except ImportError: info('Installing virtualenv') subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--user', 'virtualenv'], stdout=sys.stdout, stderr=sys.stderr) subprocess.check_call([sys.executable, '-m', 'virtualenv', idf_python_env_path], stdout=sys.stdout, stderr=sys.stderr) run_args = [virtualenv_python, '-m', 'pip', 'install', '--no-warn-script-location'] requirements_txt = os.path.join(global_idf_path, 'requirements.txt') run_args += ['-r', requirements_txt] if args.extra_wheels_dir: run_args += ['--find-links', args.extra_wheels_dir] info('Installing Python packages from {}'.format(requirements_txt)) subprocess.check_call(run_args, stdout=sys.stdout, stderr=sys.stderr) def action_add_version(args): tools_info = load_tools_info() tool_name = args.tool tool_obj = tools_info.get(tool_name) if not tool_obj: info('Creating new tool entry for {}'.format(tool_name)) tool_obj = IDFTool(tool_name, TODO_MESSAGE, IDFTool.INSTALL_ALWAYS, TODO_MESSAGE, TODO_MESSAGE, [TODO_MESSAGE], TODO_MESSAGE) tools_info[tool_name] = tool_obj version = args.version version_obj = tool_obj.versions.get(version) if version not in tool_obj.versions: info('Creating new version {}'.format(version)) version_obj = IDFToolVersion(version, IDFToolVersion.STATUS_SUPPORTED) tool_obj.versions[version] = version_obj url_prefix = args.url_prefix or 'https://%s/' % TODO_MESSAGE for file_path in args.files: file_name = os.path.basename(file_path) # Guess which platform this file is for found_platform = None for platform_alias, platform_id in PLATFORM_FROM_NAME.items(): if platform_alias in file_name: found_platform = platform_id break if found_platform is None: info('Could not guess platform for file {}'.format(file_name)) found_platform = TODO_MESSAGE # Get file size and calculate the SHA256 file_size, file_sha256 = get_file_size_sha256(file_path) url = url_prefix + file_name info('Adding download for platform {}'.format(found_platform)) info(' size: {}'.format(file_size)) info(' SHA256: {}'.format(file_sha256)) info(' URL: {}'.format(url)) version_obj.add_download(found_platform, url, file_size, file_sha256) json_str = dump_tools_json(tools_info) if not args.output: args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW) with open(args.output, 'w') as f: f.write(json_str) f.write('\n') info('Wrote output to {}'.format(args.output)) def action_rewrite(args): tools_info = load_tools_info() json_str = dump_tools_json(tools_info) if not args.output: args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW) with open(args.output, 'w') as f: f.write(json_str) f.write('\n') info('Wrote output to {}'.format(args.output)) def action_validate(args): try: import jsonschema except ImportError: fatal('You need to install jsonschema package to use validate command') raise SystemExit(1) with open(os.path.join(global_idf_path, TOOLS_FILE), 'r') as tools_file: tools_json = json.load(tools_file) with open(os.path.join(global_idf_path, TOOLS_SCHEMA_FILE), 'r') as schema_file: schema_json = json.load(schema_file) jsonschema.validate(tools_json, schema_json) # on failure, this will raise an exception with a fairly verbose diagnostic message def main(argv): parser = argparse.ArgumentParser() parser.add_argument('--quiet', help='Don\'t output diagnostic messages to stdout/stderr', action='store_true') parser.add_argument('--non-interactive', help='Don\'t output interactive messages and questions', action='store_true') parser.add_argument('--tools-json', help='Path to the tools.json file to use') parser.add_argument('--idf-path', help='ESP-IDF path to use') subparsers = parser.add_subparsers(dest='action') subparsers.add_parser('list', help='List tools and versions available') subparsers.add_parser('check', help='Print summary of tools installed or found in PATH') export = subparsers.add_parser('export', help='Output command for setting tool paths, suitable for shell') export.add_argument('--format', choices=[EXPORT_SHELL, EXPORT_KEY_VALUE], default=EXPORT_SHELL, help='Format of the output: shell (suitable for printing into shell), ' + 'or key-value (suitable for parsing by other tools') export.add_argument('--prefer-system', help='Normally, if the tool is already present in PATH, ' + 'but has an unsupported version, a version from the tools directory ' + 'will be used instead. If this flag is given, the version in PATH ' + 'will be used.', action='store_true') install = subparsers.add_parser('install', help='Download and install tools into the tools directory') if IDF_MAINTAINER: install.add_argument('--mirror-prefix-map', nargs='*', help='Pattern to rewrite download URLs, with source and replacement separated by comma.' + ' E.g. http://foo.com,http://test.foo.com') install.add_argument('tools', nargs='*', help='Tools to install. ' + 'To install a specific version use tool_name@version syntax.' + 'Use \'all\' to install all tools, including the optional ones.') install_python_env = subparsers.add_parser('install-python-env', help='Create Python virtual environment and install the ' + 'required Python packages') install_python_env.add_argument('--reinstall', help='Discard the previously installed environment', action='store_true') install_python_env.add_argument('--extra-wheels-dir', help='Additional directories with wheels ' + 'to use during installation') if IDF_MAINTAINER: add_version = subparsers.add_parser('add-version', help='Add or update download info for a version') add_version.add_argument('--output', help='Save new tools.json into this file') add_version.add_argument('--tool', help='Tool name to set add a version for', required=True) add_version.add_argument('--version', help='Version identifier', required=True) add_version.add_argument('--url-prefix', help='String to prepend to file names to obtain download URLs') add_version.add_argument('files', help='File names of the download artifacts', nargs='*') rewrite = subparsers.add_parser('rewrite', help='Load tools.json, validate, and save the result back into JSON') rewrite.add_argument('--output', help='Save new tools.json into this file') subparsers.add_parser('validate', help='Validate tools.json against schema file') args = parser.parse_args(argv) if args.action is None: parser.print_help() parser.exit(1) if args.quiet: global global_quiet global_quiet = True if args.non_interactive: global global_non_interactive global_non_interactive = True global global_idf_path global_idf_path = os.environ.get('IDF_PATH') if args.idf_path: global_idf_path = args.idf_path if not global_idf_path: global_idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) global global_idf_tools_path global_idf_tools_path = os.environ.get('IDF_TOOLS_PATH') or os.path.expanduser(IDF_TOOLS_PATH_DEFAULT) if sys.version_info.major == 2: try: global_idf_tools_path.decode('ascii') except UnicodeDecodeError: fatal('IDF_TOOLS_PATH contains non-ASCII characters: {}'.format(global_idf_tools_path) + '\nThis is not supported yet with Python 2. ' + 'Please set IDF_TOOLS_PATH to a directory with an ASCII name, or switch to Python 3.') raise SystemExit(1) if CURRENT_PLATFORM == UNKNOWN_PLATFORM: fatal('Platform {} appears to be unsupported'.format(PYTHON_PLATFORM)) raise SystemExit(1) global global_tools_json if args.tools_json: global_tools_json = args.tools_json else: global_tools_json = os.path.join(global_idf_path, TOOLS_FILE) action_func_name = 'action_' + args.action.replace('-', '_') action_func = globals()[action_func_name] action_func(args) if __name__ == '__main__': main(sys.argv[1:])
Microvellum/Fluid-Designer
refs/heads/master
win64-vc/2.78/python/lib/xmlrpc/client.py
2
# # XML-RPC CLIENT LIBRARY # $Id$ # # an XML-RPC client interface for Python. # # the marshalling and response parser code can also be used to # implement XML-RPC servers. # # Notes: # this version is designed to work with Python 2.1 or newer. # # History: # 1999-01-14 fl Created # 1999-01-15 fl Changed dateTime to use localtime # 1999-01-16 fl Added Binary/base64 element, default to RPC2 service # 1999-01-19 fl Fixed array data element (from Skip Montanaro) # 1999-01-21 fl Fixed dateTime constructor, etc. # 1999-02-02 fl Added fault handling, handle empty sequences, etc. # 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro) # 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8) # 2000-11-28 fl Changed boolean to check the truth value of its argument # 2001-02-24 fl Added encoding/Unicode/SafeTransport patches # 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1) # 2001-03-28 fl Make sure response tuple is a singleton # 2001-03-29 fl Don't require empty params element (from Nicholas Riley) # 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2) # 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod) # 2001-09-03 fl Allow Transport subclass to override getparser # 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup) # 2001-10-01 fl Remove containers from memo cache when done with them # 2001-10-01 fl Use faster escape method (80% dumps speedup) # 2001-10-02 fl More dumps microtuning # 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum) # 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow # 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems) # 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix) # 2002-03-17 fl Avoid buffered read when possible (from James Rucker) # 2002-04-07 fl Added pythondoc comments # 2002-04-16 fl Added __str__ methods to datetime/binary wrappers # 2002-05-15 fl Added error constants (from Andrew Kuchling) # 2002-06-27 fl Merged with Python CVS version # 2002-10-22 fl Added basic authentication (based on code from Phillip Eby) # 2003-01-22 sm Add support for the bool type # 2003-02-27 gvr Remove apply calls # 2003-04-24 sm Use cStringIO if available # 2003-04-25 ak Add support for nil # 2003-06-15 gn Add support for time.struct_time # 2003-07-12 gp Correct marshalling of Faults # 2003-10-31 mvl Add multicall support # 2004-08-20 mvl Bump minimum supported Python version to 2.1 # 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability # # Copyright (c) 1999-2002 by Secret Labs AB. # Copyright (c) 1999-2002 by Fredrik Lundh. # # info@pythonware.com # http://www.pythonware.com # # -------------------------------------------------------------------- # The XML-RPC client interface is # # Copyright (c) 1999-2002 by Secret Labs AB # Copyright (c) 1999-2002 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- """ An XML-RPC client interface for Python. The marshalling and response parser code can also be used to implement XML-RPC servers. Exported exceptions: Error Base class for client errors ProtocolError Indicates an HTTP protocol error ResponseError Indicates a broken response package Fault Indicates an XML-RPC fault package Exported classes: ServerProxy Represents a logical connection to an XML-RPC server MultiCall Executor of boxcared xmlrpc requests DateTime dateTime wrapper for an ISO 8601 string or time tuple or localtime integer value to generate a "dateTime.iso8601" XML-RPC value Binary binary data wrapper Marshaller Generate an XML-RPC params chunk from a Python data structure Unmarshaller Unmarshal an XML-RPC response from incoming XML event message Transport Handles an HTTP transaction to an XML-RPC server SafeTransport Handles an HTTPS transaction to an XML-RPC server Exported constants: (none) Exported functions: getparser Create instance of the fastest available parser & attach to an unmarshalling object dumps Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). loads Convert an XML-RPC packet to unmarshalled data plus a method name (None if not present). """ import base64 import sys import time from datetime import datetime import http.client import urllib.parse from xml.parsers import expat import errno from io import BytesIO try: import gzip except ImportError: gzip = None #python can be built without zlib/gzip support # -------------------------------------------------------------------- # Internal stuff def escape(s): s = s.replace("&", "&amp;") s = s.replace("<", "&lt;") return s.replace(">", "&gt;",) # used in User-Agent header sent __version__ = sys.version[:3] # xmlrpc integer limits MAXINT = 2**31-1 MININT = -2**31 # -------------------------------------------------------------------- # Error constants (from Dan Libby's specification at # http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php) # Ranges of errors PARSE_ERROR = -32700 SERVER_ERROR = -32600 APPLICATION_ERROR = -32500 SYSTEM_ERROR = -32400 TRANSPORT_ERROR = -32300 # Specific errors NOT_WELLFORMED_ERROR = -32700 UNSUPPORTED_ENCODING = -32701 INVALID_ENCODING_CHAR = -32702 INVALID_XMLRPC = -32600 METHOD_NOT_FOUND = -32601 INVALID_METHOD_PARAMS = -32602 INTERNAL_ERROR = -32603 # -------------------------------------------------------------------- # Exceptions ## # Base class for all kinds of client-side errors. class Error(Exception): """Base class for client errors.""" def __str__(self): return repr(self) ## # Indicates an HTTP-level protocol error. This is raised by the HTTP # transport layer, if the server returns an error code other than 200 # (OK). # # @param url The target URL. # @param errcode The HTTP error code. # @param errmsg The HTTP error message. # @param headers The HTTP header dictionary. class ProtocolError(Error): """Indicates an HTTP protocol error.""" def __init__(self, url, errcode, errmsg, headers): Error.__init__(self) self.url = url self.errcode = errcode self.errmsg = errmsg self.headers = headers def __repr__(self): return ( "<%s for %s: %s %s>" % (self.__class__.__name__, self.url, self.errcode, self.errmsg) ) ## # Indicates a broken XML-RPC response package. This exception is # raised by the unmarshalling layer, if the XML-RPC response is # malformed. class ResponseError(Error): """Indicates a broken response package.""" pass ## # Indicates an XML-RPC fault response package. This exception is # raised by the unmarshalling layer, if the XML-RPC response contains # a fault string. This exception can also be used as a class, to # generate a fault XML-RPC message. # # @param faultCode The XML-RPC fault code. # @param faultString The XML-RPC fault string. class Fault(Error): """Indicates an XML-RPC fault package.""" def __init__(self, faultCode, faultString, **extra): Error.__init__(self) self.faultCode = faultCode self.faultString = faultString def __repr__(self): return "<%s %s: %r>" % (self.__class__.__name__, self.faultCode, self.faultString) # -------------------------------------------------------------------- # Special values ## # Backwards compatibility boolean = Boolean = bool ## # Wrapper for XML-RPC DateTime values. This converts a time value to # the format used by XML-RPC. # <p> # The value can be given as a datetime object, as a string in the # format "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by # time.localtime()), or an integer value (as returned by time.time()). # The wrapper uses time.localtime() to convert an integer to a time # tuple. # # @param value The time, given as a datetime object, an ISO 8601 string, # a time tuple, or an integer time value. # Issue #13305: different format codes across platforms _day0 = datetime(1, 1, 1) if _day0.strftime('%Y') == '0001': # Mac OS X def _iso8601_format(value): return value.strftime("%Y%m%dT%H:%M:%S") elif _day0.strftime('%4Y') == '0001': # Linux def _iso8601_format(value): return value.strftime("%4Y%m%dT%H:%M:%S") else: def _iso8601_format(value): return value.strftime("%Y%m%dT%H:%M:%S").zfill(17) del _day0 def _strftime(value): if isinstance(value, datetime): return _iso8601_format(value) if not isinstance(value, (tuple, time.struct_time)): if value == 0: value = time.time() value = time.localtime(value) return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] class DateTime: """DateTime wrapper for an ISO 8601 string or time tuple or localtime integer value to generate 'dateTime.iso8601' XML-RPC value. """ def __init__(self, value=0): if isinstance(value, str): self.value = value else: self.value = _strftime(value) def make_comparable(self, other): if isinstance(other, DateTime): s = self.value o = other.value elif isinstance(other, datetime): s = self.value o = _iso8601_format(other) elif isinstance(other, str): s = self.value o = other elif hasattr(other, "timetuple"): s = self.timetuple() o = other.timetuple() else: otype = (hasattr(other, "__class__") and other.__class__.__name__ or type(other)) raise TypeError("Can't compare %s and %s" % (self.__class__.__name__, otype)) return s, o def __lt__(self, other): s, o = self.make_comparable(other) return s < o def __le__(self, other): s, o = self.make_comparable(other) return s <= o def __gt__(self, other): s, o = self.make_comparable(other) return s > o def __ge__(self, other): s, o = self.make_comparable(other) return s >= o def __eq__(self, other): s, o = self.make_comparable(other) return s == o def timetuple(self): return time.strptime(self.value, "%Y%m%dT%H:%M:%S") ## # Get date/time value. # # @return Date/time value, as an ISO 8601 string. def __str__(self): return self.value def __repr__(self): return "<%s %r at %#x>" % (self.__class__.__name__, self.value, id(self)) def decode(self, data): self.value = str(data).strip() def encode(self, out): out.write("<value><dateTime.iso8601>") out.write(self.value) out.write("</dateTime.iso8601></value>\n") def _datetime(data): # decode xml element contents into a DateTime structure. value = DateTime() value.decode(data) return value def _datetime_type(data): return datetime.strptime(data, "%Y%m%dT%H:%M:%S") ## # Wrapper for binary data. This can be used to transport any kind # of binary data over XML-RPC, using BASE64 encoding. # # @param data An 8-bit string containing arbitrary data. class Binary: """Wrapper for binary data.""" def __init__(self, data=None): if data is None: data = b"" else: if not isinstance(data, (bytes, bytearray)): raise TypeError("expected bytes or bytearray, not %s" % data.__class__.__name__) data = bytes(data) # Make a copy of the bytes! self.data = data ## # Get buffer contents. # # @return Buffer contents, as an 8-bit string. def __str__(self): return str(self.data, "latin-1") # XXX encoding?! def __eq__(self, other): if isinstance(other, Binary): other = other.data return self.data == other def decode(self, data): self.data = base64.decodebytes(data) def encode(self, out): out.write("<value><base64>\n") encoded = base64.encodebytes(self.data) out.write(encoded.decode('ascii')) out.write("</base64></value>\n") def _binary(data): # decode xml element contents into a Binary structure value = Binary() value.decode(data) return value WRAPPERS = (DateTime, Binary) # -------------------------------------------------------------------- # XML parsers class ExpatParser: # fast expat parser for Python 2.0 and later. def __init__(self, target): self._parser = parser = expat.ParserCreate(None, None) self._target = target parser.StartElementHandler = target.start parser.EndElementHandler = target.end parser.CharacterDataHandler = target.data encoding = None target.xml(encoding, None) def feed(self, data): self._parser.Parse(data, 0) def close(self): try: parser = self._parser except AttributeError: pass else: del self._target, self._parser # get rid of circular references parser.Parse(b"", True) # end of data # -------------------------------------------------------------------- # XML-RPC marshalling and unmarshalling code ## # XML-RPC marshaller. # # @param encoding Default encoding for 8-bit strings. The default # value is None (interpreted as UTF-8). # @see dumps class Marshaller: """Generate an XML-RPC params chunk from a Python data structure. Create a Marshaller instance for each set of parameters, and use the "dumps" method to convert your data (represented as a tuple) to an XML-RPC params chunk. To write a fault response, pass a Fault instance instead. You may prefer to use the "dumps" module function for this purpose. """ # by the way, if you don't understand what's going on in here, # that's perfectly ok. def __init__(self, encoding=None, allow_none=False): self.memo = {} self.data = None self.encoding = encoding self.allow_none = allow_none dispatch = {} def dumps(self, values): out = [] write = out.append dump = self.__dump if isinstance(values, Fault): # fault instance write("<fault>\n") dump({'faultCode': values.faultCode, 'faultString': values.faultString}, write) write("</fault>\n") else: # parameter block # FIXME: the xml-rpc specification allows us to leave out # the entire <params> block if there are no parameters. # however, changing this may break older code (including # old versions of xmlrpclib.py), so this is better left as # is for now. See @XMLRPC3 for more information. /F write("<params>\n") for v in values: write("<param>\n") dump(v, write) write("</param>\n") write("</params>\n") result = "".join(out) return result def __dump(self, value, write): try: f = self.dispatch[type(value)] except KeyError: # check if this object can be marshalled as a structure if not hasattr(value, '__dict__'): raise TypeError("cannot marshal %s objects" % type(value)) # check if this class is a sub-class of a basic type, # because we don't know how to marshal these types # (e.g. a string sub-class) for type_ in type(value).__mro__: if type_ in self.dispatch.keys(): raise TypeError("cannot marshal %s objects" % type(value)) # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix # for the p3yk merge, this should probably be fixed more neatly. f = self.dispatch["_arbitrary_instance"] f(self, value, write) def dump_nil (self, value, write): if not self.allow_none: raise TypeError("cannot marshal None unless allow_none is enabled") write("<value><nil/></value>") dispatch[type(None)] = dump_nil def dump_bool(self, value, write): write("<value><boolean>") write(value and "1" or "0") write("</boolean></value>\n") dispatch[bool] = dump_bool def dump_long(self, value, write): if value > MAXINT or value < MININT: raise OverflowError("int exceeds XML-RPC limits") write("<value><int>") write(str(int(value))) write("</int></value>\n") dispatch[int] = dump_long # backward compatible dump_int = dump_long def dump_double(self, value, write): write("<value><double>") write(repr(value)) write("</double></value>\n") dispatch[float] = dump_double def dump_unicode(self, value, write, escape=escape): write("<value><string>") write(escape(value)) write("</string></value>\n") dispatch[str] = dump_unicode def dump_bytes(self, value, write): write("<value><base64>\n") encoded = base64.encodebytes(value) write(encoded.decode('ascii')) write("</base64></value>\n") dispatch[bytes] = dump_bytes dispatch[bytearray] = dump_bytes def dump_array(self, value, write): i = id(value) if i in self.memo: raise TypeError("cannot marshal recursive sequences") self.memo[i] = None dump = self.__dump write("<value><array><data>\n") for v in value: dump(v, write) write("</data></array></value>\n") del self.memo[i] dispatch[tuple] = dump_array dispatch[list] = dump_array def dump_struct(self, value, write, escape=escape): i = id(value) if i in self.memo: raise TypeError("cannot marshal recursive dictionaries") self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k, v in value.items(): write("<member>\n") if not isinstance(k, str): raise TypeError("dictionary key must be string") write("<name>%s</name>\n" % escape(k)) dump(v, write) write("</member>\n") write("</struct></value>\n") del self.memo[i] dispatch[dict] = dump_struct def dump_datetime(self, value, write): write("<value><dateTime.iso8601>") write(_strftime(value)) write("</dateTime.iso8601></value>\n") dispatch[datetime] = dump_datetime def dump_instance(self, value, write): # check for special wrappers if value.__class__ in WRAPPERS: self.write = write value.encode(self) del self.write else: # store instance attributes as a struct (really?) self.dump_struct(value.__dict__, write) dispatch[DateTime] = dump_instance dispatch[Binary] = dump_instance # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix # for the p3yk merge, this should probably be fixed more neatly. dispatch["_arbitrary_instance"] = dump_instance ## # XML-RPC unmarshaller. # # @see loads class Unmarshaller: """Unmarshal an XML-RPC response, based on incoming XML event messages (start, data, end). Call close() to get the resulting data structure. Note that this reader is fairly tolerant, and gladly accepts bogus XML-RPC data without complaining (but not bogus XML). """ # and again, if you don't understand what's going on in here, # that's perfectly ok. def __init__(self, use_datetime=False, use_builtin_types=False): self._type = None self._stack = [] self._marks = [] self._data = [] self._methodname = None self._encoding = "utf-8" self.append = self._stack.append self._use_datetime = use_builtin_types or use_datetime self._use_bytes = use_builtin_types def close(self): # return response tuple and target method if self._type is None or self._marks: raise ResponseError() if self._type == "fault": raise Fault(**self._stack[0]) return tuple(self._stack) def getmethodname(self): return self._methodname # # event handlers def xml(self, encoding, standalone): self._encoding = encoding # FIXME: assert standalone == 1 ??? def start(self, tag, attrs): # prepare to handle this element if tag == "array" or tag == "struct": self._marks.append(len(self._stack)) self._data = [] self._value = (tag == "value") def data(self, text): self._data.append(text) def end(self, tag): # call the appropriate end tag handler try: f = self.dispatch[tag] except KeyError: pass # unknown tag ? else: return f(self, "".join(self._data)) # # accelerator support def end_dispatch(self, tag, data): # dispatch data try: f = self.dispatch[tag] except KeyError: pass # unknown tag ? else: return f(self, data) # # element decoders dispatch = {} def end_nil (self, data): self.append(None) self._value = 0 dispatch["nil"] = end_nil def end_boolean(self, data): if data == "0": self.append(False) elif data == "1": self.append(True) else: raise TypeError("bad boolean value") self._value = 0 dispatch["boolean"] = end_boolean def end_int(self, data): self.append(int(data)) self._value = 0 dispatch["i4"] = end_int dispatch["i8"] = end_int dispatch["int"] = end_int def end_double(self, data): self.append(float(data)) self._value = 0 dispatch["double"] = end_double def end_string(self, data): if self._encoding: data = data.decode(self._encoding) self.append(data) self._value = 0 dispatch["string"] = end_string dispatch["name"] = end_string # struct keys are always strings def end_array(self, data): mark = self._marks.pop() # map arrays to Python lists self._stack[mark:] = [self._stack[mark:]] self._value = 0 dispatch["array"] = end_array def end_struct(self, data): mark = self._marks.pop() # map structs to Python dictionaries dict = {} items = self._stack[mark:] for i in range(0, len(items), 2): dict[items[i]] = items[i+1] self._stack[mark:] = [dict] self._value = 0 dispatch["struct"] = end_struct def end_base64(self, data): value = Binary() value.decode(data.encode("ascii")) if self._use_bytes: value = value.data self.append(value) self._value = 0 dispatch["base64"] = end_base64 def end_dateTime(self, data): value = DateTime() value.decode(data) if self._use_datetime: value = _datetime_type(data) self.append(value) dispatch["dateTime.iso8601"] = end_dateTime def end_value(self, data): # if we stumble upon a value element with no internal # elements, treat it as a string element if self._value: self.end_string(data) dispatch["value"] = end_value def end_params(self, data): self._type = "params" dispatch["params"] = end_params def end_fault(self, data): self._type = "fault" dispatch["fault"] = end_fault def end_methodName(self, data): if self._encoding: data = data.decode(self._encoding) self._methodname = data self._type = "methodName" # no params dispatch["methodName"] = end_methodName ## Multicall support # class _MultiCallMethod: # some lesser magic to store calls made to a MultiCall object # for batch execution def __init__(self, call_list, name): self.__call_list = call_list self.__name = name def __getattr__(self, name): return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name)) def __call__(self, *args): self.__call_list.append((self.__name, args)) class MultiCallIterator: """Iterates over the results of a multicall. Exceptions are raised in response to xmlrpc faults.""" def __init__(self, results): self.results = results def __getitem__(self, i): item = self.results[i] if type(item) == type({}): raise Fault(item['faultCode'], item['faultString']) elif type(item) == type([]): return item[0] else: raise ValueError("unexpected type in multicall result") class MultiCall: """server -> an object used to boxcar method calls server should be a ServerProxy object. Methods can be added to the MultiCall using normal method call syntax e.g.: multicall = MultiCall(server_proxy) multicall.add(2,3) multicall.get_address("Guido") To execute the multicall, call the MultiCall object e.g.: add_result, address = multicall() """ def __init__(self, server): self.__server = server self.__call_list = [] def __repr__(self): return "<%s at %#x>" % (self.__class__.__name__, id(self)) __str__ = __repr__ def __getattr__(self, name): return _MultiCallMethod(self.__call_list, name) def __call__(self): marshalled_list = [] for name, args in self.__call_list: marshalled_list.append({'methodName' : name, 'params' : args}) return MultiCallIterator(self.__server.system.multicall(marshalled_list)) # -------------------------------------------------------------------- # convenience functions FastMarshaller = FastParser = FastUnmarshaller = None ## # Create a parser object, and connect it to an unmarshalling instance. # This function picks the fastest available XML parser. # # return A (parser, unmarshaller) tuple. def getparser(use_datetime=False, use_builtin_types=False): """getparser() -> parser, unmarshaller Create an instance of the fastest available parser, and attach it to an unmarshalling object. Return both objects. """ if FastParser and FastUnmarshaller: if use_builtin_types: mkdatetime = _datetime_type mkbytes = base64.decodebytes elif use_datetime: mkdatetime = _datetime_type mkbytes = _binary else: mkdatetime = _datetime mkbytes = _binary target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault) parser = FastParser(target) else: target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types) if FastParser: parser = FastParser(target) else: parser = ExpatParser(target) return parser, target ## # Convert a Python tuple or a Fault instance to an XML-RPC packet. # # @def dumps(params, **options) # @param params A tuple or Fault instance. # @keyparam methodname If given, create a methodCall request for # this method name. # @keyparam methodresponse If given, create a methodResponse packet. # If used with a tuple, the tuple must be a singleton (that is, # it must contain exactly one element). # @keyparam encoding The packet encoding. # @return A string containing marshalled data. def dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All byte strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, where necessary. """ assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, tuple): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" if FastMarshaller: m = FastMarshaller(encoding) else: m = Marshaller(encoding, allow_none) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, str): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse: # a method response, or a fault structure data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return "".join(data) ## # Convert an XML-RPC packet to a Python object. If the XML-RPC packet # represents a fault condition, this function raises a Fault exception. # # @param data An XML-RPC packet, given as an 8-bit string. # @return A tuple containing the unpacked data, and the method name # (None if not present). # @see Fault def loads(data, use_datetime=False, use_builtin_types=False): """data -> unmarshalled data, method name Convert an XML-RPC packet to unmarshalled data plus a method name (None if not present). If the XML-RPC packet represents a fault condition, this function raises a Fault exception. """ p, u = getparser(use_datetime=use_datetime, use_builtin_types=use_builtin_types) p.feed(data) p.close() return u.close(), u.getmethodname() ## # Encode a string using the gzip content encoding such as specified by the # Content-Encoding: gzip # in the HTTP header, as described in RFC 1952 # # @param data the unencoded data # @return the encoded data def gzip_encode(data): """data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError f = BytesIO() with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf: gzf.write(data) return f.getvalue() ## # Decode a string using the gzip content encoding such as specified by the # Content-Encoding: gzip # in the HTTP header, as described in RFC 1952 # # @param data The encoded data # @keyparam max_decode Maximum bytes to decode (20MB default), use negative # values for unlimited decoding # @return the unencoded data # @raises ValueError if data is not correctly coded. # @raises ValueError if max gzipped payload length exceeded def gzip_decode(data, max_decode=20971520): """gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError with gzip.GzipFile(mode="rb", fileobj=BytesIO(data)) as gzf: try: if max_decode < 0: # no limit decoded = gzf.read() else: decoded = gzf.read(max_decode + 1) except OSError: raise ValueError("invalid data") if max_decode >= 0 and len(decoded) > max_decode: raise ValueError("max gzipped payload length exceeded") return decoded ## # Return a decoded file-like object for the gzip encoding # as described in RFC 1952. # # @param response A stream supporting a read() method # @return a file-like object that the decoded data can be read() from class GzipDecodedResponse(gzip.GzipFile if gzip else object): """a file-like object to decode a response encoded with the gzip method, as described in RFC 1952. """ def __init__(self, response): #response doesn't support tell() and read(), required by #GzipFile if not gzip: raise NotImplementedError self.io = BytesIO(response.read()) gzip.GzipFile.__init__(self, mode="rb", fileobj=self.io) def close(self): try: gzip.GzipFile.close(self) finally: self.io.close() # -------------------------------------------------------------------- # request dispatcher class _Method: # some magic to bind an XML-RPC method to an RPC server. # supports "nested" methods (e.g. examples.getStateName) def __init__(self, send, name): self.__send = send self.__name = name def __getattr__(self, name): return _Method(self.__send, "%s.%s" % (self.__name, name)) def __call__(self, *args): return self.__send(self.__name, args) ## # Standard transport class for XML-RPC over HTTP. # <p> # You can create custom transports by subclassing this method, and # overriding selected methods. class Transport: """Handles an HTTP transaction to an XML-RPC server.""" # client identifier (may be overridden) user_agent = "Python-xmlrpc/%s" % __version__ #if true, we'll request gzip encoding accept_gzip_encoding = True # if positive, encode request using gzip if it exceeds this threshold # note that many server will get confused, so only use it if you know # that they can decode such a request encode_threshold = None #None = don't encode def __init__(self, use_datetime=False, use_builtin_types=False): self._use_datetime = use_datetime self._use_builtin_types = use_builtin_types self._connection = (None, None) self._extra_headers = [] ## # Send a complete request, and parse the response. # Retry request if a cached connection has disconnected. # # @param host Target host. # @param handler Target PRC handler. # @param request_body XML-RPC request body. # @param verbose Debugging flag. # @return Parsed response. def request(self, host, handler, request_body, verbose=False): #retry request once if cached connection has gone cold for i in (0, 1): try: return self.single_request(host, handler, request_body, verbose) except OSError as e: if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE): raise except http.client.RemoteDisconnected: if i: raise def single_request(self, host, handler, request_body, verbose=False): # issue XML-RPC request try: http_conn = self.send_request(host, handler, request_body, verbose) resp = http_conn.getresponse() if resp.status == 200: self.verbose = verbose return self.parse_response(resp) except Fault: raise except Exception: #All unexpected errors leave connection in # a strange state, so we clear it. self.close() raise #We got an error response. #Discard any response data and raise exception if resp.getheader("content-length", ""): resp.read() raise ProtocolError( host + handler, resp.status, resp.reason, dict(resp.getheaders()) ) ## # Create parser. # # @return A 2-tuple containing a parser and an unmarshaller. def getparser(self): # get parser and unmarshaller return getparser(use_datetime=self._use_datetime, use_builtin_types=self._use_builtin_types) ## # Get authorization info from host parameter # Host may be a string, or a (host, x509-dict) tuple; if a string, # it is checked for a "user:pw@host" format, and a "Basic # Authentication" header is added if appropriate. # # @param host Host descriptor (URL or (URL, x509 info) tuple). # @return A 3-tuple containing (actual host, extra headers, # x509 info). The header and x509 fields may be None. def get_host_info(self, host): x509 = {} if isinstance(host, tuple): host, x509 = host auth, host = urllib.parse.splituser(host) if auth: auth = urllib.parse.unquote_to_bytes(auth) auth = base64.encodebytes(auth).decode("utf-8") auth = "".join(auth.split()) # get rid of whitespace extra_headers = [ ("Authorization", "Basic " + auth) ] else: extra_headers = [] return host, extra_headers, x509 ## # Connect to server. # # @param host Target host. # @return An HTTPConnection object def make_connection(self, host): #return an existing connection if possible. This allows #HTTP/1.1 keep-alive. if self._connection and host == self._connection[0]: return self._connection[1] # create a HTTP connection object from a host descriptor chost, self._extra_headers, x509 = self.get_host_info(host) self._connection = host, http.client.HTTPConnection(chost) return self._connection[1] ## # Clear any cached connection object. # Used in the event of socket errors. # def close(self): host, connection = self._connection if connection: self._connection = (None, None) connection.close() ## # Send HTTP request. # # @param host Host descriptor (URL or (URL, x509 info) tuple). # @param handler Targer RPC handler (a path relative to host) # @param request_body The XML-RPC request body # @param debug Enable debugging if debug is true. # @return An HTTPConnection. def send_request(self, host, handler, request_body, debug): connection = self.make_connection(host) headers = self._extra_headers[:] if debug: connection.set_debuglevel(1) if self.accept_gzip_encoding and gzip: connection.putrequest("POST", handler, skip_accept_encoding=True) headers.append(("Accept-Encoding", "gzip")) else: connection.putrequest("POST", handler) headers.append(("Content-Type", "text/xml")) headers.append(("User-Agent", self.user_agent)) self.send_headers(connection, headers) self.send_content(connection, request_body) return connection ## # Send request headers. # This function provides a useful hook for subclassing # # @param connection httpConnection. # @param headers list of key,value pairs for HTTP headers def send_headers(self, connection, headers): for key, val in headers: connection.putheader(key, val) ## # Send request body. # This function provides a useful hook for subclassing # # @param connection httpConnection. # @param request_body XML-RPC request body. def send_content(self, connection, request_body): #optionally encode the request if (self.encode_threshold is not None and self.encode_threshold < len(request_body) and gzip): connection.putheader("Content-Encoding", "gzip") request_body = gzip_encode(request_body) connection.putheader("Content-Length", str(len(request_body))) connection.endheaders(request_body) ## # Parse response. # # @param file Stream. # @return Response tuple and target method. def parse_response(self, response): # read response data from httpresponse, and parse it # Check for new http response object, otherwise it is a file object. if hasattr(response, 'getheader'): if response.getheader("Content-Encoding", "") == "gzip": stream = GzipDecodedResponse(response) else: stream = response else: stream = response p, u = self.getparser() while 1: data = stream.read(1024) if not data: break if self.verbose: print("body:", repr(data)) p.feed(data) if stream is not response: stream.close() p.close() return u.close() ## # Standard transport class for XML-RPC over HTTPS. class SafeTransport(Transport): """Handles an HTTPS transaction to an XML-RPC server.""" def __init__(self, use_datetime=False, use_builtin_types=False, *, context=None): super().__init__(use_datetime=use_datetime, use_builtin_types=use_builtin_types) self.context = context # FIXME: mostly untested def make_connection(self, host): if self._connection and host == self._connection[0]: return self._connection[1] if not hasattr(http.client, "HTTPSConnection"): raise NotImplementedError( "your version of http.client doesn't support HTTPS") # create a HTTPS connection object from a host descriptor # host may be a string, or a (host, x509-dict) tuple chost, self._extra_headers, x509 = self.get_host_info(host) self._connection = host, http.client.HTTPSConnection(chost, None, context=self.context, **(x509 or {})) return self._connection[1] ## # Standard server proxy. This class establishes a virtual connection # to an XML-RPC server. # <p> # This class is available as ServerProxy and Server. New code should # use ServerProxy, to avoid confusion. # # @def ServerProxy(uri, **options) # @param uri The connection point on the server. # @keyparam transport A transport factory, compatible with the # standard transport class. # @keyparam encoding The default encoding used for 8-bit strings # (default is UTF-8). # @keyparam verbose Use a true value to enable debugging output. # (printed to standard output). # @see Transport class ServerProxy: """uri [,options] -> a logical connection to an XML-RPC server uri is the connection point on the server, given as scheme://host/target. The standard implementation always supports the "http" scheme. If SSL socket support is available (Python 2.0), it also supports "https". If the target part and the slash preceding it are both omitted, "/RPC2" is assumed. The following options can be given as keyword arguments: transport: a transport factory encoding: the request encoding (default is UTF-8) All 8-bit strings passed to the server proxy are assumed to use the given encoding. """ def __init__(self, uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, context=None): # establish a "logical" server connection # get the url type, uri = urllib.parse.splittype(uri) if type not in ("http", "https"): raise OSError("unsupported XML-RPC protocol") self.__host, self.__handler = urllib.parse.splithost(uri) if not self.__handler: self.__handler = "/RPC2" if transport is None: if type == "https": handler = SafeTransport extra_kwargs = {"context": context} else: handler = Transport extra_kwargs = {} transport = handler(use_datetime=use_datetime, use_builtin_types=use_builtin_types, **extra_kwargs) self.__transport = transport self.__encoding = encoding or 'utf-8' self.__verbose = verbose self.__allow_none = allow_none def __close(self): self.__transport.close() def __request(self, methodname, params): # call a method on the remote server request = dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none).encode(self.__encoding) response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose ) if len(response) == 1: response = response[0] return response def __repr__(self): return ( "<%s for %s%s>" % (self.__class__.__name__, self.__host, self.__handler) ) __str__ = __repr__ def __getattr__(self, name): # magic method dispatcher return _Method(self.__request, name) # note: to call a remote object with an non-standard name, use # result getattr(server, "strange-python-name")(args) def __call__(self, attr): """A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__ """ if attr == "close": return self.__close elif attr == "transport": return self.__transport raise AttributeError("Attribute %r not found" % (attr,)) def __enter__(self): return self def __exit__(self, *args): self.__close() # compatibility Server = ServerProxy # -------------------------------------------------------------------- # test code if __name__ == "__main__": # simple test program (from the XML-RPC specification) # local server, available from Lib/xmlrpc/server.py server = ServerProxy("http://localhost:8000") try: print(server.currentTime.getCurrentTime()) except Error as v: print("ERROR", v) multi = MultiCall(server) multi.getData() multi.pow(2,9) multi.add(1,2) try: for response in multi(): print(response) except Error as v: print("ERROR", v)
steveb/heat
refs/heads/master
heat/httpd/heat_api_cfn.py
3
#!/usr/bin/env python # # 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. """WSGI script for heat-api-cfn. Script for running heat-api-cfn under Apache2. """ from oslo_config import cfg import oslo_i18n as i18n from oslo_log import log as logging from heat.common import config from heat.common.i18n import _LI from heat.common import messaging from heat.common import profiler from heat import version def init_application(): i18n.enable_lazy() LOG = logging.getLogger('heat.api.cfn') logging.register_options(cfg.CONF) cfg.CONF(project='heat', prog='heat-api-cfn', version=version.version_info.version_string()) logging.setup(cfg.CONF, 'heat-api-cfn') logging.set_defaults() config.set_config_defaults() messaging.setup() port = cfg.CONF.heat_api_cfn.bind_port host = cfg.CONF.heat_api_cfn.bind_host LOG.info(_LI('Starting Heat API on %(host)s:%(port)s'), {'host': host, 'port': port}) profiler.setup('heat-api-cfn', host) return config.load_paste_app()
goddardl/gaffer
refs/heads/master
python/GafferUI/BusyWidget.py
2
########################################################################## # # Copyright (c) 2012, 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 math import time import Gaffer import GafferUI QtCore = GafferUI._qtImport( "QtCore" ) QtGui = GafferUI._qtImport( "QtGui" ) class BusyWidget( GafferUI.Widget ) : def __init__( self, size = 50, **kw ) : GafferUI.Widget.__init__( self, _BusyWidget( None, size ), **kw ) # qt implementation class class _BusyWidget( QtGui.QWidget ) : def __init__( self, parent = None , size = 50 ) : QtGui.QWidget.__init__( self, parent ) self.__size = size self.setMinimumSize( size, size ) self.__timer = None def showEvent( self, event ) : QtGui.QWidget.showEvent( self, event ) if self.__timer is None : self.__timer = self.startTimer( 1000 / 25 ) def hideEvent( self, event ) : QtGui.QWidget.hideEvent( self, event ) if self.__timer is not None : self.killTimer( self.__timer ) self.__timer = None def timerEvent( self, event ) : self.update() def paintEvent( self, event ) : painter = QtGui.QPainter( self ) painter.setRenderHint( QtGui.QPainter.Antialiasing ) width, height = float( self.width() ), float( self.height() ) centreX, centreY = width / 2, height / 2 radius = self.__size / 2.0 numCircles = 10 circleRadius = radius / 5 penWidth = circleRadius / 10 for i in range( 0, numCircles ) : theta = i * 360.0 / numCircles + time.time() * 10 circleCentreX = centreX - (radius - circleRadius - penWidth) * math.cos( math.radians( theta ) ) circleCentreY = centreY + (radius - circleRadius - penWidth) * math.sin( math.radians( theta ) ) alpha = 1 - ( ( math.fmod( theta + time.time() * 270, 360 ) ) / 360 ) ## \todo Colours (and maybe even drawing) should come from style brush = QtGui.QBrush( QtGui.QColor( 119, 156, 189, alpha * 255 ) ) painter.setBrush( brush ) pen = QtGui.QPen( QtGui.QColor( 0, 0, 0, alpha * 255 ) ) pen.setWidth( penWidth ) painter.setPen( pen ) painter.drawEllipse( QtCore.QPointF( circleCentreX, circleCentreY ), circleRadius, circleRadius )
wooyek/nuntio
refs/heads/master
web/common/appenginepatch/ragendja/template.py
1
# -*- coding: utf-8 -*- """ This is a set of utilities for faster development with Django templates. render_to_response() and render_to_string() use RequestContext internally. The app_prefixed_loader is a template loader that loads directly from the app's 'templates' folder when you specify an app prefix ('app/template.html'). The JSONResponse() function automatically converts a given Python object into JSON and returns it as an HttpResponse. """ from django.conf import settings from django.http import HttpResponse from django.template import RequestContext, loader, \ TemplateDoesNotExist, Library, Node, Variable, generic_tag_compiler from django.utils.functional import curry from inspect import getargspec from ragendja.apputils import get_app_dirs import os class Library(Library): def context_tag(self, func): params, xx, xxx, defaults = getargspec(func) class ContextNode(Node): def __init__(self, vars_to_resolve): self.vars_to_resolve = map(Variable, vars_to_resolve) def render(self, context): resolved_vars = [var.resolve(context) for var in self.vars_to_resolve] return func(context, *resolved_vars) params = params[1:] compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, ContextNode) compile_func.__doc__ = func.__doc__ self.tag(getattr(func, "_decorated_function", func).__name__, compile_func) return func def get_template_sources(template_name, template_dirs=None): """ Returs a collection of paths used to load templates in this module """ packed = template_name.split('/', 1) if len(packed) == 2 and packed[0] in app_template_dirs: return [os.path.join(app_template_dirs[packed[0]], packed[1])] return [] # The following defines a template loader that loads templates from a specific # app based on the prefix of the template path: # get_template("app/template.html") => app/templates/template.html # This keeps the code DRY and prevents name clashes. def app_prefixed_loader(template_name, template_dirs=None): path = get_template_sources(template_name, template_dirs) if path is not None and len(path) == 1: try: return (open(path[0]).read().decode(settings.FILE_CHARSET), path[0]) except IOError: pass raise TemplateDoesNotExist, template_name app_prefixed_loader.is_usable = True def render_to_string(request, template_name, data=None): return loader.render_to_string(template_name, data, context_instance=RequestContext(request)) def render_to_response(request, template_name, data=None, mimetype=None): if mimetype is None: mimetype = settings.DEFAULT_CONTENT_TYPE original_mimetype = mimetype if mimetype == 'application/xhtml+xml': # Internet Explorer only understands XHTML if it's served as text/html if request.META.get('HTTP_ACCEPT').find(mimetype) == -1: mimetype = 'text/html' response = HttpResponse(render_to_string(request, template_name, data), content_type='%s; charset=%s' % (mimetype, settings.DEFAULT_CHARSET)) if original_mimetype == 'application/xhtml+xml': # Since XHTML is served with two different MIME types, depending on the # browser, we need to tell proxies to serve different versions. from django.utils.cache import patch_vary_headers patch_vary_headers(response, ['User-Agent']) return response def JSONResponse(pyobj): from ragendja.json import JSONResponse as real_class global JSONResponse JSONResponse = real_class return JSONResponse(pyobj) def TextResponse(string=''): return HttpResponse(string, content_type='text/plain; charset=%s' % settings.DEFAULT_CHARSET) # This is needed by app_prefixed_loader. app_template_dirs = get_app_dirs('templates')
prymitive/upaas-admin
refs/heads/master
upaas_admin/common/__init__.py
23
# -*- coding: utf-8 -*- """ :copyright: Copyright 2013-2014 by Łukasz Mierzwa :contact: l.mierzwa@gmail.com """
fillycheezstake/MissionPlanner
refs/heads/master
Lib/csv.py
55
""" csv.py - read/write/investigate CSV files """ import re from functools import reduce from _csv import Error, __version__, writer, reader, register_dialect, \ unregister_dialect, get_dialect, list_dialects, \ field_size_limit, \ QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE, \ __doc__ from _csv import Dialect as _Dialect try: from cStringIO import StringIO except ImportError: from StringIO import StringIO __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", "Error", "Dialect", "__doc__", "excel", "excel_tab", "field_size_limit", "reader", "writer", "register_dialect", "get_dialect", "list_dialects", "Sniffer", "unregister_dialect", "__version__", "DictReader", "DictWriter" ] class Dialect: """Describe an Excel dialect. This must be subclassed (see csv.excel). Valid attributes are: delimiter, quotechar, escapechar, doublequote, skipinitialspace, lineterminator, quoting. """ _name = "" _valid = False # placeholders delimiter = None quotechar = None escapechar = None doublequote = None skipinitialspace = None lineterminator = None quoting = None def __init__(self): if self.__class__ != Dialect: self._valid = True self._validate() def _validate(self): try: _Dialect(self) except TypeError, e: # We do this for compatibility with py2.3 raise Error(str(e)) class excel(Dialect): """Describe the usual properties of Excel-generated CSV files.""" delimiter = ',' quotechar = '"' doublequote = True skipinitialspace = False lineterminator = '\r\n' quoting = QUOTE_MINIMAL register_dialect("excel", excel) class excel_tab(excel): """Describe the usual properties of Excel-generated TAB-delimited files.""" delimiter = '\t' register_dialect("excel-tab", excel_tab) class DictReader: def __init__(self, f, fieldnames=None, restkey=None, restval=None, dialect="excel", *args, **kwds): self._fieldnames = fieldnames # list of keys for the dict self.restkey = restkey # key to catch long rows self.restval = restval # default value for short rows self.reader = reader(f, dialect, *args, **kwds) self.dialect = dialect self.line_num = 0 def __iter__(self): return self @property def fieldnames(self): if self._fieldnames is None: try: self._fieldnames = self.reader.next() except StopIteration: pass self.line_num = self.reader.line_num return self._fieldnames @fieldnames.setter def fieldnames(self, value): self._fieldnames = value def next(self): if self.line_num == 0: # Used only for its side effect. self.fieldnames row = self.reader.next() self.line_num = self.reader.line_num # unlike the basic reader, we prefer not to return blanks, # because we will typically wind up with a dict full of None # values while row == []: row = self.reader.next() d = dict(zip(self.fieldnames, row)) lf = len(self.fieldnames) lr = len(row) if lf < lr: d[self.restkey] = row[lf:] elif lf > lr: for key in self.fieldnames[lr:]: d[key] = self.restval return d class DictWriter: def __init__(self, f, fieldnames, restval="", extrasaction="raise", dialect="excel", *args, **kwds): self.fieldnames = fieldnames # list of keys for the dict self.restval = restval # for writing short dicts if extrasaction.lower() not in ("raise", "ignore"): raise ValueError, \ ("extrasaction (%s) must be 'raise' or 'ignore'" % extrasaction) self.extrasaction = extrasaction self.writer = writer(f, dialect, *args, **kwds) def writeheader(self): header = dict(zip(self.fieldnames, self.fieldnames)) self.writerow(header) def _dict_to_list(self, rowdict): if self.extrasaction == "raise": wrong_fields = [k for k in rowdict if k not in self.fieldnames] if wrong_fields: raise ValueError("dict contains fields not in fieldnames: " + ", ".join(wrong_fields)) return [rowdict.get(key, self.restval) for key in self.fieldnames] def writerow(self, rowdict): return self.writer.writerow(self._dict_to_list(rowdict)) def writerows(self, rowdicts): rows = [] for rowdict in rowdicts: rows.append(self._dict_to_list(rowdict)) return self.writer.writerows(rows) # Guard Sniffer's type checking against builds that exclude complex() try: complex except NameError: complex = float class Sniffer: ''' "Sniffs" the format of a CSV file (i.e. delimiter, quotechar) Returns a Dialect object. ''' def __init__(self): # in case there is more than one possible delimiter self.preferred = [',', '\t', ';', ' ', ':'] def sniff(self, sample, delimiters=None): """ Returns a dialect (or None) corresponding to the sample """ quotechar, doublequote, delimiter, skipinitialspace = \ self._guess_quote_and_delimiter(sample, delimiters) if not delimiter: delimiter, skipinitialspace = self._guess_delimiter(sample, delimiters) if not delimiter: raise Error, "Could not determine delimiter" class dialect(Dialect): _name = "sniffed" lineterminator = '\r\n' quoting = QUOTE_MINIMAL # escapechar = '' dialect.doublequote = doublequote dialect.delimiter = delimiter # _csv.reader won't accept a quotechar of '' dialect.quotechar = quotechar or '"' dialect.skipinitialspace = skipinitialspace return dialect def _guess_quote_and_delimiter(self, data, delimiters): """ Looks for text enclosed between two identical quotes (the probable quotechar) which are preceded and followed by the same character (the probable delimiter). For example: ,'some text', The quote with the most wins, same with the delimiter. If there is no quotechar the delimiter can't be determined this way. """ matches = [] for restr in ('(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', # ,".*?", '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)', # ".*?", '(?P<delim>>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', # ,".*?" '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)'): # ".*?" (no delim, no space) regexp = re.compile(restr, re.DOTALL | re.MULTILINE) matches = regexp.findall(data) if matches: break if not matches: # (quotechar, doublequote, delimiter, skipinitialspace) return ('', False, None, 0) quotes = {} delims = {} spaces = 0 for m in matches: n = regexp.groupindex['quote'] - 1 key = m[n] if key: quotes[key] = quotes.get(key, 0) + 1 try: n = regexp.groupindex['delim'] - 1 key = m[n] except KeyError: continue if key and (delimiters is None or key in delimiters): delims[key] = delims.get(key, 0) + 1 try: n = regexp.groupindex['space'] - 1 except KeyError: continue if m[n]: spaces += 1 quotechar = reduce(lambda a, b, quotes = quotes: (quotes[a] > quotes[b]) and a or b, quotes.keys()) if delims: delim = reduce(lambda a, b, delims = delims: (delims[a] > delims[b]) and a or b, delims.keys()) skipinitialspace = delims[delim] == spaces if delim == '\n': # most likely a file with a single column delim = '' else: # there is *no* delimiter, it's a single column of quoted data delim = '' skipinitialspace = 0 # if we see an extra quote between delimiters, we've got a # double quoted format dq_regexp = re.compile(r"((%(delim)s)|^)\W*%(quote)s[^%(delim)s\n]*%(quote)s[^%(delim)s\n]*%(quote)s\W*((%(delim)s)|$)" % \ {'delim':delim, 'quote':quotechar}, re.MULTILINE) if dq_regexp.search(data): doublequote = True else: doublequote = False return (quotechar, doublequote, delim, skipinitialspace) def _guess_delimiter(self, data, delimiters): """ The delimiter /should/ occur the same number of times on each row. However, due to malformed data, it may not. We don't want an all or nothing approach, so we allow for small variations in this number. 1) build a table of the frequency of each character on every line. 2) build a table of frequencies of this frequency (meta-frequency?), e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows, 7 times in 2 rows' 3) use the mode of the meta-frequency to determine the /expected/ frequency for that character 4) find out how often the character actually meets that goal 5) the character that best meets its goal is the delimiter For performance reasons, the data is evaluated in chunks, so it can try and evaluate the smallest portion of the data possible, evaluating additional chunks as necessary. """ data = filter(None, data.split('\n')) ascii = [chr(c) for c in range(127)] # 7-bit ASCII # build frequency tables chunkLength = min(10, len(data)) iteration = 0 charFrequency = {} modes = {} delims = {} start, end = 0, min(chunkLength, len(data)) while start < len(data): iteration += 1 for line in data[start:end]: for char in ascii: metaFrequency = charFrequency.get(char, {}) # must count even if frequency is 0 freq = line.count(char) # value is the mode metaFrequency[freq] = metaFrequency.get(freq, 0) + 1 charFrequency[char] = metaFrequency for char in charFrequency.keys(): items = charFrequency[char].items() if len(items) == 1 and items[0][0] == 0: continue # get the mode of the frequencies if len(items) > 1: modes[char] = reduce(lambda a, b: a[1] > b[1] and a or b, items) # adjust the mode - subtract the sum of all # other frequencies items.remove(modes[char]) modes[char] = (modes[char][0], modes[char][1] - reduce(lambda a, b: (0, a[1] + b[1]), items)[1]) else: modes[char] = items[0] # build a list of possible delimiters modeList = modes.items() total = float(chunkLength * iteration) # (rows of consistent data) / (number of rows) = 100% consistency = 1.0 # minimum consistency threshold threshold = 0.9 while len(delims) == 0 and consistency >= threshold: for k, v in modeList: if v[0] > 0 and v[1] > 0: if ((v[1]/total) >= consistency and (delimiters is None or k in delimiters)): delims[k] = v consistency -= 0.01 if len(delims) == 1: delim = delims.keys()[0] skipinitialspace = (data[0].count(delim) == data[0].count("%c " % delim)) return (delim, skipinitialspace) # analyze another chunkLength lines start = end end += chunkLength if not delims: return ('', 0) # if there's more than one, fall back to a 'preferred' list if len(delims) > 1: for d in self.preferred: if d in delims.keys(): skipinitialspace = (data[0].count(d) == data[0].count("%c " % d)) return (d, skipinitialspace) # nothing else indicates a preference, pick the character that # dominates(?) items = [(v,k) for (k,v) in delims.items()] items.sort() delim = items[-1][1] skipinitialspace = (data[0].count(delim) == data[0].count("%c " % delim)) return (delim, skipinitialspace) def has_header(self, sample): # Creates a dictionary of types of data in each column. If any # column is of a single type (say, integers), *except* for the first # row, then the first row is presumed to be labels. If the type # can't be determined, it is assumed to be a string in which case # the length of the string is the determining factor: if all of the # rows except for the first are the same length, it's a header. # Finally, a 'vote' is taken at the end for each column, adding or # subtracting from the likelihood of the first row being a header. rdr = reader(StringIO(sample), self.sniff(sample)) header = rdr.next() # assume first row is header columns = len(header) columnTypes = {} for i in range(columns): columnTypes[i] = None checked = 0 for row in rdr: # arbitrary number of rows to check, to keep it sane if checked > 20: break checked += 1 if len(row) != columns: continue # skip rows that have irregular number of columns for col in columnTypes.keys(): for thisType in [int, long, float, complex]: try: thisType(row[col]) break except (ValueError, OverflowError): pass else: # fallback to length of string thisType = len(row[col]) # treat longs as ints if thisType == long: thisType = int if thisType != columnTypes[col]: if columnTypes[col] is None: # add new column type columnTypes[col] = thisType else: # type is inconsistent, remove column from # consideration del columnTypes[col] # finally, compare results against first row and "vote" # on whether it's a header hasHeader = 0 for col, colType in columnTypes.items(): if type(colType) == type(0): # it's a length if len(header[col]) != colType: hasHeader += 1 else: hasHeader -= 1 else: # attempt typecast try: colType(header[col]) except (ValueError, TypeError): hasHeader += 1 else: hasHeader -= 1 return hasHeader > 0
jskew/gnuradio
refs/heads/master
gr-blocks/python/blocks/qa_throttle.py
57
#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_throttle(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_01(self): # Test that we can make the block op = blocks.throttle(gr.sizeof_gr_complex, 1) if __name__ == '__main__': gr_unittest.run(test_throttle, "test_throttle.xml")
mwatts15/PyOpenWorm
refs/heads/master
PyOpenWorm/connection.py
1
""" .. class:: Connection connection ============= Connection between neurons """ from PyOpenWorm import Relationship class Connection(Relationship): def __init__(self, pre_cell, post_cell, number, syntype, synclass): self.pre_cell = pre_cell self.post_cell = post_cell self.number = int(number) self.syntype = syntype self.synclass = synclass def __str__(self): return "Connection from %s to %s (%i times, type: %s, neurotransmitter: %s)"%(self.pre_cell, self.post_cell, self.number, self.syntype, self.synclass)
matichorvat/pydelphin
refs/heads/master
delphin/itsdb.py
1
""" The itsdb module makes it easy to work with [incr tsdb()] profiles. The ItsdbProfile class works with whole profiles, but it generally relies on the module-level functions to do its work (such as get_relations() or decode_row()). Queries over profiles can be customized through the use of filters (see filter_rows()), applicators (see apply_rows()), and selectors (see select_rows()). In addition, one can create a new skeleton using the make_skeleton() function. """ import os import re from gzip import open as gzopen import logging from io import TextIOWrapper, BufferedReader from collections import defaultdict, namedtuple, OrderedDict from itertools import chain from contextlib import contextmanager from delphin.exceptions import ItsdbError from delphin.util import safe_int ############################################################################## # Module variables _relations_filename = 'relations' _field_delimiter = '@' _default_datatype_values = { ':integer': '-1' } _default_field_values = { 'i-wf': '1' } _primary_keys = [ ["i-id", "item"], ["p-id", "phenomenon"], ["ip-id", "item-phenomenon"], ["s-id", "set"], ["run-id", "run"], ["parse-id", "parse"], ["e-id", "edge"], ["f-id", "fold"] ] ############################################################################## # Non-class (i.e. static) functions Field = namedtuple('Field', ['name', 'datatype', 'key', 'other', 'comment']) ''' A tuple describing a column in an [incr tsdb()] profile. Args: name: the column name datatype: e.g. ":string" or ":integer" key: True if the column is a key in the database other: any other non-datatype, non-key attributes (like ":partial") comment: a description of the column ''' def get_relations(path): """ Parse the relations file and return a dictionary describing the database structure. Args: path: The path of the relations file. Returns: A dictionary mapping a table name to a list of Field tuples. """ relations = OrderedDict() table_re = re.compile(r'^(?P<table>\w.+):$') field_re = re.compile(r'\s*(?P<name>\S+)' r'(\s+(?P<props>[^#]+))?' r'(\s*#\s*(?P<comment>.*)$)?') f = open(path) current_table = None for line in f: table_match = table_re.search(line) field_match = field_re.search(line) if table_match is not None: current_table = table_match.group('table') if current_table not in relations: relations[current_table] = list() elif current_table is not None and field_match is not None: name = field_match.group('name') props = field_match.group('props').split() comment = field_match.group('comment') key = False if len(props) > 0: datatype = props.pop(0) if ':key' in props: key = True props.remove(':key') relations[current_table].append( Field(name, datatype, key, props, comment) ) f.close() return relations data_specifier_re = re.compile(r'(?P<table>[^:]+)?(:(?P<cols>.+))?$') def get_data_specifier(string): """ Return a tuple (table, col) for some [incr tsdb()] data specifier. For example:: item -> ('item', None) item:i-input -> ('item', ['i-input']) item:i-input@i-wf -> ('item', ['i-input', 'i-wf']) :i-input -> (None, ['i-input']) (otherwise) -> (None, None) """ match = data_specifier_re.match(string) if match is None: return (None, None) table = match.group('table') if table is not None: table = table.strip() cols = match.group('cols') if cols is not None: cols = list(map(str.strip, cols.split('@'))) return (table, cols) def decode_row(line): """ Decode a raw line from a profile into a list of column values. Decoding involves splitting the line by the field delimiter ('@' by default) and unescaping special characters. Args: line: a raw line from a [incr tsdb()] profile. Returns: A list of column values. """ fields = line.rstrip('\n').split(_field_delimiter) return list(map(unescape, fields)) def encode_row(fields): """ Encode a list of column values into a [incr tsdb()] profile line. Encoding involves escaping special characters for each value, then joining the values into a single string with the field delimiter ('@' by default). It does not fill in default values (see make_row()). Args: fields: a list of column values Returns: A [incr tsdb()]-encoded string """ return _field_delimiter.join(map(escape, map(str, fields))) _character_escapes = { _field_delimiter: '\\s', '\n': '\\n', '\\': '\\\\' } def _escape(m): return _character_escapes[m.group(0)] def escape(string): """ Replace any special characters with their [incr tsdb()] escape sequences. Default sequences are:: @ -> \s (newline) -> \\n \\ -> \\\\ Also see unescape() Args: string: the string to escape Returns: The escaped string """ return re.sub(r'(@|\n|\\)', _escape, string, re.UNICODE) _character_unescapes = {'\\s': _field_delimiter, '\\n': '\n', '\\\\': '\\'} def _unescape(m): return _character_unescapes[m.group(0)] def unescape(string): """ Replace [incr tsdb()] escape sequences with the regular equivalents. See escape(). Args: string: the escaped string Returns: The string with escape sequences replaced """ return re.sub(r'(\\s|\\n|\\\\)', _unescape, string, re.UNICODE) @contextmanager def _open_table(tbl_filename): if tbl_filename.endswith('.gz'): gz_filename = tbl_filename tbl_filename = tbl_filename[:-3] else: gz_filename = tbl_filename + '.gz' if os.path.exists(tbl_filename) and os.path.exists(gz_filename): logging.warning( 'Both gzipped and plaintext files were found; attempting to ' 'use the plaintext one.' ) if os.path.exists(tbl_filename): with open(tbl_filename) as f: yield f elif os.path.exists(gz_filename): # text mode only from py3.3; until then use TextIOWrapper with TextIOWrapper( BufferedReader(gzopen(tbl_filename + '.gz', mode='r')) ) as f: yield f else: raise ItsdbError( 'Table does not exist at {}(.gz)' .format(tbl_filename) ) def _write_table(profile_dir, table_name, rows, fields, append=False, gzip=False): # don't gzip if empty rows = iter(rows) try: first_row = next(rows) except StopIteration: gzip = False else: rows = chain([first_row], rows) if gzip and append: logging.warning('Appending to a gzip file may result in ' 'inefficient compression.') if not os.path.exists(profile_dir): raise ItsdbError('Profile directory does not exist: {}' .format(profile_dir)) tbl_filename = os.path.join(profile_dir, table_name) mode = 'a' if append else 'w' if gzip: # text mode only from py3.3; until then use TextIOWrapper #mode += 't' # text mode for gzip f = TextIOWrapper(gzopen(tbl_filename + '.gz', mode=mode)) else: f = open(tbl_filename, mode=mode) for row in rows: f.write(make_row(row, fields) + '\n') f.close() def make_row(row, fields): """ Encode a mapping of column name to values into a [incr tsdb()] profile line. The *fields* parameter determines what columns are used, and default values are provided if a column is missing from the mapping. Args: row: a dictionary mapping column names to values fields: an iterable of [Field] objects Returns: A [incr tsdb()]-encoded string """ row_fields = [row.get(f.name, str(default_value(f.name, f.datatype))) for f in fields] return encode_row(row_fields) def default_value(fieldname, datatype): """ Return the default value for a column. If the column name (e.g. *i-wf*) is defined to have an idiosyncratic value, that value is returned. Otherwise the default value for the column's datatype is returned. Args: fieldname: the column name (e.g. `i-wf`) datatype: the datatype of the column (e.g. `:integer`) Returns: The default value for the column. """ if fieldname in _default_field_values: return _default_field_values[fieldname] else: return _default_datatype_values.get(datatype, '') def filter_rows(filters, rows): """ Yield rows matching all applicable filters. Filter functions have binary arity (e.g. `filter(row, col)`) where the first parameter is the dictionary of row data, and the second parameter is the data at one particular column. Args: filters: a tuple of (cols, filter_func) where filter_func will be tested (filter_func(row, col)) for each col in cols where col exists in the row rows: an iterable of rows to filter Yields: Rows matching all applicable filters """ for row in rows: if all(condition(row, row.get(col)) for (cols, condition) in filters for col in cols if col is None or col in row): yield row def apply_rows(applicators, rows): """ Yield rows after applying the applicator functions to them. Applicators are simple unary functions that return a value, and that value is stored in the yielded row. E.g. `row[col] = applicator(row[col])`. These are useful to, e.g., cast strings to numeric datatypes, to convert formats stored in a cell, extract features for machine learning, and so on. Args: applicators: a tuple of (cols, applicator) where the applicator will be applied to each col in cols rows: an iterable of rows for applicators to be called on Yields: Rows with specified column values replaced with the results of the applicators """ for row in rows: for (cols, function) in applicators: for col in (cols or []): value = row.get(col, '') row[col] = function(row, value) yield row def select_rows(cols, rows, mode='list'): """ Yield data selected from rows. It is sometimes useful to select a subset of data from a profile. This function selects the data in *cols* from *rows* and yields it in a form specified by *mode*. Possible values of *mode* are: | mode | description | example `['i-id', 'i-wf']` | | -------------- | ----------------- | -------------------------- | | list (default) | a list of values | `[10, 1]` | | dict | col to value map | `{'i-id':'10','i-wf':'1'}` | | row | [incr tsdb()] row | `'10@1'` | Args: cols: an iterable of column names to select data for rows: the rows to select column data from mode: the form yielded data should take Yields: Selected data in the form specified by *mode*. """ mode = mode.lower() if mode == 'list': cast = lambda cols, data: data elif mode == 'dict': cast = lambda cols, data: dict(zip(cols, data)) elif mode == 'row': cast = lambda cols, data: encode_row(data) else: raise ItsdbError('Invalid mode for select operation: {}\n' ' Valid options include: list, dict, row' .format(mode)) for row in rows: data = [row.get(c) for c in cols] yield cast(cols, data) def match_rows(rows1, rows2, key, sort_keys=True): """ Yield triples of (value, left_rows, right_rows) where `left_rows` and `right_rows` are lists of rows that share the same column value for *key*. """ matched = OrderedDict() for i, rows in enumerate([rows1, rows2]): for row in rows: val = row[key] try: data = matched[val] except KeyError: matched[val] = ([], []) data = matched[val] data[i].append(row) vals = matched.keys() if sort_keys: vals = sorted(vals, key=safe_int) for val in vals: left, right = matched[val] yield (val, left, right) def make_skeleton(path, relations, item_rows, gzip=False): """ Instantiate a new profile skeleton (only the relations file and item file) from an existing relations file and a list of rows for the item table. For standard relations files, it is suggested to have, as a minimum, the `i-id` and `i-input` fields in the item rows. Args: path: the destination directory of the skeleton---must not already exist, as it will be created relations: the path to the relations file item_rows: the rows to use for the item file gzip: if `True`, the item file will be compressed Returns: An ItsdbProfile containing the skeleton data (but the profile data will already have been written to disk). Raises: ItsdbError if the destination directory could not be created. """ try: os.makedirs(path) except OSError: raise ItsdbError('Path already exists: {}.'.format(path)) import shutil shutil.copyfile(relations, os.path.join(path, _relations_filename)) prof = ItsdbProfile(path, index=False) prof.write_table('item', item_rows, gzip=gzip) return prof ############################################################################## # Profile class class ItsdbProfile(object): """ A [incr tsdb()] profile, analyzed and ready for reading or writing. """ # _tables is a list of table names to consider (for indexing, writing, # etc.). If `None`, all present in the relations file and on disk are # considered. Otherwise, only those present in the list are considered. _tables = None def __init__(self, path, filters=None, applicators=None, index=True): """ Only the *path* parameter is required. Args: path: The path of the directory containing the profile filters: A list of tuples [(table, cols, condition)] such that only rows in table where condition(row, row[col]) evaluates to a non-false value are returned; filters are tested in order for a table. applicators: A list of tuples [(table, cols, function)] which will be used when reading rows from a table---the function will be applied to the contents of the column cell in the table. For each table, each column-function pair will be applied in order. Applicators apply after the filters. index: If `True`, indices are created based on the keys of each table. """ self.root = path self.relations = get_relations( os.path.join(self.root, _relations_filename) ) if self._tables is None: self._tables = list(self.relations.keys()) self.filters = defaultdict(list) self.applicators = defaultdict(list) self._index = dict() for (table, cols, condition) in (filters or []): self.add_filter(table, cols, condition) for (table, cols, function) in (applicators or []): self.add_applicator(table, cols, function) if index: self._build_index() def add_filter(self, table, cols, condition): """ Add a filter. When reading *table*, rows in *table* will be filtered by filter_rows(). Args: table: The table the filter applies to. cols: The columns in *table* to filter on. condition: The filter function. """ if table is not None and table not in self.relations: raise ItsdbError('Cannot add filter; table "{}" is not defined ' 'by the relations file.' .format(table)) # this is a hack, though perhaps well-motivated if cols is None: cols = [None] self.filters[table].append((cols, condition)) def add_applicator(self, table, cols, function): """ Add an applicator. When reading *table*, rows in *table* will be modified by apply_rows(). Args: table: The table to apply the function to. cols: The columns in *table* to apply the function on. function: The applicator function. """ if table not in self.relations: raise ItsdbError('Cannot add applicator; table "{}" is not ' 'defined by the relations file.' .format(table)) if cols is None: raise ItsdbError('Cannot add applicator; columns not specified.') fields = set(f.name for f in self.relations[table]) for col in cols: if col not in fields: raise ItsdbError('Cannot add applicator; column "{}" not ' 'defined by the relations file.' .format(col)) self.applicators[table].append((cols, function)) def _build_index(self): self._index = {key: None for key, _ in _primary_keys} tables = self._tables if tables is not None: tables = set(tables) for (keyname, table) in _primary_keys: if table in tables: ids = set() try: for row in self.read_table(table): key = row[keyname] ids.add(key) except ItsdbError: logging.info('Failed to index {}.'.format(table)) self._index[keyname] = ids def table_relations(self, table): if table not in self.relations: raise ItsdbError( 'Table {} is not defined in the profiles relations.' .format(table) ) return self.relations[table] def read_raw_table(self, table): """ Yield rows in the [incr tsdb()] *table*. A row is a dictionary mapping column names to values. Data from a profile is decoded by decode_row(). No filters or applicators are used. """ field_names = [f.name for f in self.table_relations(table)] field_len = len(field_names) with _open_table(os.path.join(self.root, table)) as tbl: for line in tbl: fields = decode_row(line) if len(fields) != field_len: # should this throw an exception instead? logging.error('Number of stored fields ({}) ' 'differ from the expected number({}); ' 'fields may be misaligned!' .format(len(fields), field_len)) row = OrderedDict(zip(field_names, fields)) yield row def read_table(self, table, key_filter=True): """ Yield rows in the [incr tsdb()] *table* that pass any defined filters, and with values changed by any applicators. If no filters or applicators are defined, the result is the same as from ItsdbProfile.read_raw_table(). """ filters = self.filters[None] + self.filters[table] if key_filter: for f in self.relations[table]: key = f.name if f.key and (self._index.get(key) is not None): ids = self._index[key] # Can't keep local variables (like ids) in the scope of # the lambda expression, so make it a default argument. # Source: http://stackoverflow.com/a/938493/1441112 function = lambda r, x, ids=ids: x in ids filters.append(([key], function)) applicators = self.applicators[table] rows = self.read_raw_table(table) return filter_rows(filters, apply_rows(applicators, rows)) def select(self, table, cols, mode='list', key_filter=True): """ Yield selected rows from *table*. This method just calls select_rows() on the rows read from *table*. """ if cols is None: cols = [c.name for c in self.relations[table]] rows = self.read_table(table, key_filter=key_filter) for row in select_rows(cols, rows, mode=mode): yield row def join(self, table1, table2, key_filter=True): """ Yield rows from a table built by joining *table1* and *table2*. The column names in the rows have the original table name prepended and separated by a colon. For example, joining tables 'item' and 'parse' will result in column names like 'item:i-input' and 'parse:parse-id'. """ get_keys = lambda t: (f.name for f in self.relations[t] if f.key) keys = set(get_keys(table1)).intersection(get_keys(table2)) if not keys: raise ItsdbError( 'Cannot join tables "{}" and "{}"; no shared key exists.' .format(table1, table2) ) key = keys.pop() # this join method stores the whole of table2 in memory, but it is # MUCH faster than a nested loop method. Most profiles will fit in # memory anyway, so it's a decent tradeoff table2_data = defaultdict(list) for row in self.read_table(table2, key_filter=key_filter): table2_data[row[key]].append(row) for row1 in self.read_table(table1, key_filter=key_filter): for row2 in table2_data.get(row1[key], []): joinedrow = OrderedDict( [('{}:{}'.format(table1, k), v) for k, v in row1.items()] + [('{}:{}'.format(table2, k), v) for k, v in row2.items()] ) yield joinedrow def write_table(self, table, rows, append=False, gzip=False): """ Encode and write out *table* to the profile directory. Args: table: The name of the table to write rows: The rows to write to the table append: If `True`, append the encoded rows to any existing data. gzip: If `True`, compress the resulting table with `gzip`. The table's filename will have `.gz` appended. """ _write_table(self.root, table, rows, self.table_relations(table), append=append, gzip=gzip) def write_profile(self, profile_directory, relations_filename=None, key_filter=True, append=False, gzip=None): """ Write all tables (as specified by the relations) to a profile. Args: profile_directory: The directory of the output profile relations_filename: If given, read and use the relations at this path instead of the current profile's relations key_filter: If True, filter the rows by keys in the index append: If `True`, append profile data to existing tables in the output profile directory gzip: If `True`, compress tables using `gzip`. Table filenames will have `.gz` appended. If `False`, only write out text files. If `None`, use whatever the original file was. """ import shutil if relations_filename: relations = get_relations(relations_filename) else: relations_filename = os.path.join(self.root, _relations_filename) relations = self.relations shutil.copyfile(relations_filename, os.path.join(profile_directory, _relations_filename)) tables = self._tables if tables is not None: tables = set(tables) for table, fields in relations.items(): fn = os.path.join(self.root, table) if tables is None or table in tables: if os.path.exists(fn): pass elif os.path.exists(fn + '.gz'): fn += '.gz' else: logging.warning( 'Could not write "{}"; table doesn\'t exist.' .format(table) ) continue _gzip = gzip if gzip is not None else fn.endswith('.gz') rows = self.read_table(table, key_filter=key_filter) _write_table(profile_directory, table, rows, fields, append=append, gzip=_gzip) elif os.path.exists(fn) or os.path.exists(fn + '.gz'): logging.info('Ignoring "{}" table.'.format(table)) class ItsdbSkeleton(ItsdbProfile): """ A [incr tsdb()] skeleton, analyzed and ready for reading or writing. """ _tables = ['item']
apanju/GMIO_Odoo
refs/heads/8.0
addons/auth_oauth/res_config.py
292
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 openerp.osv import osv, fields import logging _logger = logging.getLogger(__name__) class base_config_settings(osv.TransientModel): _inherit = 'base.config.settings' _columns = { 'auth_oauth_google_enabled' : fields.boolean('Allow users to sign in with Google'), 'auth_oauth_google_client_id' : fields.char('Client ID'), 'auth_oauth_facebook_enabled' : fields.boolean('Allow users to sign in with Facebook'), 'auth_oauth_facebook_client_id' : fields.char('Client ID'), } def default_get(self, cr, uid, fields, context=None): res = super(base_config_settings, self).default_get(cr, uid, fields, context=context) res.update(self.get_oauth_providers(cr, uid, fields, context=context)) return res def get_oauth_providers(self, cr, uid, fields, context=None): google_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'auth_oauth', 'provider_google')[1] facebook_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'auth_oauth', 'provider_facebook')[1] rg = self.pool.get('auth.oauth.provider').read(cr, uid, [google_id], ['enabled','client_id'], context=context) rf = self.pool.get('auth.oauth.provider').read(cr, uid, [facebook_id], ['enabled','client_id'], context=context) return { 'auth_oauth_google_enabled': rg[0]['enabled'], 'auth_oauth_google_client_id': rg[0]['client_id'], 'auth_oauth_facebook_enabled': rf[0]['enabled'], 'auth_oauth_facebook_client_id': rf[0]['client_id'], } def set_oauth_providers(self, cr, uid, ids, context=None): google_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'auth_oauth', 'provider_google')[1] facebook_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'auth_oauth', 'provider_facebook')[1] config = self.browse(cr, uid, ids[0], context=context) rg = { 'enabled':config.auth_oauth_google_enabled, 'client_id':config.auth_oauth_google_client_id, } rf = { 'enabled':config.auth_oauth_facebook_enabled, 'client_id':config.auth_oauth_facebook_client_id, } self.pool.get('auth.oauth.provider').write(cr, uid, [google_id], rg) self.pool.get('auth.oauth.provider').write(cr, uid, [facebook_id], rf)
sudheesh001/oh-mainline
refs/heads/master
vendor/packages/Django/django/core/mail/backends/smtp.py
130
"""SMTP email backend class.""" import smtplib import ssl import threading from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.utils import DNS_NAME from django.core.mail.message import sanitize_address from django.utils.encoding import force_bytes class EmailBackend(BaseEmailBackend): """ A wrapper that manages the SMTP network connection. """ def __init__(self, host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, **kwargs): super(EmailBackend, self).__init__(fail_silently=fail_silently) self.host = host or settings.EMAIL_HOST self.port = port or settings.EMAIL_PORT if username is None: self.username = settings.EMAIL_HOST_USER else: self.username = username if password is None: self.password = settings.EMAIL_HOST_PASSWORD else: self.password = password if use_tls is None: self.use_tls = settings.EMAIL_USE_TLS else: self.use_tls = use_tls self.connection = None self._lock = threading.RLock() def open(self): """ Ensures we have a connection to the email server. Returns whether or not a new connection was required (True or False). """ if self.connection: # Nothing to do if the connection is already open. return False try: # If local_hostname is not specified, socket.getfqdn() gets used. # For performance, we use the cached FQDN for local_hostname. self.connection = smtplib.SMTP(self.host, self.port, local_hostname=DNS_NAME.get_fqdn()) if self.use_tls: self.connection.ehlo() self.connection.starttls() self.connection.ehlo() if self.username and self.password: self.connection.login(self.username, self.password) return True except: if not self.fail_silently: raise def close(self): """Closes the connection to the email server.""" if self.connection is None: return try: try: self.connection.quit() except (ssl.SSLError, smtplib.SMTPServerDisconnected): # This happens when calling quit() on a TLS connection # sometimes, or when the connection was already disconnected # by the server. self.connection.close() except: if self.fail_silently: return raise finally: self.connection = None def send_messages(self, email_messages): """ Sends one or more EmailMessage objects and returns the number of email messages sent. """ if not email_messages: return with self._lock: new_conn_created = self.open() if not self.connection: # We failed silently on open(). # Trying to send would be pointless. return num_sent = 0 for message in email_messages: sent = self._send(message) if sent: num_sent += 1 if new_conn_created: self.close() return num_sent def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False from_email = sanitize_address(email_message.from_email, email_message.encoding) recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.recipients()] message = email_message.message() charset = message.get_charset().get_output_charset() if message.get_charset() else 'utf-8' try: self.connection.sendmail(from_email, recipients, force_bytes(message.as_string(), charset)) except: if not self.fail_silently: raise return False return True
PaulAYoung/f2014_iolab
refs/heads/master
pymongoProject/venv/lib/python2.7/site-packages/pymongo/auth.py
13
# Copyright 2013-2014 MongoDB, 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. """Authentication helpers.""" import hmac try: import hashlib _MD5 = hashlib.md5 _DMOD = _MD5 except ImportError: # for Python < 2.5 import md5 _MD5 = md5.new _DMOD = md5 HAVE_KERBEROS = True try: import kerberos except ImportError: HAVE_KERBEROS = False from bson.binary import Binary from bson.py3compat import b from bson.son import SON from pymongo.errors import ConfigurationError, OperationFailure MECHANISMS = frozenset(['GSSAPI', 'MONGODB-CR', 'MONGODB-X509', 'PLAIN']) """The authentication mechanisms supported by PyMongo.""" def _build_credentials_tuple(mech, source, user, passwd, extra): """Build and return a mechanism specific credentials tuple. """ if mech == 'GSSAPI': gsn = extra.get('gssapiservicename', 'mongodb') # No password, source is always $external. return (mech, '$external', user, gsn) elif mech == 'MONGODB-X509': return (mech, '$external', user) return (mech, source, user, passwd) def _password_digest(username, password): """Get a password digest to use for authentication. """ if not isinstance(password, basestring): raise TypeError("password must be an instance " "of %s" % (basestring.__name__,)) if len(password) == 0: raise ValueError("password can't be empty") if not isinstance(username, basestring): raise TypeError("username must be an instance " "of %s" % (basestring.__name__,)) md5hash = _MD5() data = "%s:mongo:%s" % (username, password) md5hash.update(data.encode('utf-8')) return unicode(md5hash.hexdigest()) def _auth_key(nonce, username, password): """Get an auth key to use for authentication. """ digest = _password_digest(username, password) md5hash = _MD5() data = "%s%s%s" % (nonce, unicode(username), digest) md5hash.update(data.encode('utf-8')) return unicode(md5hash.hexdigest()) def _authenticate_gssapi(credentials, sock_info, cmd_func): """Authenticate using GSSAPI. """ try: dummy, username, gsn = credentials # Starting here and continuing through the while loop below - establish # the security context. See RFC 4752, Section 3.1, first paragraph. result, ctx = kerberos.authGSSClientInit( gsn + '@' + sock_info.host, gssflags=kerberos.GSS_C_MUTUAL_FLAG) if result != kerberos.AUTH_GSS_COMPLETE: raise OperationFailure('Kerberos context failed to initialize.') try: # pykerberos uses a weird mix of exceptions and return values # to indicate errors. # 0 == continue, 1 == complete, -1 == error # Only authGSSClientStep can return 0. if kerberos.authGSSClientStep(ctx, '') != 0: raise OperationFailure('Unknown kerberos ' 'failure in step function.') # Start a SASL conversation with mongod/s # Note: pykerberos deals with base64 encoded byte strings. # Since mongo accepts base64 strings as the payload we don't # have to use bson.binary.Binary. payload = kerberos.authGSSClientResponse(ctx) cmd = SON([('saslStart', 1), ('mechanism', 'GSSAPI'), ('payload', payload), ('autoAuthorize', 1)]) response, _ = cmd_func(sock_info, '$external', cmd) # Limit how many times we loop to catch protocol / library issues for _ in xrange(10): result = kerberos.authGSSClientStep(ctx, str(response['payload'])) if result == -1: raise OperationFailure('Unknown kerberos ' 'failure in step function.') payload = kerberos.authGSSClientResponse(ctx) or '' cmd = SON([('saslContinue', 1), ('conversationId', response['conversationId']), ('payload', payload)]) response, _ = cmd_func(sock_info, '$external', cmd) if result == kerberos.AUTH_GSS_COMPLETE: break else: raise OperationFailure('Kerberos ' 'authentication failed to complete.') # Once the security context is established actually authenticate. # See RFC 4752, Section 3.1, last two paragraphs. if kerberos.authGSSClientUnwrap(ctx, str(response['payload'])) != 1: raise OperationFailure('Unknown kerberos ' 'failure during GSS_Unwrap step.') if kerberos.authGSSClientWrap(ctx, kerberos.authGSSClientResponse(ctx), username) != 1: raise OperationFailure('Unknown kerberos ' 'failure during GSS_Wrap step.') payload = kerberos.authGSSClientResponse(ctx) cmd = SON([('saslContinue', 1), ('conversationId', response['conversationId']), ('payload', payload)]) response, _ = cmd_func(sock_info, '$external', cmd) finally: kerberos.authGSSClientClean(ctx) except kerberos.KrbError, exc: raise OperationFailure(str(exc)) def _authenticate_plain(credentials, sock_info, cmd_func): """Authenticate using SASL PLAIN (RFC 4616) """ source, username, password = credentials payload = ('\x00%s\x00%s' % (username, password)).encode('utf-8') cmd = SON([('saslStart', 1), ('mechanism', 'PLAIN'), ('payload', Binary(payload)), ('autoAuthorize', 1)]) cmd_func(sock_info, source, cmd) def _authenticate_cram_md5(credentials, sock_info, cmd_func): """Authenticate using CRAM-MD5 (RFC 2195) """ source, username, password = credentials # The password used as the mac key is the # same as what we use for MONGODB-CR passwd = _password_digest(username, password) cmd = SON([('saslStart', 1), ('mechanism', 'CRAM-MD5'), ('payload', Binary(b(''))), ('autoAuthorize', 1)]) response, _ = cmd_func(sock_info, source, cmd) # MD5 as implicit default digest for digestmod is deprecated # in python 3.4 mac = hmac.HMAC(key=passwd.encode('utf-8'), digestmod=_DMOD) mac.update(response['payload']) challenge = username.encode('utf-8') + b(' ') + b(mac.hexdigest()) cmd = SON([('saslContinue', 1), ('conversationId', response['conversationId']), ('payload', Binary(challenge))]) cmd_func(sock_info, source, cmd) def _authenticate_x509(credentials, sock_info, cmd_func): """Authenticate using MONGODB-X509. """ dummy, username = credentials query = SON([('authenticate', 1), ('mechanism', 'MONGODB-X509'), ('user', username)]) cmd_func(sock_info, '$external', query) def _authenticate_mongo_cr(credentials, sock_info, cmd_func): """Authenticate using MONGODB-CR. """ source, username, password = credentials # Get a nonce response, _ = cmd_func(sock_info, source, {'getnonce': 1}) nonce = response['nonce'] key = _auth_key(nonce, username, password) # Actually authenticate query = SON([('authenticate', 1), ('user', username), ('nonce', nonce), ('key', key)]) cmd_func(sock_info, source, query) _AUTH_MAP = { 'CRAM-MD5': _authenticate_cram_md5, 'GSSAPI': _authenticate_gssapi, 'MONGODB-CR': _authenticate_mongo_cr, 'MONGODB-X509': _authenticate_x509, 'PLAIN': _authenticate_plain, } def authenticate(credentials, sock_info, cmd_func): """Authenticate sock_info. """ mechanism = credentials[0] if mechanism == 'GSSAPI': if not HAVE_KERBEROS: raise ConfigurationError('The "kerberos" module must be ' 'installed to use GSSAPI authentication.') auth_func = _AUTH_MAP.get(mechanism) auth_func(credentials[1:], sock_info, cmd_func)
uglyboxer/linear_neuron
refs/heads/master
net-p3/lib/python3.5/site-packages/numpy/distutils/lib2def.py
193
from __future__ import division, absolute_import, print_function import re import sys import os import subprocess __doc__ = """This module generates a DEF file from the symbols in an MSVC-compiled DLL import library. It correctly discriminates between data and functions. The data is collected from the output of the program nm(1). Usage: python lib2def.py [libname.lib] [output.def] or python lib2def.py [libname.lib] > output.def libname.lib defaults to python<py_ver>.lib and output.def defaults to stdout Author: Robert Kern <kernr@mail.ncifcrf.gov> Last Update: April 30, 1999 """ __version__ = '0.1a' py_ver = "%d%d" % tuple(sys.version_info[:2]) DEFAULT_NM = 'nm -Cs' DEF_HEADER = """LIBRARY python%s.dll ;CODE PRELOAD MOVEABLE DISCARDABLE ;DATA PRELOAD SINGLE EXPORTS """ % py_ver # the header of the DEF file FUNC_RE = re.compile(r"^(.*) in python%s\.dll" % py_ver, re.MULTILINE) DATA_RE = re.compile(r"^_imp__(.*) in python%s\.dll" % py_ver, re.MULTILINE) def parse_cmd(): """Parses the command-line arguments. libfile, deffile = parse_cmd()""" if len(sys.argv) == 3: if sys.argv[1][-4:] == '.lib' and sys.argv[2][-4:] == '.def': libfile, deffile = sys.argv[1:] elif sys.argv[1][-4:] == '.def' and sys.argv[2][-4:] == '.lib': deffile, libfile = sys.argv[1:] else: print("I'm assuming that your first argument is the library") print("and the second is the DEF file.") elif len(sys.argv) == 2: if sys.argv[1][-4:] == '.def': deffile = sys.argv[1] libfile = 'python%s.lib' % py_ver elif sys.argv[1][-4:] == '.lib': deffile = None libfile = sys.argv[1] else: libfile = 'python%s.lib' % py_ver deffile = None return libfile, deffile def getnm(nm_cmd = ['nm', '-Cs', 'python%s.lib' % py_ver]): """Returns the output of nm_cmd via a pipe. nm_output = getnam(nm_cmd = 'nm -Cs py_lib')""" f = subprocess.Popen(nm_cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True) nm_output = f.stdout.read() f.stdout.close() return nm_output def parse_nm(nm_output): """Returns a tuple of lists: dlist for the list of data symbols and flist for the list of function symbols. dlist, flist = parse_nm(nm_output)""" data = DATA_RE.findall(nm_output) func = FUNC_RE.findall(nm_output) flist = [] for sym in data: if sym in func and (sym[:2] == 'Py' or sym[:3] == '_Py' or sym[:4] == 'init'): flist.append(sym) dlist = [] for sym in data: if sym not in flist and (sym[:2] == 'Py' or sym[:3] == '_Py'): dlist.append(sym) dlist.sort() flist.sort() return dlist, flist def output_def(dlist, flist, header, file = sys.stdout): """Outputs the final DEF file to a file defaulting to stdout. output_def(dlist, flist, header, file = sys.stdout)""" for data_sym in dlist: header = header + '\t%s DATA\n' % data_sym header = header + '\n' # blank line for func_sym in flist: header = header + '\t%s\n' % func_sym file.write(header) if __name__ == '__main__': libfile, deffile = parse_cmd() if deffile is None: deffile = sys.stdout else: deffile = open(deffile, 'w') nm_cmd = [str(DEFAULT_NM), str(libfile)] nm_output = getnm(nm_cmd) dlist, flist = parse_nm(nm_output) output_def(dlist, flist, DEF_HEADER, deffile)
cooperhewitt/py-cooperhewitt-roboteyes-shannon
refs/heads/master
setup.py
1
#!/usr/bin/env python from setuptools import setup, find_packages packages = find_packages() desc = open("README.md").read(), setup( name='cooperhewitt.roboteyes.shannon', namespace_packages=['cooperhewitt', 'cooperhewitt.roboteyes'], version='0.2', description='', author='Cooper Hewitt Smithsonian Design Museum', url='https://github.com/cooperhewitt/py-cooperhewitt-roboteyes-shannon', requires=[], packages=packages, scripts=[], download_url='https://github.com/cooperhewitt/py-cooperhewitt-roboteyes-shannon/tarball/master', license='BSD')
signed/intellij-community
refs/heads/master
python/testData/inspections/PyMethodMayBeStaticInspection/staticMethod.py
83
__author__ = 'ktisha' class Foo(object): @staticmethod def foo(param): # <-method here should not be highlighted return "foo"
cloudbase/cinder
refs/heads/master
cinder/tests/unit/backup/drivers/test_backup_posix.py
6
# Copyright (c) 2015 Red Hat, 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. """ Tests for Posix backup driver. """ import os import mock from six.moves import builtins from cinder.backup.drivers import posix from cinder import context from cinder import test from cinder.tests.unit import fake_constants as fake FAKE_FILE_SIZE = 52428800 FAKE_SHA_BLOCK_SIZE_BYTES = 1024 FAKE_BACKUP_ENABLE_PROGRESS_TIMER = True FAKE_CONTAINER = 'fake/container' FAKE_BACKUP_ID = fake.BACKUP_ID FAKE_BACKUP_ID_PART1 = fake.BACKUP_ID[:2] FAKE_BACKUP_ID_PART2 = fake.BACKUP_ID[2:4] FAKE_BACKUP_ID_REST = fake.BACKUP_ID[4:] FAKE_BACKUP = {'id': FAKE_BACKUP_ID, 'container': None} UPDATED_CONTAINER_NAME = os.path.join(FAKE_BACKUP_ID_PART1, FAKE_BACKUP_ID_PART2, FAKE_BACKUP_ID) FAKE_BACKUP_MOUNT_POINT_BASE = '/fake/mount-point-base' FAKE_EXPORT_PATH = 'fake/export/path' FAKE_BACKUP_POSIX_PATH = os.path.join(FAKE_BACKUP_MOUNT_POINT_BASE, FAKE_EXPORT_PATH) FAKE_PREFIX = 'prefix-' FAKE_CONTAINER_ENTRIES = [FAKE_PREFIX + 'one', FAKE_PREFIX + 'two', 'three'] EXPECTED_CONTAINER_ENTRIES = [FAKE_PREFIX + 'one', FAKE_PREFIX + 'two'] FAKE_OBJECT_NAME = 'fake-object-name' FAKE_OBJECT_PATH = os.path.join(FAKE_BACKUP_POSIX_PATH, FAKE_CONTAINER, FAKE_OBJECT_NAME) class PosixBackupDriverTestCase(test.TestCase): def setUp(self): super(PosixBackupDriverTestCase, self).setUp() self.ctxt = context.get_admin_context() self.override_config('backup_file_size', FAKE_FILE_SIZE) self.override_config('backup_sha_block_size_bytes', FAKE_SHA_BLOCK_SIZE_BYTES) self.override_config('backup_enable_progress_timer', FAKE_BACKUP_ENABLE_PROGRESS_TIMER) self.override_config('backup_posix_path', FAKE_BACKUP_POSIX_PATH) self.mock_object(posix, 'LOG') self.driver = posix.PosixBackupDriver(self.ctxt) def test_init(self): drv = posix.PosixBackupDriver(self.ctxt) self.assertEqual(FAKE_BACKUP_POSIX_PATH, drv.backup_path) def test_update_container_name_container_passed(self): result = self.driver.update_container_name(FAKE_BACKUP, FAKE_CONTAINER) self.assertEqual(FAKE_CONTAINER, result) def test_update_container_na_container_passed(self): result = self.driver.update_container_name(FAKE_BACKUP, None) self.assertEqual(UPDATED_CONTAINER_NAME, result) def test_put_container(self): self.mock_object(os.path, 'exists', mock.Mock(return_value=False)) self.mock_object(os, 'makedirs') self.mock_object(os, 'chmod') path = os.path.join(self.driver.backup_path, FAKE_CONTAINER) self.driver.put_container(FAKE_CONTAINER) os.path.exists.assert_called_once_with(path) os.makedirs.assert_called_once_with(path) os.chmod.assert_called_once_with(path, 0o770) def test_put_container_already_exists(self): self.mock_object(os.path, 'exists', mock.Mock(return_value=True)) self.mock_object(os, 'makedirs') self.mock_object(os, 'chmod') path = os.path.join(self.driver.backup_path, FAKE_CONTAINER) self.driver.put_container(FAKE_CONTAINER) os.path.exists.assert_called_once_with(path) self.assertEqual(0, os.makedirs.call_count) self.assertEqual(0, os.chmod.call_count) def test_put_container_exception(self): self.mock_object(os.path, 'exists', mock.Mock(return_value=False)) self.mock_object(os, 'makedirs', mock.Mock( side_effect=OSError)) self.mock_object(os, 'chmod') path = os.path.join(self.driver.backup_path, FAKE_CONTAINER) self.assertRaises(OSError, self.driver.put_container, FAKE_CONTAINER) os.path.exists.assert_called_once_with(path) os.makedirs.assert_called_once_with(path) self.assertEqual(0, os.chmod.call_count) def test_get_container_entries(self): self.mock_object(os, 'listdir', mock.Mock( return_value=FAKE_CONTAINER_ENTRIES)) result = self.driver.get_container_entries(FAKE_CONTAINER, FAKE_PREFIX) self.assertEqual(EXPECTED_CONTAINER_ENTRIES, result) def test_get_container_entries_no_list(self): self.mock_object(os, 'listdir', mock.Mock( return_value=[])) result = self.driver.get_container_entries(FAKE_CONTAINER, FAKE_PREFIX) self.assertEqual([], result) def test_get_container_entries_no_match(self): self.mock_object(os, 'listdir', mock.Mock( return_value=FAKE_CONTAINER_ENTRIES)) result = self.driver.get_container_entries(FAKE_CONTAINER, FAKE_PREFIX + 'garbage') self.assertEqual([], result) def test_get_object_writer(self): self.mock_object(builtins, 'open', mock.mock_open()) self.mock_object(os, 'chmod') self.driver.get_object_writer(FAKE_CONTAINER, FAKE_OBJECT_NAME) os.chmod.assert_called_once_with(FAKE_OBJECT_PATH, 0o660) builtins.open.assert_called_once_with(FAKE_OBJECT_PATH, 'wb') def test_get_object_reader(self): self.mock_object(builtins, 'open', mock.mock_open()) self.driver.get_object_reader(FAKE_CONTAINER, FAKE_OBJECT_NAME) builtins.open.assert_called_once_with(FAKE_OBJECT_PATH, 'rb') def test_delete_object(self): self.mock_object(os, 'remove') self.driver.delete_object(FAKE_CONTAINER, FAKE_OBJECT_NAME) def test_delete_nonexistent_object(self): self.mock_object(os, 'remove', mock.Mock( side_effect=OSError)) self.assertRaises(OSError, self.driver.delete_object, FAKE_CONTAINER, FAKE_OBJECT_NAME)
sfumato77/Kernel-4.8_Android-x86_BayTrail
refs/heads/master
tools/perf/scripts/python/check-perf-trace.py
1997
# perf script event handlers, generated by perf script -g python # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # This script tests basic functionality such as flag and symbol # strings, common_xxx() calls back into perf, begin, end, unhandled # events, etc. Basically, if this script runs successfully and # displays expected results, Python scripting support should be ok. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from Core import * from perf_trace_context import * unhandled = autodict() def trace_begin(): print "trace_begin" pass def trace_end(): print_unhandled() def irq__softirq_entry(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, vec): print_header(event_name, common_cpu, common_secs, common_nsecs, common_pid, common_comm) print_uncommon(context) print "vec=%s\n" % \ (symbol_str("irq__softirq_entry", "vec", vec)), def kmem__kmalloc(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, call_site, ptr, bytes_req, bytes_alloc, gfp_flags): print_header(event_name, common_cpu, common_secs, common_nsecs, common_pid, common_comm) print_uncommon(context) print "call_site=%u, ptr=%u, bytes_req=%u, " \ "bytes_alloc=%u, gfp_flags=%s\n" % \ (call_site, ptr, bytes_req, bytes_alloc, flag_str("kmem__kmalloc", "gfp_flags", gfp_flags)), def trace_unhandled(event_name, context, event_fields_dict): try: unhandled[event_name] += 1 except TypeError: unhandled[event_name] = 1 def print_header(event_name, cpu, secs, nsecs, pid, comm): print "%-20s %5u %05u.%09u %8u %-20s " % \ (event_name, cpu, secs, nsecs, pid, comm), # print trace fields not included in handler args def print_uncommon(context): print "common_preempt_count=%d, common_flags=%s, common_lock_depth=%d, " \ % (common_pc(context), trace_flag_str(common_flags(context)), \ common_lock_depth(context)) def print_unhandled(): keys = unhandled.keys() if not keys: return print "\nunhandled events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "-----------"), for event_name in keys: print "%-40s %10d\n" % (event_name, unhandled[event_name])
IlyaGusev/PoetryCorpus
refs/heads/master
poetry/apps/accounts/migrations/0002_auto_20170415_0020.py
1
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-15 00:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_username_max_length'), ('accounts', '0001_initial'), ] operations = [ migrations.AddField( model_name='myuser', name='groups', field=models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups'), ), migrations.AddField( model_name='myuser', name='is_superuser', field=models.BooleanField(default=False), ), migrations.AddField( model_name='myuser', name='user_permissions', field=models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions'), ), ]
jO-Osko/adventofcode2015
refs/heads/master
2015/problems/day19.py
1
DAY = 19 def part1(data): changes, start = parse_data(data.split("\n")) return len(make_next(start, changes)) def parse_data(data, reverse=False): changes = [] for line in data: if not line.strip(): break if reverse: changes.append(list(reversed(line.strip().split(" => ")))) else: changes.append(line.strip().split(" => ")) return changes, data[-1].strip() def make_next(starter, changes): replaced = set() len_s = len(starter) for old, new in changes: le = len(old) for j in range(len_s - le +1): if starter[j:j+le] == old: replaced.add(starter[:j] + new + starter[j+le:]) return replaced def part2(data): changes, start = parse_data(data.split("\n"), True) changes.sort(key= lambda x: -len(x[0])) return find_shortest_path(start, "e", changes) # Greedy, but works fast enough def find_shortest_path(start, end, changes): mi = float("inf") def find_path(current, cost): if current == end: nonlocal mi if cost < mi: mi = cost print(mi) for nex in make_next(current, changes): find_path(nex, cost+1) find_path(start, 0) return mi DATA = """Al => ThF Al => ThRnFAr B => BCa B => TiB B => TiRnFAr Ca => CaCa Ca => PB Ca => PRnFAr Ca => SiRnFYFAr Ca => SiRnMgAr Ca => SiTh F => CaF F => PMg F => SiAl H => CRnAlAr H => CRnFYFYFAr H => CRnFYMgAr H => CRnMgYFAr H => HCa H => NRnFYFAr H => NRnMgAr H => NTh H => OB H => ORnFAr Mg => BF Mg => TiMg N => CRnFAr N => HSi O => CRnFYFAr O => CRnMgAr O => HP O => NRnFAr O => OTi P => CaP P => PTi P => SiRnFAr Si => CaSi Th => ThCa Ti => BP Ti => TiTi e => HF e => NAl e => OMg CRnSiRnCaPTiMgYCaPTiRnFArSiThFArCaSiThSiThPBCaCaSiRnSiRnTiTiMgArPBCaPMgYPTiRnFArFArCaSiRnBPMgArPRnCaPTiRnFArCaSiThCaCaFArPBCaCaPTiTiRnFArCaSiRnSiAlYSiThRnFArArCaSiRnBFArCaCaSiRnSiThCaCaCaFYCaPTiBCaSiThCaSiThPMgArSiRnCaPBFYCaCaFArCaCaCaCaSiThCaSiRnPRnFArPBSiThPRnFArSiRnMgArCaFYFArCaSiRnSiAlArTiTiTiTiTiTiTiRnPMgArPTiTiTiBSiRnSiAlArTiTiRnPMgArCaFYBPBPTiRnSiRnMgArSiThCaFArCaSiThFArPRnFArCaSiRnTiBSiThSiRnSiAlYCaFArPRnFArSiThCaFArCaCaSiThCaCaCaSiRnPRnCaFArFYPMgArCaPBCaPBSiRnFYPBCaFArCaSiAl""" print(part1(DATA)) print(part2(DATA))
twiest/openshift-tools
refs/heads/stg
openshift/installer/vendored/openshift-ansible-3.6.173.0.59/roles/openshift_health_checker/openshift_checks/etcd_traffic.py
7
"""Check that scans journalctl for messages caused as a symptom of increased etcd traffic.""" from openshift_checks import OpenShiftCheck class EtcdTraffic(OpenShiftCheck): """Check if host is being affected by an increase in etcd traffic.""" name = "etcd_traffic" tags = ["health", "etcd"] def is_active(self): """Skip hosts that do not have etcd in their group names.""" group_names = self.get_var("group_names", default=[]) valid_group_names = "etcd" in group_names version = self.get_major_minor_version(self.get_var("openshift_image_tag")) valid_version = version in ((3, 4), (3, 5)) return super(EtcdTraffic, self).is_active() and valid_group_names and valid_version def run(self): is_containerized = self.get_var("openshift", "common", "is_containerized") unit = "etcd_container" if is_containerized else "etcd" log_matchers = [{ "start_regexp": r"Starting Etcd Server", "regexp": r"etcd: sync duration of [^,]+, expected less than 1s", "unit": unit }] match = self.execute_module("search_journalctl", {"log_matchers": log_matchers}) if match.get("matched"): msg = ("Higher than normal etcd traffic detected.\n" "OpenShift 3.4 introduced an increase in etcd traffic.\n" "Upgrading to OpenShift 3.6 is recommended in order to fix this issue.\n" "Please refer to https://access.redhat.com/solutions/2916381 for more information.") return {"failed": True, "msg": msg} if match.get("failed"): return {"failed": True, "msg": "\n".join(match.get("errors"))} return {}
walac/build-mozharness
refs/heads/master
configs/b2g_bumper/v2.1.py
2
#!/usr/bin/env python config = { "exes": { # Get around the https warnings "hg": ['/usr/local/bin/hg', "--config", "web.cacerts=/etc/pki/tls/certs/ca-bundle.crt"], "hgtool.py": ["/usr/local/bin/hgtool.py"], "gittool.py": ["/usr/local/bin/gittool.py"], }, 'gecko_pull_url': 'https://hg.mozilla.org/releases/mozilla-b2g34_v2_1/', 'gecko_push_url': 'ssh://hg.mozilla.org/releases/mozilla-b2g34_v2_1/', 'gecko_local_dir': 'mozilla-b2g34_v2_1', 'git_ref_cache': '/builds/b2g_bumper/git_ref_cache.json', 'manifests_repo': 'https://git.mozilla.org/b2g/b2g-manifest.git', 'manifests_revision': 'origin/v2.1', 'hg_user': 'B2G Bumper Bot <release+b2gbumper@mozilla.com>', "ssh_key": "~/.ssh/ffxbld_rsa", "ssh_user": "ffxbld", 'hgtool_base_bundle_urls': ['https://ftp-ssl.mozilla.org/pub/mozilla.org/firefox/bundles'], 'gaia_repo_url': 'https://hg.mozilla.org/integration/gaia-2_1', 'gaia_revision_file': 'b2g/config/gaia.json', 'gaia_max_revisions': 5, # Which git branch this hg repo corresponds to 'gaia_git_branch': 'v2.1', 'gaia_git_repo': 'https://git.mozilla.org/releases/gaia.git', 'gaia_mapper_project': 'gaia', 'mapper_url': 'http://cruncher.build.mozilla.org/mapper/{project}/{vcs}/{rev}', 'devices': { 'dolphin': { 'ignore_projects': ['gecko'], 'ignore_groups': ['darwin'], }, 'emulator-kk': { 'ignore_projects': ['gecko'], 'ignore_groups': ['darwin'], }, 'emulator-jb': { 'ignore_projects': ['gecko'], 'ignore_groups': ['darwin'], }, 'emulator-ics': { 'ignore_projects': ['gecko'], 'ignore_groups': ['darwin'], 'manifest_file': 'emulator.xml', }, # Equivalent to emulator-ics - see bug 916134 # Remove once the above bug resolved 'emulator': { 'ignore_projects': ['gecko'], 'ignore_groups': ['darwin'], 'manifest_file': 'emulator.xml', }, 'flame': { 'ignore_projects': ['gecko'], 'ignore_groups': ['darwin'], }, 'flame-kk': { 'ignore_projects': ['gecko'], 'ignore_groups': ['darwin'], }, 'nexus-4': { 'ignore_projects': ['gecko'], 'ignore_groups': ['darwin'], }, }, 'repo_remote_mappings': { 'https://android.googlesource.com/': 'https://git.mozilla.org/external/aosp', 'git://codeaurora.org/': 'https://git.mozilla.org/external/caf', 'git://github.com/mozilla-b2g/': 'https://git.mozilla.org/b2g', 'git://github.com/mozilla/': 'https://git.mozilla.org/b2g', 'https://git.mozilla.org/releases': 'https://git.mozilla.org/releases', 'http://android.git.linaro.org/git-ro/': 'https://git.mozilla.org/external/linaro', 'http://sprdsource.spreadtrum.com:8085/b2g/android': 'https://git.mozilla.org/external/sprd-aosp', 'git://github.com/apitrace/': 'https://git.mozilla.org/external/apitrace', 'git://github.com/t2m-foxfone/': 'https://git.mozilla.org/external/t2m-foxfone', # Some mappings to ourself, we want to leave these as-is! 'https://git.mozilla.org/external/aosp': 'https://git.mozilla.org/external/aosp', 'https://git.mozilla.org/external/caf': 'https://git.mozilla.org/external/caf', 'https://git.mozilla.org/b2g': 'https://git.mozilla.org/b2g', 'https://git.mozilla.org/external/apitrace': 'https://git.mozilla.org/external/apitrace', 'https://git.mozilla.org/external/t2m-foxfone': 'https://git.mozilla.org/external/t2m-foxfone', }, }
zephyrplugins/zephyr
refs/heads/master
zephyr.plugin.jython/jython2.5.2rc3/Lib/test/test_old_mailbox.py
11
# This set of tests exercises the backward-compatibility class # in mailbox.py (the ones without write support). from __future__ import with_statement import mailbox import os import time import unittest from test import test_support # cleanup earlier tests try: os.unlink(test_support.TESTFN) except os.error: pass FROM_ = "From some.body@dummy.domain Sat Jul 24 13:43:35 2004\n" DUMMY_MESSAGE = """\ From: some.body@dummy.domain To: me@my.domain Subject: Simple Test This is a dummy message. """ class MaildirTestCase(unittest.TestCase): def setUp(self): # create a new maildir mailbox to work with: self._dir = test_support.TESTFN os.mkdir(self._dir) os.mkdir(os.path.join(self._dir, "cur")) os.mkdir(os.path.join(self._dir, "tmp")) os.mkdir(os.path.join(self._dir, "new")) self._counter = 1 self._msgfiles = [] def tearDown(self): map(os.unlink, self._msgfiles) os.rmdir(os.path.join(self._dir, "cur")) os.rmdir(os.path.join(self._dir, "tmp")) os.rmdir(os.path.join(self._dir, "new")) os.rmdir(self._dir) def createMessage(self, dir, mbox=False): t = int(time.time() % 1000000) pid = self._counter self._counter += 1 filename = os.extsep.join((str(t), str(pid), "myhostname", "mydomain")) tmpname = os.path.join(self._dir, "tmp", filename) newname = os.path.join(self._dir, dir, filename) fp = open(tmpname, "w") self._msgfiles.append(tmpname) if mbox: fp.write(FROM_) fp.write(DUMMY_MESSAGE) fp.close() if hasattr(os, "link"): os.link(tmpname, newname) else: fp = open(newname, "w") fp.write(DUMMY_MESSAGE) fp.close() self._msgfiles.append(newname) return tmpname def assert_and_close(self, message): self.assert_(message is not None) message.fp.close() def test_empty_maildir(self): """Test an empty maildir mailbox""" # Test for regression on bug #117490: self.mbox = mailbox.Maildir(test_support.TESTFN) self.assert_(len(self.mbox) == 0) self.assert_(self.mbox.next() is None) self.assert_(self.mbox.next() is None) def test_nonempty_maildir_cur(self): self.createMessage("cur") self.mbox = mailbox.Maildir(test_support.TESTFN) self.assert_(len(self.mbox) == 1) self.assert_and_close(self.mbox.next()) self.assert_(self.mbox.next() is None) self.assert_(self.mbox.next() is None) def test_nonempty_maildir_new(self): self.createMessage("new") self.mbox = mailbox.Maildir(test_support.TESTFN) self.assert_(len(self.mbox) == 1) self.assert_and_close(self.mbox.next()) self.assert_(self.mbox.next() is None) self.assert_(self.mbox.next() is None) def test_nonempty_maildir_both(self): self.createMessage("cur") self.createMessage("new") self.mbox = mailbox.Maildir(test_support.TESTFN) self.assert_(len(self.mbox) == 2) self.assert_and_close(self.mbox.next()) self.assert_and_close(self.mbox.next()) self.assert_(self.mbox.next() is None) self.assert_(self.mbox.next() is None) def test_unix_mbox(self): ### should be better! import email.Parser fname = self.createMessage("cur", True) n = 0 with open(fname) as fp: for msg in mailbox.PortableUnixMailbox(fp, email.Parser.Parser().parse): n += 1 self.assertEqual(msg["subject"], "Simple Test") self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE)) self.assertEqual(n, 1) class MboxTestCase(unittest.TestCase): def setUp(self): # create a new maildir mailbox to work with: self._path = test_support.TESTFN def tearDown(self): os.unlink(self._path) def test_from_regex (self): # Testing new regex from bug #1633678 f = open(self._path, 'w') f.write("""From fred@example.com Mon May 31 13:24:50 2004 +0200 Subject: message 1 body1 From fred@example.com Mon May 31 13:24:50 2004 -0200 Subject: message 2 body2 From fred@example.com Mon May 31 13:24:50 2004 Subject: message 3 body3 From fred@example.com Mon May 31 13:24:50 2004 Subject: message 4 body4 """) f.close() box = mailbox.UnixMailbox(open(self._path, 'r')) messages = list(iter(box)) self.assert_(len(messages) == 4) for message in messages: message.fp.close() # XXX We still need more tests! def test_main(): test_support.run_unittest(MaildirTestCase, MboxTestCase) if __name__ == "__main__": test_main()
FelixLoether/blog-project
refs/heads/master
blog/users/__init__.py
1
from blog import db, app from sqlalchemy import Column, Integer, String from passlib.apps import custom_app_context as pwd_context class User(db.Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String, unique=True) password = Column(String) def __init__(self, name, password): app.logger.info('Creating user "%s".', name) self.name = name self.password = pwd_context.encrypt(password) def verify(self, password): return pwd_context.verify(password, self.password)
ilay09/keystone
refs/heads/master
keystone/common/sql/data_migration_repo/versions/003_migrate_unencrypted_credentials.py
5
# 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 sqlalchemy as sql from keystone.credential.providers import fernet as credential_fernet def upgrade(migrate_engine): meta = sql.MetaData() meta.bind = migrate_engine session = sql.orm.sessionmaker(bind=migrate_engine)() credential_table = sql.Table('credential', meta, autoload=True) credentials = list(credential_table.select().execute()) for credential in credentials: crypto, keys = credential_fernet.get_multi_fernet_keys() primary_key_hash = credential_fernet.primary_key_hash(keys) encrypted_blob = crypto.encrypt(credential['blob'].encode('utf-8')) values = { 'encrypted_blob': encrypted_blob, 'key_hash': primary_key_hash } update = credential_table.update().where( credential_table.c.id == credential.id ).values(values) session.execute(update) session.commit() session.close()
jss-emr/openerp-7-src
refs/heads/master
openerp/tools/config.py
31
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import ConfigParser import optparse import os import sys import openerp import openerp.conf import openerp.loglevels as loglevels import logging import openerp.release as release class MyOption (optparse.Option, object): """ optparse Option with two additional attributes. The list of command line options (getopt.Option) is used to create the list of the configuration file options. When reading the file, and then reading the command line arguments, we don't want optparse.parse results to override the configuration file values. But if we provide default values to optparse, optparse will return them and we can't know if they were really provided by the user or not. A solution is to not use optparse's default attribute, but use a custom one (that will be copied to create the default values of the configuration file). """ def __init__(self, *opts, **attrs): self.my_default = attrs.pop('my_default', None) super(MyOption, self).__init__(*opts, **attrs) #.apidoc title: Server Configuration Loader def check_ssl(): try: from OpenSSL import SSL import socket return hasattr(socket, 'ssl') and hasattr(SSL, "Connection") except: return False DEFAULT_LOG_HANDLER = [':INFO'] class configmanager(object): def __init__(self, fname=None): # Options not exposed on the command line. Command line options will be added # from optparse's parser. self.options = { 'admin_passwd': 'admin', 'csv_internal_sep': ',', 'login_message': False, 'publisher_warranty_url': 'http://services.openerp.com/publisher-warranty/', 'reportgz': False, 'root_path': None, } # Not exposed in the configuration file. self.blacklist_for_save = set( ['publisher_warranty_url', 'load_language', 'root_path', 'init', 'save', 'config', 'update', 'stop_after_init']) # dictionary mapping option destination (keys in self.options) to MyOptions. self.casts = {} self.misc = {} self.config_file = fname self.has_ssl = check_ssl() self._LOGLEVELS = dict([(getattr(loglevels, 'LOG_%s' % x), getattr(logging, x)) for x in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'TEST', 'DEBUG', 'NOTSET')]) version = "%s %s" % (release.description, release.version) self.parser = parser = optparse.OptionParser(version=version, option_class=MyOption) # Server startup config group = optparse.OptionGroup(parser, "Common options") group.add_option("-c", "--config", dest="config", help="specify alternate config file") group.add_option("-s", "--save", action="store_true", dest="save", default=False, help="save configuration to ~/.openerp_serverrc") group.add_option("-i", "--init", dest="init", help="install one or more modules (comma-separated list, use \"all\" for all modules), requires -d") group.add_option("-u", "--update", dest="update", help="update one or more modules (comma-separated list, use \"all\" for all modules). Requires -d.") group.add_option("--without-demo", dest="without_demo", help="disable loading demo data for modules to be installed (comma-separated, use \"all\" for all modules). Requires -d and -i. Default is %default", my_default=False) group.add_option("-P", "--import-partial", dest="import_partial", my_default='', help="Use this for big data importation, if it crashes you will be able to continue at the current state. Provide a filename to store intermediate importation states.") group.add_option("--pidfile", dest="pidfile", help="file where the server pid will be stored") group.add_option("--addons-path", dest="addons_path", help="specify additional addons paths (separated by commas).", action="callback", callback=self._check_addons_path, nargs=1, type="string") group.add_option("--load", dest="server_wide_modules", help="Comma-separated list of server-wide modules default=web") parser.add_option_group(group) # XML-RPC / HTTP group = optparse.OptionGroup(parser, "XML-RPC Configuration") group.add_option("--xmlrpc-interface", dest="xmlrpc_interface", my_default='', help="Specify the TCP IP address for the XML-RPC protocol. The empty string binds to all interfaces.") group.add_option("--xmlrpc-port", dest="xmlrpc_port", my_default=8069, help="specify the TCP port for the XML-RPC protocol", type="int") group.add_option("--no-xmlrpc", dest="xmlrpc", action="store_false", my_default=True, help="disable the XML-RPC protocol") group.add_option("--proxy-mode", dest="proxy_mode", action="store_true", my_default=False, help="Enable correct behavior when behind a reverse proxy") parser.add_option_group(group) # XML-RPC / HTTPS title = "XML-RPC Secure Configuration" if not self.has_ssl: title += " (disabled as ssl is unavailable)" group = optparse.OptionGroup(parser, title) group.add_option("--xmlrpcs-interface", dest="xmlrpcs_interface", my_default='', help="Specify the TCP IP address for the XML-RPC Secure protocol. The empty string binds to all interfaces.") group.add_option("--xmlrpcs-port", dest="xmlrpcs_port", my_default=8071, help="specify the TCP port for the XML-RPC Secure protocol", type="int") group.add_option("--no-xmlrpcs", dest="xmlrpcs", action="store_false", my_default=True, help="disable the XML-RPC Secure protocol") group.add_option("--cert-file", dest="secure_cert_file", my_default='server.cert', help="specify the certificate file for the SSL connection") group.add_option("--pkey-file", dest="secure_pkey_file", my_default='server.pkey', help="specify the private key file for the SSL connection") parser.add_option_group(group) # NET-RPC group = optparse.OptionGroup(parser, "NET-RPC Configuration") group.add_option("--netrpc-interface", dest="netrpc_interface", my_default='', help="specify the TCP IP address for the NETRPC protocol") group.add_option("--netrpc-port", dest="netrpc_port", my_default=8070, help="specify the TCP port for the NETRPC protocol", type="int") # Needed a few day for runbot and saas group.add_option("--no-netrpc", dest="netrpc", action="store_false", my_default=False, help="disable the NETRPC protocol") group.add_option("--netrpc", dest="netrpc", action="store_true", my_default=False, help="enable the NETRPC protocol") parser.add_option_group(group) # WEB # TODO move to web addons after MetaOption merge group = optparse.OptionGroup(parser, "Web interface Configuration") group.add_option("--db-filter", dest="dbfilter", default='.*', help="Filter listed database", metavar="REGEXP") parser.add_option_group(group) # Static HTTP group = optparse.OptionGroup(parser, "Static HTTP service") group.add_option("--static-http-enable", dest="static_http_enable", action="store_true", my_default=False, help="enable static HTTP service for serving plain HTML files") group.add_option("--static-http-document-root", dest="static_http_document_root", help="specify the directory containing your static HTML files (e.g '/var/www/')") group.add_option("--static-http-url-prefix", dest="static_http_url_prefix", help="specify the URL root prefix where you want web browsers to access your static HTML files (e.g '/')") parser.add_option_group(group) # Testing Group group = optparse.OptionGroup(parser, "Testing Configuration") group.add_option("--test-file", dest="test_file", my_default=False, help="Launch a YML test file.") group.add_option("--test-report-directory", dest="test_report_directory", my_default=False, help="If set, will save sample of all reports in this directory.") group.add_option("--test-enable", action="store_true", dest="test_enable", my_default=False, help="Enable YAML and unit tests.") group.add_option("--test-commit", action="store_true", dest="test_commit", my_default=False, help="Commit database changes performed by YAML or XML tests.") parser.add_option_group(group) # Logging Group group = optparse.OptionGroup(parser, "Logging Configuration") group.add_option("--logfile", dest="logfile", help="file where the server log will be stored") group.add_option("--no-logrotate", dest="logrotate", action="store_false", my_default=True, help="do not rotate the logfile") group.add_option("--syslog", action="store_true", dest="syslog", my_default=False, help="Send the log to the syslog server") group.add_option('--log-handler', action="append", default=DEFAULT_LOG_HANDLER, my_default=DEFAULT_LOG_HANDLER, metavar="PREFIX:LEVEL", help='setup a handler at LEVEL for a given PREFIX. An empty PREFIX indicates the root logger. This option can be repeated. Example: "openerp.orm:DEBUG" or "werkzeug:CRITICAL" (default: ":INFO")') group.add_option('--log-request', action="append_const", dest="log_handler", const="openerp.netsvc.rpc.request:DEBUG", help='shortcut for --log-handler=openerp.netsvc.rpc.request:DEBUG') group.add_option('--log-response', action="append_const", dest="log_handler", const="openerp.netsvc.rpc.response:DEBUG", help='shortcut for --log-handler=openerp.netsvc.rpc.response:DEBUG') group.add_option('--log-web', action="append_const", dest="log_handler", const="openerp.addons.web.http:DEBUG", help='shortcut for --log-handler=openerp.addons.web.http:DEBUG') group.add_option('--log-sql', action="append_const", dest="log_handler", const="openerp.sql_db:DEBUG", help='shortcut for --log-handler=openerp.sql_db:DEBUG') # For backward-compatibility, map the old log levels to something # quite close. levels = ['info', 'debug_rpc', 'warn', 'test', 'critical', 'debug_sql', 'error', 'debug', 'debug_rpc_answer', 'notset'] group.add_option('--log-level', dest='log_level', type='choice', choices=levels, my_default='info', help='specify the level of the logging. Accepted values: ' + str(levels) + ' (deprecated option).') parser.add_option_group(group) # SMTP Group group = optparse.OptionGroup(parser, "SMTP Configuration") group.add_option('--email-from', dest='email_from', my_default=False, help='specify the SMTP email address for sending email') group.add_option('--smtp', dest='smtp_server', my_default='localhost', help='specify the SMTP server for sending email') group.add_option('--smtp-port', dest='smtp_port', my_default=25, help='specify the SMTP port', type="int") group.add_option('--smtp-ssl', dest='smtp_ssl', action='store_true', my_default=False, help='if passed, SMTP connections will be encrypted with SSL (STARTTLS)') group.add_option('--smtp-user', dest='smtp_user', my_default=False, help='specify the SMTP username for sending email') group.add_option('--smtp-password', dest='smtp_password', my_default=False, help='specify the SMTP password for sending email') parser.add_option_group(group) group = optparse.OptionGroup(parser, "Database related options") group.add_option("-d", "--database", dest="db_name", my_default=False, help="specify the database name") group.add_option("-r", "--db_user", dest="db_user", my_default=False, help="specify the database user name") group.add_option("-w", "--db_password", dest="db_password", my_default=False, help="specify the database password") group.add_option("--pg_path", dest="pg_path", help="specify the pg executable path") group.add_option("--db_host", dest="db_host", my_default=False, help="specify the database host") group.add_option("--db_port", dest="db_port", my_default=False, help="specify the database port", type="int") group.add_option("--db_maxconn", dest="db_maxconn", type='int', my_default=64, help="specify the the maximum number of physical connections to posgresql") group.add_option("--db-template", dest="db_template", my_default="template1", help="specify a custom database template to create a new database") parser.add_option_group(group) group = optparse.OptionGroup(parser, "Internationalisation options", "Use these options to translate OpenERP to another language." "See i18n section of the user manual. Option '-d' is mandatory." "Option '-l' is mandatory in case of importation" ) group.add_option('--load-language', dest="load_language", help="specifies the languages for the translations you want to be loaded") group.add_option('-l', "--language", dest="language", help="specify the language of the translation file. Use it with --i18n-export or --i18n-import") group.add_option("--i18n-export", dest="translate_out", help="export all sentences to be translated to a CSV file, a PO file or a TGZ archive and exit") group.add_option("--i18n-import", dest="translate_in", help="import a CSV or a PO file with translations and exit. The '-l' option is required.") group.add_option("--i18n-overwrite", dest="overwrite_existing_translations", action="store_true", my_default=False, help="overwrites existing translation terms on updating a module or importing a CSV or a PO file.") group.add_option("--modules", dest="translate_modules", help="specify modules to export. Use in combination with --i18n-export") parser.add_option_group(group) security = optparse.OptionGroup(parser, 'Security-related options') security.add_option('--no-database-list', action="store_false", dest='list_db', my_default=True, help="disable the ability to return the list of databases") parser.add_option_group(security) # Advanced options group = optparse.OptionGroup(parser, "Advanced options") group.add_option('--debug', dest='debug_mode', action='store_true', my_default=False, help='enable debug mode') group.add_option("--stop-after-init", action="store_true", dest="stop_after_init", my_default=False, help="stop the server after its initialization") group.add_option("-t", "--timezone", dest="timezone", my_default=False, help="specify reference timezone for the server (e.g. Europe/Brussels") group.add_option("--osv-memory-count-limit", dest="osv_memory_count_limit", my_default=False, help="Force a limit on the maximum number of records kept in the virtual " "osv_memory tables. The default is False, which means no count-based limit.", type="int") group.add_option("--osv-memory-age-limit", dest="osv_memory_age_limit", my_default=1.0, help="Force a limit on the maximum age of records kept in the virtual " "osv_memory tables. This is a decimal value expressed in hours, " "and the default is 1 hour.", type="float") group.add_option("--max-cron-threads", dest="max_cron_threads", my_default=2, help="Maximum number of threads processing concurrently cron jobs (default 2).", type="int") group.add_option("--unaccent", dest="unaccent", my_default=False, action="store_true", help="Use the unaccent function provided by the database when available.") parser.add_option_group(group) group = optparse.OptionGroup(parser, "Multiprocessing options") # TODO sensible default for the three following limits. group.add_option("--workers", dest="workers", my_default=0, help="Specify the number of workers, 0 disable prefork mode.", type="int") group.add_option("--limit-memory-soft", dest="limit_memory_soft", my_default=640 * 1024 * 1024, help="Maximum allowed virtual memory per worker, when reached the worker be reset after the current request (default 671088640 aka 640MB).", type="int") group.add_option("--limit-memory-hard", dest="limit_memory_hard", my_default=768 * 1024 * 1024, help="Maximum allowed virtual memory per worker, when reached, any memory allocation will fail (default 805306368 aka 768MB).", type="int") group.add_option("--limit-time-cpu", dest="limit_time_cpu", my_default=60, help="Maximum allowed CPU time per request (default 60).", type="int") group.add_option("--limit-time-real", dest="limit_time_real", my_default=120, help="Maximum allowed Real time per request (default 120).", type="int") group.add_option("--limit-request", dest="limit_request", my_default=8192, help="Maximum number of request to be processed per worker (default 8192).", type="int") parser.add_option_group(group) # Copy all optparse options (i.e. MyOption) into self.options. for group in parser.option_groups: for option in group.option_list: if option.dest not in self.options: self.options[option.dest] = option.my_default self.casts[option.dest] = option self.parse_config(None, False) def parse_config(self, args=None, complete=True): """ Parse the configuration file (if any) and the command-line arguments. This method initializes openerp.tools.config and openerp.conf (the former should be removed in the furture) with library-wide configuration values. This method must be called before proper usage of this library can be made. Typical usage of this method: openerp.tools.config.parse_config(sys.argv[1:]) :param complete: this is a hack used in __init__(), leave it to True. """ if args is None: args = [] opt, args = self.parser.parse_args(args) def die(cond, msg): if cond: self.parser.error(msg) # Ensures no illegitimate argument is silently discarded (avoids insidious "hyphen to dash" problem) die(args, "unrecognized parameters: '%s'" % " ".join(args)) die(bool(opt.syslog) and bool(opt.logfile), "the syslog and logfile options are exclusive") die(opt.translate_in and (not opt.language or not opt.db_name), "the i18n-import option cannot be used without the language (-l) and the database (-d) options") die(opt.overwrite_existing_translations and not (opt.translate_in or opt.update), "the i18n-overwrite option cannot be used without the i18n-import option or without the update option") die(opt.translate_out and (not opt.db_name), "the i18n-export option cannot be used without the database (-d) option") # Check if the config file exists (-c used, but not -s) die(not opt.save and opt.config and not os.path.exists(opt.config), "The config file '%s' selected with -c/--config doesn't exist, "\ "use -s/--save if you want to generate it"% opt.config) # place/search the config file on Win32 near the server installation # (../etc from the server) # if the server is run by an unprivileged user, he has to specify location of a config file where he has the rights to write, # else he won't be able to save the configurations, or even to start the server... if os.name == 'nt': rcfilepath = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'openerp-server.conf') else: rcfilepath = os.path.expanduser('~/.openerp_serverrc') self.rcfile = os.path.abspath( self.config_file or opt.config \ or os.environ.get('OPENERP_SERVER') or rcfilepath) self.load() # Verify that we want to log or not, if not the output will go to stdout if self.options['logfile'] in ('None', 'False'): self.options['logfile'] = False # the same for the pidfile if self.options['pidfile'] in ('None', 'False'): self.options['pidfile'] = False # if defined dont take the configfile value even if the defined value is None keys = ['xmlrpc_interface', 'xmlrpc_port', 'db_name', 'db_user', 'db_password', 'db_host', 'db_port', 'db_template', 'logfile', 'pidfile', 'smtp_port', 'email_from', 'smtp_server', 'smtp_user', 'smtp_password', 'netrpc_interface', 'netrpc_port', 'db_maxconn', 'import_partial', 'addons_path', 'netrpc', 'xmlrpc', 'syslog', 'without_demo', 'timezone', 'xmlrpcs_interface', 'xmlrpcs_port', 'xmlrpcs', 'static_http_enable', 'static_http_document_root', 'static_http_url_prefix', 'secure_cert_file', 'secure_pkey_file', 'dbfilter', 'log_handler', 'log_level' ] for arg in keys: # Copy the command-line argument (except the special case for log_handler, due to # action=append requiring a real default, so we cannot use the my_default workaround) if getattr(opt, arg) and getattr(opt, arg) != DEFAULT_LOG_HANDLER: self.options[arg] = getattr(opt, arg) # ... or keep, but cast, the config file value. elif isinstance(self.options[arg], basestring) and self.casts[arg].type in optparse.Option.TYPE_CHECKER: self.options[arg] = optparse.Option.TYPE_CHECKER[self.casts[arg].type](self.casts[arg], arg, self.options[arg]) if isinstance(self.options['log_handler'], basestring): self.options['log_handler'] = self.options['log_handler'].split(',') # if defined but None take the configfile value keys = [ 'language', 'translate_out', 'translate_in', 'overwrite_existing_translations', 'debug_mode', 'smtp_ssl', 'load_language', 'stop_after_init', 'logrotate', 'without_demo', 'netrpc', 'xmlrpc', 'syslog', 'list_db', 'xmlrpcs', 'proxy_mode', 'test_file', 'test_enable', 'test_commit', 'test_report_directory', 'osv_memory_count_limit', 'osv_memory_age_limit', 'max_cron_threads', 'unaccent', 'workers', 'limit_memory_hard', 'limit_memory_soft', 'limit_time_cpu', 'limit_time_real', 'limit_request' ] for arg in keys: # Copy the command-line argument... if getattr(opt, arg) is not None: self.options[arg] = getattr(opt, arg) # ... or keep, but cast, the config file value. elif isinstance(self.options[arg], basestring) and self.casts[arg].type in optparse.Option.TYPE_CHECKER: self.options[arg] = optparse.Option.TYPE_CHECKER[self.casts[arg].type](self.casts[arg], arg, self.options[arg]) self.options['root_path'] = os.path.abspath(os.path.expanduser(os.path.expandvars(os.path.dirname(openerp.__file__)))) if not self.options['addons_path'] or self.options['addons_path']=='None': self.options['addons_path'] = os.path.join(self.options['root_path'], 'addons') else: self.options['addons_path'] = ",".join( os.path.abspath(os.path.expanduser(os.path.expandvars(x))) for x in self.options['addons_path'].split(',')) self.options['init'] = opt.init and dict.fromkeys(opt.init.split(','), 1) or {} self.options["demo"] = not opt.without_demo and self.options['init'] or {} self.options['update'] = opt.update and dict.fromkeys(opt.update.split(','), 1) or {} self.options['translate_modules'] = opt.translate_modules and map(lambda m: m.strip(), opt.translate_modules.split(',')) or ['all'] self.options['translate_modules'].sort() # TODO checking the type of the parameters should be done for every # parameters, not just the timezone. # The call to get_server_timezone() sets the timezone; this should # probably done here. if self.options['timezone']: # Prevent the timezone to be True. (The config file parsing changes # the string 'True' to the boolean value True. It would be probably # be better to remove that conversion.) die(not isinstance(self.options['timezone'], basestring), "Invalid timezone value in configuration or environment: %r.\n" "Please fix this in your configuration." %(self.options['timezone'])) # If an explicit TZ was provided in the config, make sure it is known try: import pytz pytz.timezone(self.options['timezone']) except pytz.UnknownTimeZoneError: die(True, "The specified timezone (%s) is invalid" % self.options['timezone']) except: # If pytz is missing, don't check the provided TZ, it will be ignored anyway. pass if opt.pg_path: self.options['pg_path'] = opt.pg_path if self.options.get('language', False): if len(self.options['language']) > 5: raise Exception('ERROR: The Lang name must take max 5 chars, Eg: -lfr_BE') if not self.options['db_user']: try: import getpass self.options['db_user'] = getpass.getuser() except: self.options['db_user'] = None die(not self.options['db_user'], 'ERROR: No user specified for the connection to the database') if self.options['db_password']: if sys.platform == 'win32' and not self.options['db_host']: self.options['db_host'] = 'localhost' #if self.options['db_host']: # self._generate_pgpassfile() if opt.save: self.save() openerp.conf.addons_paths = self.options['addons_path'].split(',') if opt.server_wide_modules: openerp.conf.server_wide_modules = map(lambda m: m.strip(), opt.server_wide_modules.split(',')) else: openerp.conf.server_wide_modules = ['web','web_kanban'] if complete: openerp.modules.module.initialize_sys_path() openerp.modules.loading.open_openerp_namespace() def _generate_pgpassfile(self): """ Generate the pgpass file with the parameters from the command line (db_host, db_user, db_password) Used because pg_dump and pg_restore can not accept the password on the command line. """ is_win32 = sys.platform == 'win32' if is_win32: filename = os.path.join(os.environ['APPDATA'], 'pgpass.conf') else: filename = os.path.join(os.environ['HOME'], '.pgpass') text_to_add = "%(db_host)s:*:*:%(db_user)s:%(db_password)s" % self.options if os.path.exists(filename): content = [x.strip() for x in file(filename, 'r').readlines()] if text_to_add in content: return fp = file(filename, 'a+') fp.write(text_to_add + "\n") fp.close() if is_win32: try: import _winreg except ImportError: _winreg = None x=_winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE) y = _winreg.OpenKey(x, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", 0,_winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(y,"PGPASSFILE", 0, _winreg.REG_EXPAND_SZ, filename ) _winreg.CloseKey(y) _winreg.CloseKey(x) else: import stat os.chmod(filename, stat.S_IRUSR + stat.S_IWUSR) def _is_addons_path(self, path): for f in os.listdir(path): modpath = os.path.join(path, f) if os.path.isdir(modpath): def hasfile(filename): return os.path.isfile(os.path.join(modpath, filename)) if hasfile('__init__.py') and (hasfile('__openerp__.py') or hasfile('__terp__.py')): return True return False def _check_addons_path(self, option, opt, value, parser): ad_paths = [] for path in value.split(','): path = path.strip() res = os.path.abspath(os.path.expanduser(path)) if not os.path.isdir(res): raise optparse.OptionValueError("option %s: no such directory: %r" % (opt, path)) if not self._is_addons_path(res): raise optparse.OptionValueError("option %s: The addons-path %r does not seem to a be a valid Addons Directory!" % (opt, path)) ad_paths.append(res) setattr(parser.values, option.dest, ",".join(ad_paths)) def load(self): p = ConfigParser.ConfigParser() try: p.read([self.rcfile]) for (name,value) in p.items('options'): if value=='True' or value=='true': value = True if value=='False' or value=='false': value = False self.options[name] = value #parse the other sections, as well for sec in p.sections(): if sec == 'options': continue if not self.misc.has_key(sec): self.misc[sec]= {} for (name, value) in p.items(sec): if value=='True' or value=='true': value = True if value=='False' or value=='false': value = False self.misc[sec][name] = value except IOError: pass except ConfigParser.NoSectionError: pass def save(self): p = ConfigParser.ConfigParser() loglevelnames = dict(zip(self._LOGLEVELS.values(), self._LOGLEVELS.keys())) p.add_section('options') for opt in sorted(self.options.keys()): if opt in ('version', 'language', 'translate_out', 'translate_in', 'overwrite_existing_translations', 'init', 'update'): continue if opt in self.blacklist_for_save: continue if opt in ('log_level',): p.set('options', opt, loglevelnames.get(self.options[opt], self.options[opt])) else: p.set('options', opt, self.options[opt]) for sec in sorted(self.misc.keys()): p.add_section(sec) for opt in sorted(self.misc[sec].keys()): p.set(sec,opt,self.misc[sec][opt]) # try to create the directories and write the file try: rc_exists = os.path.exists(self.rcfile) if not rc_exists and not os.path.exists(os.path.dirname(self.rcfile)): os.makedirs(os.path.dirname(self.rcfile)) try: p.write(file(self.rcfile, 'w')) if not rc_exists: os.chmod(self.rcfile, 0600) except IOError: sys.stderr.write("ERROR: couldn't write the config file\n") except OSError: # what to do if impossible? sys.stderr.write("ERROR: couldn't create the config directory\n") def get(self, key, default=None): return self.options.get(key, default) def get_misc(self, sect, key, default=None): return self.misc.get(sect,{}).get(key, default) def __setitem__(self, key, value): self.options[key] = value if key in self.options and isinstance(self.options[key], basestring) and \ key in self.casts and self.casts[key].type in optparse.Option.TYPE_CHECKER: self.options[key] = optparse.Option.TYPE_CHECKER[self.casts[key].type](self.casts[key], key, self.options[key]) def __getitem__(self, key): return self.options[key] config = configmanager() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Graha/kubernetes
refs/heads/master
hack/jenkins/test-history/gen_html_test.py
12
#!/usr/bin/env python # Copyright 2016 The Kubernetes 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 gen_html.""" import json import os import shutil import tempfile import unittest import gen_html TEST_DATA = { "test1": {"kubernetes-release": [{"build": 3, "failed": False, "time": 3.52}, {"build": 4, "failed": True, "time": 63.21}], "kubernetes-debug": [{"build": 5, "failed": False, "time": 7.56}, {"build": 6, "failed": False, "time": 8.43}], }, "test2": {"kubernetes-debug": [{"build": 6, "failed": True, "time": 3.53}]}, } class GenHtmlTest(unittest.TestCase): def gen_html(self, *args): return gen_html.gen_html(TEST_DATA, *args)[0] def testGenHtml(self): html = self.gen_html('') self.assertIn("test1", html) self.assertIn("test2", html) self.assertIn("release", html) self.assertIn("debug", html) def testGenHtmlFilter(self): html = self.gen_html('release') self.assertIn("release", html) self.assertIn('skipped">\ntest2', html) self.assertNotIn("debug", html) def testGenHtmlFilterExact(self): html = self.gen_html('release', True) self.assertNotIn('debug', html) def testMain(self): temp_dir = tempfile.mkdtemp(prefix='kube-test-hist-') try: tests_json = os.path.join(temp_dir, 'tests.json') with open(tests_json, 'w') as f: json.dump(TEST_DATA, f) gen_html.main(['--suites', '--prefixes', ',rel,deb', '--output-dir', temp_dir, '--input', tests_json]) for page in ('index', 'suite-kubernetes-debug', 'tests', 'tests-rel', 'tests-deb'): self.assertTrue(os.path.exists('%s/%s.html' % (temp_dir, page))) finally: shutil.rmtree(temp_dir) if __name__ == '__main__': unittest.main()
stefanw/django-cms
refs/heads/develop
cms/south_migrations/0069_static_placeholder_permissions.py
48
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name) user_model_label = '%s.%s' % (User._meta.app_label, User._meta.model_name) user_ptr_name = '%s_ptr' % User._meta.object_name.lower() class Migration(DataMigration): def forwards(self, orm): try: ct = orm['contenttypes.ContentType'].objects.get(model='page', app_label='cms') except orm['contenttypes.ContentType'].DoesNotExist: ct = orm['contenttypes.ContentType'].objects.create(name='page', model='page', app_label='cms') try: perm = orm['auth.permission'].objects.get(codename='edit_static_placeholder') except orm['auth.permission'].DoesNotExist: perm = orm['auth.permission'].objects.create(content_type=ct, codename='edit_static_placeholder', name=u'Can edit static placeholders') def backwards(self, orm): pass models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'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': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'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', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'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', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'cms.aliaspluginmodel': { 'Meta': {'object_name': 'AliasPluginModel', '_ormbases': ['cms.CMSPlugin']}, 'alias_placeholder': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'alias_placeholder'", 'null': 'True', 'to': "orm['cms.Placeholder']"}), u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}), 'plugin': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'alias_reference'", 'null': 'True', 'to': "orm['cms.CMSPlugin']"}) }, 'cms.cmsplugin': { 'Meta': {'object_name': 'CMSPlugin'}, 'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}), 'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}), 'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}), 'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.globalpagepermission': { 'Meta': {'object_name': 'GlobalPagePermission'}, 'can_add': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change_advanced_settings': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_change_permissions': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_delete': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_move_page': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_publish': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_recover_page': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_view': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'sites': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['sites.Site']", 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'cms.page': { 'Meta': {'ordering': "('tree_id', 'lft')", 'unique_together': "(('publisher_is_draft', 'application_namespace'), ('reverse_id', 'site', 'publisher_is_draft'))", 'object_name': 'Page'}, 'application_namespace': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'application_urls': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'changed_by': ('django.db.models.fields.CharField', [], {'max_length': '70'}), 'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.CharField', [], {'max_length': '70'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_navigation': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'is_home': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'languages': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'limit_visibility_in_menu': ('django.db.models.fields.SmallIntegerField', [], {'default': 'None', 'null': 'True', 'db_index': 'True', 'blank': 'True'}), 'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'navigation_extenders': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '80', 'null': 'True', 'blank': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['cms.Page']"}), 'placeholders': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['cms.Placeholder']", 'symmetrical': 'False'}), 'publication_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'publication_end_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'publisher_is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'publisher_public': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Page']"}), 'reverse_id': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '40', 'null': 'True', 'blank': 'True'}), 'revision_id': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'djangocms_pages'", 'to': u"orm['sites.Site']"}), 'soft_root': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'template': ('django.db.models.fields.CharField', [], {'default': "'INHERIT'", 'max_length': '100'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'xframe_options': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'cms.pagepermission': { 'Meta': {'object_name': 'PagePermission'}, 'can_add': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change_advanced_settings': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_change_permissions': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_delete': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_move_page': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_publish': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_view': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'grant_on': ('django.db.models.fields.IntegerField', [], {'default': '5'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Page']", 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'cms.pageuser': { 'Meta': {'object_name': 'PageUser', '_ormbases': [u'auth.User']}, 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_users'", 'to': u"orm['auth.User']"}), u'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}) }, 'cms.pageusergroup': { 'Meta': {'object_name': 'PageUserGroup', '_ormbases': [u'auth.Group']}, 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_usergroups'", 'to': u"orm['auth.User']"}), u'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}) }, 'cms.placeholder': { 'Meta': {'object_name': 'Placeholder'}, 'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slot': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}) }, 'cms.placeholderreference': { 'Meta': {'object_name': 'PlaceholderReference', '_ormbases': ['cms.CMSPlugin']}, u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'placeholder_ref': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}) }, 'cms.staticplaceholder': { 'Meta': {'unique_together': "(('code', 'site'),)", 'object_name': 'StaticPlaceholder'}, 'code': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'creation_method': ('django.db.models.fields.CharField', [], {'default': "'code'", 'max_length': '20', 'blank': 'True'}), 'dirty': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'draft': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'static_draft'", 'null': 'True', 'to': "orm['cms.Placeholder']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), 'public': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'static_public'", 'null': 'True', 'to': "orm['cms.Placeholder']"}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']", 'null': 'True', 'blank': 'True'}) }, 'cms.title': { 'Meta': {'unique_together': "(('language', 'page'),)", 'object_name': 'Title'}, 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'has_url_overwrite': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'menu_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'meta_description': ('django.db.models.fields.TextField', [], {'max_length': '155', 'null': 'True', 'blank': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'title_set'", 'to': "orm['cms.Page']"}), 'page_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'publisher_is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'publisher_public': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Title']"}), 'publisher_state': ('django.db.models.fields.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}), 'redirect': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'cms.usersettings': { 'Meta': {'object_name': 'UserSettings'}, 'clipboard': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'djangocms_usersettings'", 'unique': 'True', 'to': u"orm['auth.User']"}) }, u'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'}), u'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'}) }, u'sites.site': { 'Meta': {'ordering': "(u'domain',)", 'object_name': 'Site', 'db_table': "u'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['cms'] symmetrical = True
robjohnson189/home-assistant
refs/heads/dev
homeassistant/components/binary_sensor/modbus.py
28
""" Support for Modbus Coil sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.modbus/ """ import logging import voluptuous as vol import homeassistant.components.modbus as modbus from homeassistant.const import CONF_NAME from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.helpers import config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['modbus'] CONF_COIL = "coil" CONF_COILS = "coils" CONF_SLAVE = "slave" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_COILS): [{ vol.Required(CONF_COIL): cv.positive_int, vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_SLAVE): cv.positive_int }] }) def setup_platform(hass, config, add_devices, discovery_info=None): """Setup Modbus binary sensors.""" sensors = [] for coil in config.get(CONF_COILS): sensors.append(ModbusCoilSensor( coil.get(CONF_NAME), coil.get(CONF_SLAVE), coil.get(CONF_COIL))) add_devices(sensors) class ModbusCoilSensor(BinarySensorDevice): """Modbus coil sensor.""" def __init__(self, name, slave, coil): """Initialize the modbus coil sensor.""" self._name = name self._slave = int(slave) if slave else None self._coil = int(coil) self._value = None @property def is_on(self): """Return the state of the sensor.""" return self._value def update(self): """Update the state of the sensor.""" result = modbus.HUB.read_coils(self._slave, self._coil, 1) self._value = result.bits[0]
LogicalDash/kivy
refs/heads/master
examples/widgets/camera.py
71
from kivy.app import App from kivy.lang import Builder kv = ''' BoxLayout: orientation: 'vertical' Camera: id: camera resolution: 399, 299 BoxLayout: orientation: 'horizontal' size_hint_y: None height: '48dp' Button: text: 'Start' on_release: camera.play = True Button: text: 'Stop' on_release: camera.play = False ''' class CameraApp(App): def build(self): return Builder.load_string(kv) if __name__ == '__main__': CameraApp().run()
drpngx/tensorflow
refs/heads/master
tensorflow/contrib/timeseries/python/timeseries/state_management.py
67
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Classes for wrapping a model to operate on different data shapes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc from tensorflow.contrib.timeseries.python.timeseries import feature_keys from tensorflow.contrib.timeseries.python.timeseries import math_utils from tensorflow.contrib.timeseries.python.timeseries.model import ModelOutputs from tensorflow.python.estimator import estimator_lib from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.util import nest class PassthroughStateManager(object): """A minimal wrapper for models which do not need state management.""" def __init__(self): self._input_statistics = None self._graph_initialized = False def initialize_graph(self, model, input_statistics=None): """Adds required operations to the graph.""" del model # unused self._graph_initialized = True self._input_statistics = input_statistics def define_loss(self, model, features, mode): """Wrap "model" with StateManager-specific operations. Args: model: The model (inheriting from TimeSeriesModel) to manage state for. features: A dictionary with the following key/value pairs: feature_keys.TrainEvalFeatures.TIMES: A [batch size x window size] Tensor with times for each observation. feature_keys.TrainEvalFeatures.VALUES: A [batch size x window size x num features] Tensor with values for each observation. mode: The tf.estimator.ModeKeys mode to use (TRAIN or EVAL). Returns: A ModelOutputs object. Raises: ValueError: If start state was specified. """ if feature_keys.State.STATE_TUPLE in features: raise ValueError( "Overriding start state is not supported for this model.") return model.define_loss(features, mode) class _OverridableStateManager(PassthroughStateManager): """Base class for state managers which support overriding model state.""" @abc.abstractmethod def _define_loss_with_saved_state(self, model, features, mode): pass def define_loss(self, model, features, mode): """Switches between explicit start state and managed state.""" if feature_keys.FilteringFeatures.STATE_TUPLE in features: # Explicit start state has been provided, so we should use that. if mode == estimator_lib.ModeKeys.TRAIN: raise ValueError( "Overriding saved state for training is not supported (but a value " "for feature {} was specified).".format( feature_keys.FilteringFeatures.STATE_TUPLE)) start_state = features[feature_keys.FilteringFeatures.STATE_TUPLE] del features[feature_keys.FilteringFeatures.STATE_TUPLE] return model.get_batch_loss( features=features, mode=mode, state=start_state) else: # No explicit start state; use managed state. return self._define_loss_with_saved_state( model=model, features=features, mode=mode) class FilteringOnlyStateManager(_OverridableStateManager): """State manager for models which use state only for filtering. Window-based models (ARModel) do not require state to be fed during training (instead requiring a specific window size). Rather than requiring a minimum window size for filtering, these models maintain this window in their state, and so need state to be fed. """ def _define_loss_with_saved_state(self, model, features, mode): return model.define_loss(features, mode) class ChainingStateManager(_OverridableStateManager): """Maintains state across a batch for SequentialTimeSeriesModel subclasses. The batch dimension is treated as indexing sequential chunks of the same timeseries. End state from each chunk is fed as start state to the next chunk during the next timestep. This is an approximation to full-batch training for sequential models, but is typically much faster while still accurately recovering parameters. The speedup comes from reduced scheduling overhead of TensorFlow ops, since each operation can do much more work. """ def __init__(self, state_saving_interval=20, checkpoint_state=False): """Initialize the state manager. Args: state_saving_interval: This state manager saves intermediate model state every `state_saving_interval` times. Larger values save memory, and checkpoint size if `checkpoint_state` is enabled, but models will need to impute across artificial gaps of up to this size (i.e. gaps not appearing in the original data). This imputation may affect training. Set state_saving_interval to 1 to avoid any artificial imputation. checkpoint_state: If True, saved intermediate model state will be written to checkpoints. Checkpoints will then scale with dataset size. If False, state will be freshly imputed from the beginning of a series each time the model is restored, which means it may take a few iterations for state to warm up. """ super(ChainingStateManager, self).__init__() self._checkpoint_state = checkpoint_state self._state_saving_interval = state_saving_interval self._start_state = None self._cached_states = None def initialize_graph(self, model, input_statistics=None): """Adds required operations to the graph.""" super(ChainingStateManager, self).initialize_graph( model=model, input_statistics=input_statistics) self._start_state = model.get_start_state() self._cached_states = math_utils.TupleOfTensorsLookup( key_dtype=dtypes.int64, default_values=self._start_state, empty_key=-1, name="cached_states", checkpoint=self._checkpoint_state) def _define_loss_with_saved_state(self, model, features, mode): """Feeds end state from one training iteration into the next. Args: model: The model to wrap. Compatible with children of TimeSeriesModel. features: Dictionary with Tensor values defining the data to be processed. The expected key/value pairs are at minimum: feature_keys.TrainEvalFeatures.TIMES: A [number of chunks x window size] Tensor with times for each observation, the result of chunking a single longer time series. feature_keys.TrainEvalFeatures.VALUES: A [number of chunks x window size x num features] Tensor with values for each observation, corresponding to times. mode: The tf.estimator.ModeKeys mode to use. For EVAL and INFER, no batching is performed, which may be slow. This is to avoid giving cached and almost certainly stale values. Returns: A ModelOutputs object. Raises: ValueError: If initialize_graph has not been called. """ if not self._graph_initialized: raise ValueError("ChainingStateManager requires initialize_graph() to be " "called before use.") (loss_op, end_state, batch_predictions) = self._update_cached_states( model=model, features=features, mode=mode) # Add a batch dimension so state can be used directly (e.g. for predictions) # without the user manually reshaping it. last_end_state_flat = [end_state_value[-1][None] for end_state_value in nest.flatten(end_state)] batch_predictions["observed"] = features[ feature_keys.TrainEvalFeatures.VALUES] return ModelOutputs( loss=loss_op, end_state=nest.pack_sequence_as(end_state, last_end_state_flat), predictions=batch_predictions, prediction_times=features[feature_keys.TrainEvalFeatures.TIMES]) def _get_chunk_number(self, time): return time // self._state_saving_interval def _get_cached_states(self, times): """Retrieve cached states for a batch of times.""" read_chunk_numbers = self._get_chunk_number(times) looked_up_state = list(self._cached_states.lookup( math_ops.cast(read_chunk_numbers, dtypes.int64))) looked_up_state = tuple(looked_up_state) # We need to special-case the first chunk in a series to explicitly rely on # the model's starting state so that gradients flow back to it. Otherwise it # would affect only initialization, and would not be read from or updated # during training. Not doing this also isolates that part of the graph, # leading to errors on model reload if there are trainable variables # affecting a model's start state. if self._input_statistics is not None: start_time = self._input_statistics.start_time else: start_time = 0 set_to_start_state = math_ops.equal(read_chunk_numbers, self._get_chunk_number(start_time)) new_states = [] for start_state_value, cache_variable in zip( nest.flatten( math_utils.replicate_state(self._start_state, array_ops.shape(times)[0])), nest.flatten(looked_up_state)): new_states.append( array_ops.where(set_to_start_state, start_state_value, cache_variable)) looked_up_state = nest.pack_sequence_as(looked_up_state, new_states) return looked_up_state def _update_cached_states(self, model, features, mode): """Read, process, and write chunks to the cache.""" times = features[feature_keys.TrainEvalFeatures.TIMES] looked_up_state = self._get_cached_states(times[:, 0]) (model_loss, intermediate_states, batch_predictions) = model.per_step_batch_loss( features=features, mode=mode, state=looked_up_state) # We need to at least write to the bucket after the one we read from. min_chunk_numbers = self._get_chunk_number(times) + 1 # We write to the bucket that would have been read had the window started at # the next sample (except for the last sample in the window, which gets # written to the next bucket). This assumes fixed missing times (i.e. if we # were presented with times [10, 50] we will never see times [30, 50]). # # TODO(allenl): Retrieve the highest time less than the current time rather # than relying on fixed bucketing. write_chunk_numbers = math_ops.maximum( self._get_chunk_number(array_ops.concat( [times[:, 1:], times[:, -1:] + 1], axis=1)), min_chunk_numbers) # Write once for every computed state; this may mean that we write multiple # times to the same cell, but later writes will take precedence. save_ops = [ self._cached_states.insert( keys=write_chunk_numbers, values=intermediate_states)] end_state = nest.pack_sequence_as( intermediate_states, [state_element[:, -1] for state_element in nest.flatten(intermediate_states)]) with ops.control_dependencies(save_ops): # Make sure end states get saved at each iteration loss_op = array_ops.identity(model_loss) return loss_op, end_state, batch_predictions
teq10/learngit
refs/heads/master
hzlu-github.py
150
print "hello, thank you for your GIT Tutorial."
lasombra/rhiot
refs/heads/master
dockerfiles/openalpr/src/main/docker/2.2.0/src/bindings/python/test.py
18
from openalpr import Alpr from argparse import ArgumentParser parser = ArgumentParser(description='OpenALPR Python Test Program') parser.add_argument("-c", "--country", dest="country", action="store", default="us", help="License plate Country" ) parser.add_argument("--config", dest="config", action="store", default="/etc/openalpr/openalpr.conf", help="Path to openalpr.conf config file" ) parser.add_argument("--runtime_data", dest="runtime_data", action="store", default="/usr/share/openalpr/runtime_data", help="Path to OpenALPR runtime_data directory" ) parser.add_argument('plate_image', help='License plate image file') options = parser.parse_args() alpr = None try: alpr = Alpr(options.country, options.config, options.runtime_data) if not alpr.is_loaded(): print("Error loading OpenALPR") else: print("Using OpenALPR " + alpr.get_version()) alpr.set_top_n(7) alpr.set_default_region("wa") alpr.set_detect_region(False) jpeg_bytes = open(options.plate_image, "rb").read() results = alpr.recognize_array(jpeg_bytes) # Uncomment to see the full results structure # import pprint # pprint.pprint(results) print("Image size: %dx%d" %(results['img_width'], results['img_height'])) print("Processing Time: %f" % results['processing_time_ms']) i = 0 for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) finally: if alpr: alpr.unload()
agrista/odoo-saas
refs/heads/master
addons/mrp/company.py
381
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv,fields class company(osv.osv): _inherit = 'res.company' _columns = { 'manufacturing_lead': fields.float('Manufacturing Lead Time', required=True, help="Security days for each manufacturing operation."), } _defaults = { 'manufacturing_lead': lambda *a: 1.0, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
JohnDenker/brython
refs/heads/master
www/src/Lib/atexit.py
743
"""allow programmer to define multiple exit functions to be executedupon normal program termination. Two public functions, register and unregister, are defined. """ class __loader__(object): pass def _clear(*args,**kw): """_clear() -> None Clear the list of previously registered exit functions.""" pass def _run_exitfuncs(*args,**kw): """_run_exitfuncs() -> None Run all registered exit functions.""" pass def register(*args,**kw): """register(func, *args, **kwargs) -> func Register a function to be executed upon normal program termination func - function to be called at exit args - optional arguments to pass to func kwargs - optional keyword arguments to pass to func func is returned to facilitate usage as a decorator.""" pass def unregister(*args,**kw): """unregister(func) -> None Unregister a exit function which was previously registered using atexit.register func - function to be unregistered""" pass
dwightgunning/django
refs/heads/master
tests/mail/tests.py
119
# -*- coding: utf-8 -*- from __future__ import unicode_literals import asyncore import mimetypes import os import shutil import smtpd import sys import tempfile import threading from email.mime.text import MIMEText from smtplib import SMTP, SMTPException from ssl import SSLError from django.core import mail from django.core.mail import ( EmailMessage, EmailMultiAlternatives, mail_admins, mail_managers, send_mail, send_mass_mail, ) from django.core.mail.backends import console, dummy, filebased, locmem, smtp from django.core.mail.message import BadHeaderError from django.test import SimpleTestCase, override_settings from django.utils._os import upath from django.utils.encoding import force_bytes, force_text from django.utils.six import PY3, StringIO, binary_type from django.utils.translation import ugettext_lazy if PY3: from email.utils import parseaddr from email import message_from_bytes, message_from_binary_file else: from email.Utils import parseaddr from email import (message_from_string as message_from_bytes, message_from_file as message_from_binary_file) class HeadersCheckMixin(object): def assertMessageHasHeaders(self, message, headers): """ Check that :param message: has all :param headers: headers. :param message: can be an instance of an email.Message subclass or a string with the contents of an email message. :param headers: should be a set of (header-name, header-value) tuples. """ if isinstance(message, binary_type): message = message_from_bytes(message) msg_headers = set(message.items()) self.assertTrue(headers.issubset(msg_headers), msg='Message is missing ' 'the following headers: %s' % (headers - msg_headers),) class MailTests(HeadersCheckMixin, SimpleTestCase): """ Non-backend specific tests. """ def test_ascii(self): email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com']) message = email.message() self.assertEqual(message['Subject'], 'Subject') self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message['From'], 'from@example.com') self.assertEqual(message['To'], 'to@example.com') def test_multiple_recipients(self): email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com', 'other@example.com']) message = email.message() self.assertEqual(message['Subject'], 'Subject') self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message['From'], 'from@example.com') self.assertEqual(message['To'], 'to@example.com, other@example.com') def test_cc(self): """Regression test for #7722""" email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'], cc=['cc@example.com']) message = email.message() self.assertEqual(message['Cc'], 'cc@example.com') self.assertEqual(email.recipients(), ['to@example.com', 'cc@example.com']) # Test multiple CC with multiple To email = EmailMessage( 'Subject', 'Content', 'from@example.com', ['to@example.com', 'other@example.com'], cc=['cc@example.com', 'cc.other@example.com'] ) message = email.message() self.assertEqual(message['Cc'], 'cc@example.com, cc.other@example.com') self.assertEqual( email.recipients(), ['to@example.com', 'other@example.com', 'cc@example.com', 'cc.other@example.com'] ) # Testing with Bcc email = EmailMessage( 'Subject', 'Content', 'from@example.com', ['to@example.com', 'other@example.com'], cc=['cc@example.com', 'cc.other@example.com'], bcc=['bcc@example.com'] ) message = email.message() self.assertEqual(message['Cc'], 'cc@example.com, cc.other@example.com') self.assertEqual( email.recipients(), ['to@example.com', 'other@example.com', 'cc@example.com', 'cc.other@example.com', 'bcc@example.com'] ) def test_reply_to(self): email = EmailMessage( 'Subject', 'Content', 'from@example.com', ['to@example.com'], reply_to=['reply_to@example.com'], ) message = email.message() self.assertEqual(message['Reply-To'], 'reply_to@example.com') email = EmailMessage( 'Subject', 'Content', 'from@example.com', ['to@example.com'], reply_to=['reply_to1@example.com', 'reply_to2@example.com'] ) message = email.message() self.assertEqual(message['Reply-To'], 'reply_to1@example.com, reply_to2@example.com') def test_recipients_as_tuple(self): email = EmailMessage( 'Subject', 'Content', 'from@example.com', ('to@example.com', 'other@example.com'), cc=('cc@example.com', 'cc.other@example.com'), bcc=('bcc@example.com',) ) message = email.message() self.assertEqual(message['Cc'], 'cc@example.com, cc.other@example.com') self.assertEqual( email.recipients(), ['to@example.com', 'other@example.com', 'cc@example.com', 'cc.other@example.com', 'bcc@example.com'] ) def test_recipients_as_string(self): with self.assertRaisesMessage(TypeError, '"to" argument must be a list or tuple'): EmailMessage(to='foo@example.com') with self.assertRaisesMessage(TypeError, '"cc" argument must be a list or tuple'): EmailMessage(cc='foo@example.com') with self.assertRaisesMessage(TypeError, '"bcc" argument must be a list or tuple'): EmailMessage(bcc='foo@example.com') with self.assertRaisesMessage(TypeError, '"reply_to" argument must be a list or tuple'): EmailMessage(reply_to='reply_to@example.com') def test_header_injection(self): email = EmailMessage('Subject\nInjection Test', 'Content', 'from@example.com', ['to@example.com']) self.assertRaises(BadHeaderError, email.message) email = EmailMessage( ugettext_lazy('Subject\nInjection Test'), 'Content', 'from@example.com', ['to@example.com'] ) self.assertRaises(BadHeaderError, email.message) def test_space_continuation(self): """ Test for space continuation character in long (ASCII) subject headers (#7747) """ email = EmailMessage( 'Long subject lines that get wrapped should contain a space ' 'continuation character to get expected behavior in Outlook and Thunderbird', 'Content', 'from@example.com', ['to@example.com'] ) message = email.message() # Note that in Python 3, maximum line length has increased from 76 to 78 self.assertEqual( message['Subject'].encode(), b'Long subject lines that get wrapped should contain a space continuation\n' b' character to get expected behavior in Outlook and Thunderbird' ) def test_message_header_overrides(self): """ Specifying dates or message-ids in the extra headers overrides the default values (#9233) """ headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} email = EmailMessage('subject', 'content', 'from@example.com', ['to@example.com'], headers=headers) self.assertMessageHasHeaders(email.message(), { ('Content-Transfer-Encoding', '7bit'), ('Content-Type', 'text/plain; charset="utf-8"'), ('From', 'from@example.com'), ('MIME-Version', '1.0'), ('Message-ID', 'foo'), ('Subject', 'subject'), ('To', 'to@example.com'), ('date', 'Fri, 09 Nov 2001 01:08:47 -0000'), }) def test_from_header(self): """ Make sure we can manually set the From header (#9214) """ email = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) message = email.message() self.assertEqual(message['From'], 'from@example.com') def test_to_header(self): """ Make sure we can manually set the To header (#17444) """ email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['list-subscriber@example.com', 'list-subscriber2@example.com'], headers={'To': 'mailing-list@example.com'}) message = email.message() self.assertEqual(message['To'], 'mailing-list@example.com') self.assertEqual(email.to, ['list-subscriber@example.com', 'list-subscriber2@example.com']) # If we don't set the To header manually, it should default to the `to` argument to the constructor email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['list-subscriber@example.com', 'list-subscriber2@example.com']) message = email.message() self.assertEqual(message['To'], 'list-subscriber@example.com, list-subscriber2@example.com') self.assertEqual(email.to, ['list-subscriber@example.com', 'list-subscriber2@example.com']) def test_reply_to_header(self): """ Specifying 'Reply-To' in headers should override reply_to. """ email = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], reply_to=['foo@example.com'], headers={'Reply-To': 'override@example.com'}, ) message = email.message() self.assertEqual(message['Reply-To'], 'override@example.com') def test_multiple_message_call(self): """ Regression for #13259 - Make sure that headers are not changed when calling EmailMessage.message() """ email = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) message = email.message() self.assertEqual(message['From'], 'from@example.com') message = email.message() self.assertEqual(message['From'], 'from@example.com') def test_unicode_address_header(self): """ Regression for #11144 - When a to/from/cc header contains unicode, make sure the email addresses are parsed correctly (especially with regards to commas) """ email = EmailMessage( 'Subject', 'Content', 'from@example.com', ['"Firstname Sürname" <to@example.com>', 'other@example.com'], ) self.assertEqual( email.message()['To'], '=?utf-8?q?Firstname_S=C3=BCrname?= <to@example.com>, other@example.com' ) email = EmailMessage( 'Subject', 'Content', 'from@example.com', ['"Sürname, Firstname" <to@example.com>', 'other@example.com'], ) self.assertEqual( email.message()['To'], '=?utf-8?q?S=C3=BCrname=2C_Firstname?= <to@example.com>, other@example.com' ) def test_unicode_headers(self): email = EmailMessage("Gżegżółka", "Content", "from@example.com", ["to@example.com"], headers={"Sender": '"Firstname Sürname" <sender@example.com>', "Comments": 'My Sürname is non-ASCII'}) message = email.message() self.assertEqual(message['Subject'], '=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=') self.assertEqual(message['Sender'], '=?utf-8?q?Firstname_S=C3=BCrname?= <sender@example.com>') self.assertEqual(message['Comments'], '=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?=') def test_safe_mime_multipart(self): """ Make sure headers can be set with a different encoding than utf-8 in SafeMIMEMultipart as well """ headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} from_email, to = 'from@example.com', '"Sürname, Firstname" <to@example.com>' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, "text/html") msg.encoding = 'iso-8859-1' self.assertEqual(msg.message()['To'], '=?iso-8859-1?q?S=FCrname=2C_Firstname?= <to@example.com>') self.assertEqual(msg.message()['Subject'], '=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=') def test_encoding(self): """ Regression for #12791 - Encode body correctly with other encodings than utf-8 """ email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', 'from@example.com', ['other@example.com']) email.encoding = 'iso-8859-1' message = email.message() self.assertMessageHasHeaders(message, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="iso-8859-1"'), ('Content-Transfer-Encoding', 'quoted-printable'), ('Subject', 'Subject'), ('From', 'from@example.com'), ('To', 'other@example.com')}) self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.') # Make sure MIME attachments also works correctly with other encodings than utf-8 text_content = 'Firstname Sürname is a great guy.' html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>' msg = EmailMultiAlternatives('Subject', text_content, 'from@example.com', ['to@example.com']) msg.encoding = 'iso-8859-1' msg.attach_alternative(html_content, "text/html") payload0 = msg.message().get_payload(0) self.assertMessageHasHeaders(payload0, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="iso-8859-1"'), ('Content-Transfer-Encoding', 'quoted-printable')}) self.assertTrue(payload0.as_bytes().endswith(b'\n\nFirstname S=FCrname is a great guy.')) payload1 = msg.message().get_payload(1) self.assertMessageHasHeaders(payload1, { ('MIME-Version', '1.0'), ('Content-Type', 'text/html; charset="iso-8859-1"'), ('Content-Transfer-Encoding', 'quoted-printable')}) self.assertTrue( payload1.as_bytes().endswith(b'\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>') ) def test_attachments(self): """Regression test for #9367""" headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, "text/html") msg.attach("an attachment.pdf", b"%PDF-1.4.%...", mimetype="application/pdf") msg_bytes = msg.message().as_bytes() message = message_from_bytes(msg_bytes) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_content_type(), 'multipart/mixed') self.assertEqual(message.get_default_type(), 'text/plain') payload = message.get_payload() self.assertEqual(payload[0].get_content_type(), 'multipart/alternative') self.assertEqual(payload[1].get_content_type(), 'application/pdf') def test_non_ascii_attachment_filename(self): """Regression test for #14964""" headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' content = 'This is the message.' msg = EmailMessage(subject, content, from_email, [to], headers=headers) # Unicode in file name msg.attach("une pièce jointe.pdf", b"%PDF-1.4.%...", mimetype="application/pdf") msg_bytes = msg.message().as_bytes() message = message_from_bytes(msg_bytes) payload = message.get_payload() self.assertEqual(payload[1].get_filename(), 'une pièce jointe.pdf') def test_attach_file(self): """ Test attaching a file against different mimetypes and make sure that a file will be attached and sent properly even if an invalid mimetype is specified. """ files = ( # filename, actual mimetype ('file.txt', 'text/plain'), ('file.png', 'image/png'), ('file_txt', None), ('file_png', None), ('file_txt.png', 'image/png'), ('file_png.txt', 'text/plain'), ) test_mimetypes = ['text/plain', 'image/png', None] for basename, real_mimetype in files: for mimetype in test_mimetypes: email = EmailMessage('subject', 'body', 'from@example.com', ['to@example.com']) self.assertEqual(mimetypes.guess_type(basename)[0], real_mimetype) self.assertEqual(email.attachments, []) file_path = os.path.join(os.path.dirname(upath(__file__)), 'attachments', basename) email.attach_file(file_path, mimetype=mimetype) self.assertEqual(len(email.attachments), 1) self.assertIn(basename, email.attachments[0]) msgs_sent_num = email.send() self.assertEqual(msgs_sent_num, 1) def test_dummy_backend(self): """ Make sure that dummy backends returns correct number of sent messages """ connection = dummy.EmailBackend() email = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) self.assertEqual(connection.send_messages([email, email, email]), 3) def test_arbitrary_keyword(self): """ Make sure that get_connection() accepts arbitrary keyword that might be used with custom backends. """ c = mail.get_connection(fail_silently=True, foo='bar') self.assertTrue(c.fail_silently) def test_custom_backend(self): """Test custom backend defined in this suite.""" conn = mail.get_connection('mail.custombackend.EmailBackend') self.assertTrue(hasattr(conn, 'test_outbox')) email = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) conn.send_messages([email]) self.assertEqual(len(conn.test_outbox), 1) def test_backend_arg(self): """Test backend argument of mail.get_connection()""" self.assertIsInstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend) self.assertIsInstance( mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend ) self.assertIsInstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend) self.assertIsInstance( mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend ) tmp_dir = tempfile.mkdtemp() try: self.assertIsInstance( mail.get_connection('django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir), filebased.EmailBackend ) finally: shutil.rmtree(tmp_dir) self.assertIsInstance(mail.get_connection(), locmem.EmailBackend) @override_settings( EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend', ADMINS=[('nobody', 'nobody@example.com')], MANAGERS=[('nobody', 'nobody@example.com')]) def test_connection_arg(self): """Test connection argument to send_mail(), et. al.""" mail.outbox = [] # Send using non-default connection connection = mail.get_connection('mail.custombackend.EmailBackend') send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, 'Subject') connection = mail.get_connection('mail.custombackend.EmailBackend') send_mass_mail([ ('Subject1', 'Content1', 'from1@example.com', ['to1@example.com']), ('Subject2', 'Content2', 'from2@example.com', ['to2@example.com']), ], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 2) self.assertEqual(connection.test_outbox[0].subject, 'Subject1') self.assertEqual(connection.test_outbox[1].subject, 'Subject2') connection = mail.get_connection('mail.custombackend.EmailBackend') mail_admins('Admin message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Admin message') connection = mail.get_connection('mail.custombackend.EmailBackend') mail_managers('Manager message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Manager message') def test_dont_mangle_from_in_body(self): # Regression for #13433 - Make sure that EmailMessage doesn't mangle # 'From ' in message body. email = EmailMessage( 'Subject', 'From the future', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) self.assertNotIn(b'>From the future', email.message().as_bytes()) def test_dont_base64_encode(self): # Ticket #3472 # Shouldn't use Base64 encoding at all msg = EmailMessage( 'Subject', 'UTF-8 encoded body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) self.assertNotIn(b'Content-Transfer-Encoding: base64', msg.message().as_bytes()) # Ticket #11212 # Shouldn't use quoted printable, should detect it can represent content with 7 bit data msg = EmailMessage( 'Subject', 'Body with only ASCII characters.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) s = msg.message().as_bytes() self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s) self.assertIn(b'Content-Transfer-Encoding: 7bit', s) # Shouldn't use quoted printable, should detect it can represent content with 8 bit data msg = EmailMessage( 'Subject', 'Body with latin characters: àáä.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) s = msg.message().as_bytes() self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s) self.assertIn(b'Content-Transfer-Encoding: 8bit', s) msg = EmailMessage( 'Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) s = msg.message().as_bytes() self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s) self.assertIn(b'Content-Transfer-Encoding: 8bit', s) def test_dont_base64_encode_message_rfc822(self): # Ticket #18967 # Shouldn't use base64 encoding for a child EmailMessage attachment. # Create a child message first child_msg = EmailMessage( 'Child Subject', 'Some body of child message', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) child_s = child_msg.message().as_string() # Now create a parent parent_msg = EmailMessage( 'Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) # Attach to parent as a string parent_msg.attach(content=child_s, mimetype='message/rfc822') parent_s = parent_msg.message().as_string() # Verify that the child message header is not base64 encoded self.assertIn(str('Child Subject'), parent_s) # Feature test: try attaching email.Message object directly to the mail. parent_msg = EmailMessage( 'Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) parent_msg.attach(content=child_msg.message(), mimetype='message/rfc822') parent_s = parent_msg.message().as_string() # Verify that the child message header is not base64 encoded self.assertIn(str('Child Subject'), parent_s) # Feature test: try attaching Django's EmailMessage object directly to the mail. parent_msg = EmailMessage( 'Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) parent_msg.attach(content=child_msg, mimetype='message/rfc822') parent_s = parent_msg.message().as_string() # Verify that the child message header is not base64 encoded self.assertIn(str('Child Subject'), parent_s) class PythonGlobalState(SimpleTestCase): """ Tests for #12422 -- Django smarts (#2472/#11212) with charset of utf-8 text parts shouldn't pollute global email Python package charset registry when django.mail.message is imported. """ def test_utf8(self): txt = MIMEText('UTF-8 encoded body', 'plain', 'utf-8') self.assertIn('Content-Transfer-Encoding: base64', txt.as_string()) def test_7bit(self): txt = MIMEText('Body with only ASCII characters.', 'plain', 'utf-8') self.assertIn('Content-Transfer-Encoding: base64', txt.as_string()) def test_8bit_latin(self): txt = MIMEText('Body with latin characters: àáä.', 'plain', 'utf-8') self.assertIn(str('Content-Transfer-Encoding: base64'), txt.as_string()) def test_8bit_non_latin(self): txt = MIMEText('Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'plain', 'utf-8') self.assertIn(str('Content-Transfer-Encoding: base64'), txt.as_string()) class BaseEmailBackendTests(HeadersCheckMixin, object): email_backend = None def setUp(self): self.settings_override = override_settings(EMAIL_BACKEND=self.email_backend) self.settings_override.enable() def tearDown(self): self.settings_override.disable() def assertStartsWith(self, first, second): if not first.startswith(second): self.longMessage = True self.assertEqual(first[:len(second)], second, "First string doesn't start with the second.") def get_mailbox_content(self): raise NotImplementedError('subclasses of BaseEmailBackendTests must provide a get_mailbox_content() method') def flush_mailbox(self): raise NotImplementedError('subclasses of BaseEmailBackendTests may require a flush_mailbox() method') def get_the_message(self): mailbox = self.get_mailbox_content() self.assertEqual(len(mailbox), 1, "Expected exactly one message, got %d.\n%r" % (len(mailbox), [ m.as_string() for m in mailbox])) return mailbox[0] def test_send(self): email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com']) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "from@example.com") self.assertEqual(message.get_all("to"), ["to@example.com"]) def test_send_unicode(self): email = EmailMessage('Chère maman', 'Je t\'aime très fort', 'from@example.com', ['to@example.com']) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], '=?utf-8?q?Ch=C3=A8re_maman?=') self.assertEqual(force_text(message.get_payload(decode=True)), 'Je t\'aime très fort') def test_send_many(self): email1 = EmailMessage('Subject', 'Content1', 'from@example.com', ['to@example.com']) email2 = EmailMessage('Subject', 'Content2', 'from@example.com', ['to@example.com']) num_sent = mail.get_connection().send_messages([email1, email2]) self.assertEqual(num_sent, 2) messages = self.get_mailbox_content() self.assertEqual(len(messages), 2) self.assertEqual(messages[0].get_payload(), "Content1") self.assertEqual(messages[1].get_payload(), "Content2") def test_send_verbose_name(self): email = EmailMessage("Subject", "Content", '"Firstname Sürname" <from@example.com>', ["to@example.com"]) email.send() message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <from@example.com>") def test_plaintext_send_mail(self): """ Test send_mail without the html_message regression test for adding html_message parameter to send_mail() """ send_mail('Subject', 'Content', 'sender@example.com', ['nobody@example.com']) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get_all('to'), ['nobody@example.com']) self.assertFalse(message.is_multipart()) self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message.get_content_type(), 'text/plain') def test_html_send_mail(self): """Test html_message argument to send_mail""" send_mail('Subject', 'Content', 'sender@example.com', ['nobody@example.com'], html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get_all('to'), ['nobody@example.com']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), 'Content') self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') @override_settings(MANAGERS=[('nobody', 'nobody@example.com')]) def test_html_mail_managers(self): """Test html_message argument to mail_managers""" mail_managers('Subject', 'Content', html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.assertEqual(message.get_all('to'), ['nobody@example.com']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), 'Content') self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') @override_settings(ADMINS=[('nobody', 'nobody@example.com')]) def test_html_mail_admins(self): """Test html_message argument to mail_admins """ mail_admins('Subject', 'Content', html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.assertEqual(message.get_all('to'), ['nobody@example.com']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), 'Content') self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') @override_settings( ADMINS=[('nobody', 'nobody+admin@example.com')], MANAGERS=[('nobody', 'nobody+manager@example.com')]) def test_manager_and_admin_mail_prefix(self): """ String prefix + lazy translated subject = bad output Regression for #13494 """ mail_managers(ugettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.flush_mailbox() mail_admins(ugettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') @override_settings(ADMINS=[], MANAGERS=[]) def test_empty_admins(self): """ Test that mail_admins/mail_managers doesn't connect to the mail server if there are no recipients (#9383) """ mail_admins('hi', 'there') self.assertEqual(self.get_mailbox_content(), []) mail_managers('hi', 'there') self.assertEqual(self.get_mailbox_content(), []) def test_message_cc_header(self): """ Regression test for #7722 """ email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'], cc=['cc@example.com']) mail.get_connection().send_messages([email]) message = self.get_the_message() self.assertMessageHasHeaders(message, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="utf-8"'), ('Content-Transfer-Encoding', '7bit'), ('Subject', 'Subject'), ('From', 'from@example.com'), ('To', 'to@example.com'), ('Cc', 'cc@example.com')}) self.assertIn('\nDate: ', message.as_string()) def test_idn_send(self): """ Regression test for #14301 """ self.assertTrue(send_mail('Subject', 'Content', 'from@öäü.com', ['to@öäü.com'])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), 'from@xn--4ca9at.com') self.assertEqual(message.get('to'), 'to@xn--4ca9at.com') self.flush_mailbox() m = EmailMessage('Subject', 'Content', 'from@öäü.com', ['to@öäü.com'], cc=['cc@öäü.com']) m.send() message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), 'from@xn--4ca9at.com') self.assertEqual(message.get('to'), 'to@xn--4ca9at.com') self.assertEqual(message.get('cc'), 'cc@xn--4ca9at.com') def test_recipient_without_domain(self): """ Regression test for #15042 """ self.assertTrue(send_mail("Subject", "Content", "tester", ["django"])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), "tester") self.assertEqual(message.get('to'), "django") def test_lazy_addresses(self): """ Email sending should support lazy email addresses (#24416). """ _ = ugettext_lazy self.assertTrue(send_mail('Subject', 'Content', _('tester'), [_('django')])) message = self.get_the_message() self.assertEqual(message.get('from'), 'tester') self.assertEqual(message.get('to'), 'django') self.flush_mailbox() m = EmailMessage( 'Subject', 'Content', _('tester'), [_('to1'), _('to2')], cc=[_('cc1'), _('cc2')], bcc=[_('bcc')], reply_to=[_('reply')], ) self.assertEqual(m.recipients(), ['to1', 'to2', 'cc1', 'cc2', 'bcc']) m.send() message = self.get_the_message() self.assertEqual(message.get('from'), 'tester') self.assertEqual(message.get('to'), 'to1, to2') self.assertEqual(message.get('cc'), 'cc1, cc2') self.assertEqual(message.get('Reply-To'), 'reply') def test_close_connection(self): """ Test that connection can be closed (even when not explicitly opened) """ conn = mail.get_connection(username='', password='') conn.close() def test_use_as_contextmanager(self): """ Test that the connection can be used as a contextmanager. """ opened = [False] closed = [False] conn = mail.get_connection(username='', password='') def open(): opened[0] = True conn.open = open def close(): closed[0] = True conn.close = close with conn as same_conn: self.assertTrue(opened[0]) self.assertIs(same_conn, conn) self.assertFalse(closed[0]) self.assertTrue(closed[0]) class LocmemBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = 'django.core.mail.backends.locmem.EmailBackend' def get_mailbox_content(self): return [m.message() for m in mail.outbox] def flush_mailbox(self): mail.outbox = [] def tearDown(self): super(LocmemBackendTests, self).tearDown() mail.outbox = [] def test_locmem_shared_messages(self): """ Make sure that the locmen backend populates the outbox. """ connection = locmem.EmailBackend() connection2 = locmem.EmailBackend() email = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) connection.send_messages([email]) connection2.send_messages([email]) self.assertEqual(len(mail.outbox), 2) def test_validate_multiline_headers(self): # Ticket #18861 - Validate emails when using the locmem backend with self.assertRaises(BadHeaderError): send_mail('Subject\nMultiline', 'Content', 'from@example.com', ['to@example.com']) class FileBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = 'django.core.mail.backends.filebased.EmailBackend' def setUp(self): super(FileBackendTests, self).setUp() self.tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tmp_dir) self._settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir) self._settings_override.enable() def tearDown(self): self._settings_override.disable() super(FileBackendTests, self).tearDown() def flush_mailbox(self): for filename in os.listdir(self.tmp_dir): os.unlink(os.path.join(self.tmp_dir, filename)) def get_mailbox_content(self): messages = [] for filename in os.listdir(self.tmp_dir): with open(os.path.join(self.tmp_dir, filename), 'rb') as fp: session = fp.read().split(force_bytes('\n' + ('-' * 79) + '\n', encoding='ascii')) messages.extend(message_from_bytes(m) for m in session if m) return messages def test_file_sessions(self): """Make sure opening a connection creates a new file""" msg = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) connection = mail.get_connection() connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 1) with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]), 'rb') as fp: message = message_from_binary_file(fp) self.assertEqual(message.get_content_type(), 'text/plain') self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), 'from@example.com') self.assertEqual(message.get('to'), 'to@example.com') connection2 = mail.get_connection() connection2.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) msg.connection = mail.get_connection() self.assertTrue(connection.open()) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) connection.close() class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = 'django.core.mail.backends.console.EmailBackend' def setUp(self): super(ConsoleBackendTests, self).setUp() self.__stdout = sys.stdout self.stream = sys.stdout = StringIO() def tearDown(self): del self.stream sys.stdout = self.__stdout del self.__stdout super(ConsoleBackendTests, self).tearDown() def flush_mailbox(self): self.stream = sys.stdout = StringIO() def get_mailbox_content(self): messages = self.stream.getvalue().split(str('\n' + ('-' * 79) + '\n')) return [message_from_bytes(force_bytes(m)) for m in messages if m] def test_console_stream_kwarg(self): """ Test that the console backend can be pointed at an arbitrary stream. """ s = StringIO() connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s) send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection) message = force_bytes(s.getvalue().split('\n' + ('-' * 79) + '\n')[0]) self.assertMessageHasHeaders(message, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="utf-8"'), ('Content-Transfer-Encoding', '7bit'), ('Subject', 'Subject'), ('From', 'from@example.com'), ('To', 'to@example.com')}) self.assertIn(b'\nDate: ', message) class FakeSMTPChannel(smtpd.SMTPChannel): def collect_incoming_data(self, data): try: super(FakeSMTPChannel, self).collect_incoming_data(data) except UnicodeDecodeError: # ignore decode error in SSL/TLS connection tests as we only care # whether the connection attempt was made pass class FakeSMTPServer(smtpd.SMTPServer, threading.Thread): """ Asyncore SMTP server wrapped into a thread. Based on DummyFTPServer from: http://svn.python.org/view/python/branches/py3k/Lib/test/test_ftplib.py?revision=86061&view=markup """ channel_class = FakeSMTPChannel def __init__(self, *args, **kwargs): threading.Thread.__init__(self) # New kwarg added in Python 3.5; default switching to False in 3.6. if sys.version_info >= (3, 5): kwargs['decode_data'] = True smtpd.SMTPServer.__init__(self, *args, **kwargs) self._sink = [] self.active = False self.active_lock = threading.Lock() self.sink_lock = threading.Lock() def process_message(self, peer, mailfrom, rcpttos, data): if PY3: data = data.encode('utf-8') m = message_from_bytes(data) maddr = parseaddr(m.get('from'))[1] if mailfrom != maddr: return "553 '%s' != '%s'" % (mailfrom, maddr) with self.sink_lock: self._sink.append(m) def get_sink(self): with self.sink_lock: return self._sink[:] def flush_sink(self): with self.sink_lock: self._sink[:] = [] def start(self): assert not self.active self.__flag = threading.Event() threading.Thread.start(self) self.__flag.wait() def run(self): self.active = True self.__flag.set() while self.active and asyncore.socket_map: with self.active_lock: asyncore.loop(timeout=0.1, count=1) asyncore.close_all() def stop(self): if self.active: self.active = False self.join() class SMTPBackendTestsBase(SimpleTestCase): @classmethod def setUpClass(cls): super(SMTPBackendTestsBase, cls).setUpClass() cls.server = FakeSMTPServer(('127.0.0.1', 0), None) cls._settings_override = override_settings( EMAIL_HOST="127.0.0.1", EMAIL_PORT=cls.server.socket.getsockname()[1]) cls._settings_override.enable() cls.server.start() @classmethod def tearDownClass(cls): cls._settings_override.disable() cls.server.stop() super(SMTPBackendTestsBase, cls).tearDownClass() class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): email_backend = 'django.core.mail.backends.smtp.EmailBackend' def setUp(self): super(SMTPBackendTests, self).setUp() self.server.flush_sink() def tearDown(self): self.server.flush_sink() super(SMTPBackendTests, self).tearDown() def flush_mailbox(self): self.server.flush_sink() def get_mailbox_content(self): return self.server.get_sink() @override_settings( EMAIL_HOST_USER="not empty username", EMAIL_HOST_PASSWORD="not empty password") def test_email_authentication_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.username, 'not empty username') self.assertEqual(backend.password, 'not empty password') @override_settings( EMAIL_HOST_USER="not empty username", EMAIL_HOST_PASSWORD="not empty password") def test_email_authentication_override_settings(self): backend = smtp.EmailBackend(username='username', password='password') self.assertEqual(backend.username, 'username') self.assertEqual(backend.password, 'password') @override_settings( EMAIL_HOST_USER="not empty username", EMAIL_HOST_PASSWORD="not empty password") def test_email_disabled_authentication(self): backend = smtp.EmailBackend(username='', password='') self.assertEqual(backend.username, '') self.assertEqual(backend.password, '') def test_auth_attempted(self): """ Test that opening the backend with non empty username/password tries to authenticate against the SMTP server. """ backend = smtp.EmailBackend( username='not empty username', password='not empty password') try: self.assertRaisesMessage(SMTPException, 'SMTP AUTH extension not supported by server.', backend.open) finally: backend.close() def test_server_open(self): """ Test that open() tells us whether it opened a connection. """ backend = smtp.EmailBackend(username='', password='') self.assertFalse(backend.connection) opened = backend.open() backend.close() self.assertTrue(opened) @override_settings(EMAIL_USE_TLS=True) def test_email_tls_use_settings(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_tls) @override_settings(EMAIL_USE_TLS=True) def test_email_tls_override_settings(self): backend = smtp.EmailBackend(use_tls=False) self.assertFalse(backend.use_tls) def test_email_tls_default_disabled(self): backend = smtp.EmailBackend() self.assertFalse(backend.use_tls) @override_settings(EMAIL_USE_SSL=True) def test_email_ssl_use_settings(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_ssl) @override_settings(EMAIL_USE_SSL=True) def test_email_ssl_override_settings(self): backend = smtp.EmailBackend(use_ssl=False) self.assertFalse(backend.use_ssl) def test_email_ssl_default_disabled(self): backend = smtp.EmailBackend() self.assertFalse(backend.use_ssl) @override_settings(EMAIL_SSL_CERTFILE='foo') def test_email_ssl_certfile_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.ssl_certfile, 'foo') @override_settings(EMAIL_SSL_CERTFILE='foo') def test_email_ssl_certfile_override_settings(self): backend = smtp.EmailBackend(ssl_certfile='bar') self.assertEqual(backend.ssl_certfile, 'bar') def test_email_ssl_certfile_default_disabled(self): backend = smtp.EmailBackend() self.assertEqual(backend.ssl_certfile, None) @override_settings(EMAIL_SSL_KEYFILE='foo') def test_email_ssl_keyfile_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.ssl_keyfile, 'foo') @override_settings(EMAIL_SSL_KEYFILE='foo') def test_email_ssl_keyfile_override_settings(self): backend = smtp.EmailBackend(ssl_keyfile='bar') self.assertEqual(backend.ssl_keyfile, 'bar') def test_email_ssl_keyfile_default_disabled(self): backend = smtp.EmailBackend() self.assertEqual(backend.ssl_keyfile, None) @override_settings(EMAIL_USE_TLS=True) def test_email_tls_attempts_starttls(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_tls) try: self.assertRaisesMessage(SMTPException, 'STARTTLS extension not supported by server.', backend.open) finally: backend.close() @override_settings(EMAIL_USE_SSL=True) def test_email_ssl_attempts_ssl_connection(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_ssl) try: self.assertRaises(SSLError, backend.open) finally: backend.close() def test_connection_timeout_default(self): """Test that the connection's timeout value is None by default.""" connection = mail.get_connection('django.core.mail.backends.smtp.EmailBackend') self.assertEqual(connection.timeout, None) def test_connection_timeout_custom(self): """Test that the timeout parameter can be customized.""" class MyEmailBackend(smtp.EmailBackend): def __init__(self, *args, **kwargs): kwargs.setdefault('timeout', 42) super(MyEmailBackend, self).__init__(*args, **kwargs) myemailbackend = MyEmailBackend() myemailbackend.open() self.assertEqual(myemailbackend.timeout, 42) self.assertEqual(myemailbackend.connection.timeout, 42) myemailbackend.close() @override_settings(EMAIL_TIMEOUT=10) def test_email_timeout_override_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.timeout, 10) def test_email_msg_uses_crlf(self): """#23063 -- Test that RFC-compliant messages are sent over SMTP.""" send = SMTP.send try: smtp_messages = [] def mock_send(self, s): smtp_messages.append(s) return send(self, s) SMTP.send = mock_send email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com']) mail.get_connection().send_messages([email]) # Find the actual message msg = None for i, m in enumerate(smtp_messages): if m[:4] == 'data': msg = smtp_messages[i + 1] break self.assertTrue(msg) if PY3: msg = msg.decode('utf-8') # Ensure that the message only contains CRLF and not combinations of CRLF, LF, and CR. msg = msg.replace('\r\n', '') self.assertNotIn('\r', msg) self.assertNotIn('\n', msg) finally: SMTP.send = send class SMTPBackendStoppedServerTest(SMTPBackendTestsBase): """ This test requires a separate class, because it shuts down the FakeSMTPServer started in setUpClass(). It cannot be restarted ("RuntimeError: threads can only be started once"). """ def test_server_stopped(self): """ Test that closing the backend while the SMTP server is stopped doesn't raise an exception. """ backend = smtp.EmailBackend(username='', password='') backend.open() self.server.stop() backend.close()
shaunstanislaus/pyexperiment
refs/heads/master
pyexperiment/__init__.py
4
"""The pyexperiment module - quick and clean experiments with Python. """ from pyexperiment.version import __version__ from pyexperiment.utils.Singleton import delegate_singleton # For convenience, set up the basic tools here # pylint: disable=invalid-name from pyexperiment.Config import Config conf = delegate_singleton(Config) from pyexperiment.Logger import TimingLogger log = delegate_singleton(TimingLogger) from pyexperiment.State import State state = delegate_singleton(State)
salomon1184/bite-project
refs/heads/master
tools/bugs/server/appengine/models/url_bug_map/get_bugs.py
17
# Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Retrieve bugs based on url from mapping functionality. The retrieval returns the following data [[url, [bug*]]+] url associated with a set of bugs. The url can be a full url, domain, domain + path, etc. bug is the entire details of a given bug. The data returned will be a list containing all the given urls and componentized versions of those urls. Each url will be broken into the following: full url, url_domain + url_path, url_domain Each component will contain all the bugs that contain those components. Attributes: _MAX_RESULTS_CAP: Private static constant used used to cap the amount of results a clients can request. """ __author__ = ('alexto@google.com (Alexis O. Torres)', 'jason.stredwick@gmail.com (Jason Stredwick)') import logging import re import json from google.appengine.ext import db from bugs import kind from bugs.models.url_bug_map import url_bug_map from bugs.models.bugs import bug from util import model_to_dict _MAX_RESULTS_CAP = 500 class Error(Exception): pass def GetBugs(urls, limit=_MAX_RESULTS_CAP): """Returns a list of objects containing the mapping of url to bugs. TODO (jason.stredwick): Change the URL_BUG_MAP kind to isolate the break down of the url into components into a single result for a given url. Args: urls: A list or urls used to retrieve bugs. ([string]) limit: The max number of results to fetch. (integer) Returns: An object. ([{url: string, [kind.Kind.BUG]}]) Raises: Error: Raised if an error occurs accessing bug references. """ if limit > _MAX_RESULTS_CAP: limit = _MAX_RESULTS_CAP results = [] # For each url create a relevance mapping to related bugs. for url in urls: url_components = url_bug_map.PrepareUrl(url) results_dict = {} # Track which bugs have already been added. queries = GetQueriesForUrl(url_components) for (key, query) in queries: if not query: results.append({'url': key, 'bugs': []}) continue mappings = query.fetch(limit) if not mappings: results.append({'url': key, 'bugs': []}) continue result = [] keys = [] for mapping in mappings: try: bug_key = mapping.bug.key() id = bug_key.id() except Exception, e: raise Error(e) if id in results_dict: continue results_dict[id] = True keys.append(bug_key) if keys: try: result = db.get(keys) except Exception, e: raise Error(e) result = [model_to_dict.ModelToDict(r) for r in result if r] for r in result: r['kind'] = kind.Kind.BUG results.append({'url': key, 'bugs': result}) return results def GetQueriesForUrl(url_components): """Retrieves a list of queries to try for a given URL. Each query represents a possible way to find matches, each one has different relevancy implications: query[0] = Does a full URL match (considered the most relevant). query[1] = Does a hostname + path match. query[2] = Does a hostname match (considered the least relevant). Args: url_components: NormalizUrlResult object. Returns: A list containing Query objects. """ url = url_components['url'] hostname = url_components['hostname'] path = url_components['path'] url_no_schema = re.sub('^https?://', '', url) hostname_path = hostname + path url_query = (url, url_bug_map.UrlBugMap.all().filter('url = ', url)) hostname_path_query = (hostname + path, url_bug_map.UrlBugMap.all() .filter('hostname = ', hostname) .filter('path = ', path)) hostname_query = (hostname, url_bug_map.UrlBugMap.all() .filter('hostname = ', hostname)) queries = [] # This does not make sense to me. What if the url is only a schemeless # hostname + path? Why wouldn't one also search for url? # TODO (jasonstredwick): Figure out purpose and reinstate if necessary. #if url_no_schema == hostname_path: # if path: # queries.append(hostname_path_query) # queries.append(hostname_query) #el if hostname_path == hostname: # If no path then do query on it. queries.append(url_query) queries.append((hostname_path, None)) queries.append(hostname_query) else: queries.append(url_query) queries.append(hostname_path_query) queries.append(hostname_query) queries = [(k, q.order('-last_update')) for (k, q) in queries if q] # TODO (jason.stredwick): Add back in state filtering later. It requires the # passing of filter data with the request. # If states is specified, filter results to query bug matching it's value. #queries = [(k, q.filter('state = ', state.lower())) # for (k, q) in queries if q] return queries
kobejean/tensorflow
refs/heads/master
tensorflow/compiler/tests/eager_test.py
11
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Test cases for eager execution using XLA.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.compiler.tests import xla_test from tensorflow.core.protobuf import config_pb2 from tensorflow.python.eager import backprop from tensorflow.python.eager import context from tensorflow.python.eager import function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.layers import convolutional from tensorflow.python.layers import pooling from tensorflow.python.ops import array_ops from tensorflow.python.ops import embedding_ops from tensorflow.python.ops import gen_random_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.platform import googletest from tensorflow.python.training import adam class EagerTest(xla_test.XLATestCase): def testBasic(self): with self.test_scope(): three = constant_op.constant(3) five = constant_op.constant(5) product = three * five self.assertAllEqual(15, product) def testGradientTape(self): with self.test_scope(): x = constant_op.constant(1.0) y = constant_op.constant(10.0) with backprop.GradientTape(persistent=True) as tape: tape.watch(x) tape.watch(y) a = x + y + x * y da_dx = tape.gradient(a, x) da_dy = tape.gradient(a, y) self.assertEqual(11.0, da_dx.numpy()) self.assertEqual(2.0, da_dy.numpy()) def testExecuteListOutputLen0(self): with self.test_scope(): empty = constant_op.constant([], dtype=dtypes.float32) result = array_ops.unstack(empty, 0) self.assertTrue(isinstance(result, list)) self.assertEqual(0, len(result)) def testExecuteListOutputLen1(self): with self.test_scope(): split_dim = constant_op.constant(1) value = constant_op.constant([[0., 1., 2.], [3., 4., 5.]]) result = array_ops.split(value, 1, axis=split_dim) self.assertTrue(isinstance(result, list)) self.assertEqual(1, len(result)) self.assertAllEqual([[0, 1, 2], [3, 4, 5]], result[0]) def testExecuteListOutputLen3(self): with self.test_scope(): split_dim = constant_op.constant(1) value = constant_op.constant([[0., 1., 2.], [3., 4., 5.]]) result = array_ops.split(value, 3, axis=split_dim) self.assertTrue(isinstance(result, list)) self.assertEqual(3, len(result)) self.assertAllEqual([[0], [3]], result[0]) self.assertAllEqual([[1], [4]], result[1]) self.assertAllEqual([[2], [5]], result[2]) def testBasicGraph(self): # Run some ops eagerly with self.test_scope(): three = constant_op.constant(3) five = constant_op.constant(5) product = three * five self.assertAllEqual(15, product) # Run some ops graphly with context.graph_mode(), self.cached_session() as sess: with self.test_scope(): three = constant_op.constant(3) five = constant_op.constant(5) product = three * five self.assertAllEqual(15, sess.run(product)) def testDegenerateSlices(self): with self.test_scope(): npt = np.arange(1, 19, dtype=np.float32).reshape(3, 2, 3) t = constant_op.constant(npt) # degenerate by offering a forward interval with a negative stride self.assertAllEqual(npt[0:-1:-1, :, :], t[0:-1:-1, :, :]) # degenerate with a reverse interval with a positive stride self.assertAllEqual(npt[-1:0, :, :], t[-1:0, :, :]) # empty interval in every dimension self.assertAllEqual(npt[-1:0, 2:2, 2:3:-1], t[-1:0, 2:2, 2:3:-1]) def testIdentity(self): with self.test_scope(): self.assertAllEqual(2, array_ops.identity(2)) def testRandomOps(self): with self.test_scope(): tensor = gen_random_ops.random_uniform((2, 2), dtypes.float32) row0 = tensor[0].numpy() row1 = tensor[1].numpy() # It should be very unlikely to rng to generate two equal rows. self.assertFalse((row0 == row1).all()) def testIdentityOnVariable(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(True) i = array_ops.identity(v) self.assertAllEqual(True, i.numpy()) def testAssignAddVariable(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(1.0) v.assign_add(2.0) self.assertEqual(3.0, v.numpy()) def testReadAssignRead(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(1.0) val1 = v.read_value() v.assign_add(2.0) val2 = v.read_value() self.assertEqual(1.0, val1.numpy()) self.assertEqual(3.0, val2.numpy()) def testGradient(self): def f(x): return x with self.test_scope(): grad_fn = backprop.gradients_function(f) self.assertAllEqual(2., grad_fn(1., dy=2.)[0]) def testVariableGradient(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(1.0) def f(): x = v0 * v0 return x grads = backprop.implicit_grad(f)() self.assertEqual(2., grads[0][0].numpy()) def testMultipleVariableReads(self): # This test makes sure consecutive variable reads don't copy # the underlying memory. with self.test_scope(): # Create 128MiB variables var = resource_variable_ops.ResourceVariable( array_ops.ones([32, 1024, 1024])) # Read the same variable 100 times. If the underlying tensor # is not copied, this is a trivial operation. If it is copied, # this will eat over 13GB and OOM. values = [] for _ in range(100): values.append(var.value()) # The shape, shape_n, size, and rank are tested here because their # execution kernels (as opposed to compilation only tf2xla kernels) # are distincts from tf2xla kernels. def testShape(self): def const(value): return array_ops.shape( constant_op.constant(value)).numpy() def ones(value): return array_ops.shape( array_ops.ones(value)).numpy() with self.test_scope(): # Shapes of directly constructed tensors self.assertAllEqual([], const(3)) self.assertAllEqual([3], const([1.0, 2.0, 3.0])) self.assertAllEqual([2, 2], const([[1.0, 2.0], [3.0, 4.0]])) self.assertAllEqual([2, 1, 2], const([[[1.0, 2.0]], [[3.0, 4.0]]])) # Shapes of tensors created by op running on device # We make this distinction because directly constructed tensors # are treated differently in a few places that can influence shape: # - they always have on_host_tensor # - they and their shapes can be cached # - they end up on device via a copy, instead of as program output self.assertAllEqual([], ones([])) self.assertAllEqual([3], ones([3])) self.assertAllEqual([2, 2], ones([2, 2])) self.assertAllEqual([2, 1, 2], ones([2, 1, 2])) def testShapeN(self): with self.test_scope(): # Shapes of directly constructed tensors shapes = array_ops.shape_n([ constant_op.constant(1.0), constant_op.constant([1.0, 2.0, 3.0]), constant_op.constant([[1.0, 2.0], [3.0, 4.0]])]) self.assertAllEqual( [[], [3], [2, 2]], [x.numpy().tolist() for x in shapes]) # Shapes of tensors created by op running on device shapes = array_ops.shape_n([ array_ops.ones([]), array_ops.ones([3]), array_ops.ones([2, 2])]) self.assertAllEqual( [[], [3], [2, 2]], [x.numpy().tolist() for x in shapes]) def testSize(self): with self.test_scope(): self.assertEqual( 1, array_ops.size(constant_op.constant(1.0)).numpy()) self.assertEqual( 3, array_ops.size(constant_op.constant([1.0, 2.0, 3.0])).numpy()) self.assertEqual( 4, array_ops.size( constant_op.constant([[1.0, 2.0], [3.0, 4.0]])).numpy()) def testRank(self): with self.test_scope(): self.assertEqual( 0, array_ops.rank(constant_op.constant(1.0)).numpy()) self.assertEqual( 1, array_ops.rank(constant_op.constant([1.0, 2.0, 3.0])).numpy()) self.assertEqual( 2, array_ops.rank( constant_op.constant([[1.0, 2.0], [3.0, 4.0]])).numpy()) def testAdam(self): with self.test_scope(): optimizer = adam.AdamOptimizer(0.1) x = resource_variable_ops.ResourceVariable(10.0) with backprop.GradientTape() as tape: y = x * x dy_dx = tape.gradient(y, x) optimizer.apply_gradients([(dy_dx, x)]) self.assertAlmostEqual(9.9, x.numpy(), places=3) def testAdamSparse(self): with ops.device('/cpu:0'): # Create 2-D embedding for 3 objects on CPU because sparse/sliced updates # are not implemented on TPU. embedding_matrix = resource_variable_ops.ResourceVariable( array_ops.ones([3, 2])) with self.test_scope(): with backprop.GradientTape() as tape: embedding = embedding_ops.embedding_lookup(embedding_matrix, [1]) y = math_ops.reduce_sum(embedding) dy_dx = tape.gradient(y, embedding_matrix) self.assertIsInstance(dy_dx, ops.IndexedSlices) optimizer = adam.AdamOptimizer(0.1) # The gradient application operations will run on CPU because optimizer # updates are always collocated with the variable. optimizer.apply_gradients([(dy_dx, embedding_matrix)]) # This assign_add will run on CPU because when an input to an # operation is a resource, this operation is placed on the resource's # device by the eager runtime. embedding_matrix.assign_add(array_ops.ones([3, 2])) self.assertAllClose([[2.0, 2.0], [1.9, 1.9], [2.0, 2.0]], embedding_matrix.numpy()) class EagerFunctionTest(xla_test.XLATestCase): def testBasic(self): with self.test_scope(): matmul = function.defun(math_ops.matmul) t = constant_op.constant([[1.0, 2.0], [3.0, 4.0]]) sq = matmul(t, t, transpose_a=True) self.assertAllEqual(sq.numpy().reshape(-1), [10, 14, 14, 20]) def testConv(self): if 'GPU' in self.device: # TODO(b/32333178) self.skipTest('Current implementation of RandomStandardNormal kernel ' 'is very slow on GPU, and has been blacklisted.') with self.test_scope(): data_format = 'channels_last' conv = convolutional.Conv2D( filters=1, kernel_size=2, padding='VALID', data_format=data_format, activation=nn_ops.relu, kernel_initializer=init_ops.ones_initializer(), bias_initializer=init_ops.zeros_initializer()) pool = pooling.MaxPooling2D(2, 2, data_format=data_format) def model(x): x = conv(x) return pool(x) model = function.defun(model) x = array_ops.ones([1, 4, 4, 1]) y = model(x) self.assertAllEqual(y.numpy(), [[[[4.]]]]) def testReadVariable(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(1.0) @function.defun def f(): return v.read_value() var = f() self.assertEqual(1.0, var.numpy()) def testUpdateVariable(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(1.0) def f(v): v.assign_add(1.0) return v f = function.defun(f) var = f(v) self.assertEqual(2.0, var.numpy()) def testReturnResourceHandle(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable([[1.0, 2.0], [3.0, 4.0]]) def f(v): return v.handle f = function.defun(f) handle = f(v) self.assertAllEqual(v.numpy(), resource_variable_ops.read_variable_op( handle, dtypes.float32).numpy()) def testReturnMultipleResourceHandles(self): with self.test_scope(): v1 = resource_variable_ops.ResourceVariable(1.25) v2 = resource_variable_ops.ResourceVariable(2.0) def f(v): return v.handle, 3.0 * v, v2.handle, v + v2 f = function.defun(f) v1_handle, v1_times_3, v2_handle, variable_sum = f(v1) self.assertAllEqual(v1.numpy(), resource_variable_ops.read_variable_op( v1_handle, dtypes.float32).numpy()) self.assertEqual(3.75, v1_times_3.numpy()) self.assertAllEqual(v2.numpy(), resource_variable_ops.read_variable_op( v2_handle, dtypes.float32).numpy()) self.assertEqual(3.25, variable_sum.numpy()) def testAllArgumentKinds(self): """Test a complex function that takes different argument kinds. tf2xla machinery that translates, compiles, and runs defuns classifies arguments into: compile-time constants, regular tensors, and resources. This test creates a function with a mix of all these kinds. Moreover, the order of function arguments is intentionally mixed up. This also tests the case when the same argument is a compile-time constant as well as used in an operation that normally expects its inputs to be in device memory - addition in this case. """ with self.test_scope(): def foo(c1, r1, v1, c2, v2, r2): # c1 and c2 are compile-time constants # r1 and r2 are regular tensors # v1 and v2 are resource variables a = c1 + r1 b = math_ops.cast(c2, dtypes.float32) + v2 c = array_ops.slice(v1, c1, c2) d = r2 * v2 return a, b, c, d foo = function.defun(foo) c1 = [0, 0] c2 = array_ops.ones([2], dtype=dtypes.int32) r1 = array_ops.ones([2]) r2 = [[2., 2.], [3., 3.]] v1 = resource_variable_ops.ResourceVariable([[1., 2.], [3., 4.]]) v2 = resource_variable_ops.ResourceVariable([[10., 20.], [30., 40.]]) a, b, c, d = foo(c1, r1, v1, c2, v2, r2) self.assertAllEqual([1, 1], a.numpy()) self.assertAllEqual([[11., 21.], [31., 41.]], b.numpy()) self.assertAllEqual([[1.]], c.numpy()) self.assertAllEqual([[20., 40.], [90., 120.]], d.numpy()) def testDefunInGradientTape(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) @function.defun def f(x): x = v0 * v0 * x return x x = constant_op.constant(3.0) with backprop.GradientTape() as tape: y = f(x) dy = tape.gradient(y, v0) self.assertEqual(75, y.numpy()) self.assertEqual(30, dy.numpy()) def testGradientTapeInDefun(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) @function.defun def f(): x = constant_op.constant(1.0) with backprop.GradientTape() as tape: y = v0 * x dy = tape.gradient(y, v0) return dy dy = f() self.assertEqual(1.0, dy.numpy()) def testSliceInDefun(self): with self.test_scope(): @function.defun def f(x, y): return x[0::2, y:, ...] x = array_ops.ones([2, 3, 4]) y = array_ops.ones([], dtype=dtypes.int32) with backprop.GradientTape() as tape: tape.watch(x) tape.watch(y) z = f(x, y) dz = tape.gradient(z, x) self.assertAllEqual(np.ones([1, 2, 4]), z.numpy()) self.assertAllEqual((2, 3, 4), dz.shape.as_list()) def testNestedDefun(self): with self.test_scope(): @function.defun def times_two(x): return 2 * x @function.defun def two_x_plus_1(x): return times_two(x) + 1 x = constant_op.constant([2, 3, 4]) y = two_x_plus_1(x) self.assertAllEqual([5, 7, 9], y.numpy()) def testNestedDefunWithVariable(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) @function.defun def g(x): x = v0 * x return x @function.defun def f(x): x = g(v0 * x) return x x = constant_op.constant(3.0) y = f(x) self.assertEqual(75, y.numpy()) def testNestedDefunInGradientTape(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) @function.defun def g(x): x = v0 * x return x @function.defun def f(x): x = g(v0 * x) return x x = constant_op.constant(3.0) with backprop.GradientTape() as tape: y = f(x) dy = tape.gradient(y, v0) self.assertEqual(75, y.numpy()) self.assertEqual(30, dy.numpy()) def testNestedDefunInGradientTapeDifferentVars(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) v1 = resource_variable_ops.ResourceVariable(3.0) @function.defun def g(x): x = v1 * x return x @function.defun def f(x): x = g(v0 * x) return x x = constant_op.constant(3.0) with backprop.GradientTape(persistent=True) as tape: y = f(x) dy_v0 = tape.gradient(y, v0) dy_v1 = tape.gradient(y, v1) self.assertEqual(45, y.numpy()) self.assertEqual(9, dy_v0.numpy()) self.assertEqual(15, dy_v1.numpy()) class ExcessivePaddingTest(xla_test.XLATestCase): """Test that eager execution works with TPU flattened tensors. Tensors that would normally be excessively padded when written to TPU memory are reshaped to 1-D flat tensors. This test case verifies that such tensors work with eager execution. The flattening currently only happens on TPU, but tests should work fine with all backends as flattening is transparent. """ def testFromConstant(self): with self.test_scope(): # Create constant of shape [100, 2, 1]. This tensor would be # excessively padded on TPU. tensor = constant_op.constant(100 * [[[10.0], [2.0]]]) # Use reduce_sum since it requires correctly working with # a particular dimension. reduced = math_ops.reduce_sum(tensor, axis=1) self.assertAllEqual(100 * [[12.0]], reduced) def testFromOperation(self): with self.test_scope(): tensor = array_ops.ones([3, 100, 2, 2]) reduced = math_ops.reduce_sum(tensor, axis=[0, 2, 3]) self.assertAllEqual(100 * [12.0], reduced) def testAsFunctionInput(self): with self.test_scope(): @function.defun def f(x): return math_ops.reduce_sum(x, axis=2) tensor = constant_op.constant(100 * [[[10.0, 2.0]]]) reduced = f(tensor) self.assertAllEqual(100 * [[12.0]], reduced) def testAsFunctionOutput(self): with self.test_scope(): @function.defun def f(x): return x * constant_op.constant(100 * [[[10.0, 2.0]]]) y = f(3) reduced = math_ops.reduce_sum(y, axis=2) self.assertAllEqual(100 * [[36.0]], reduced) def multiple_tpus(): devices = context.context().devices() return len([d for d in devices if 'device:TPU:' in d]) > 1 class MultiDeviceTest(xla_test.XLATestCase): """Test running TPU computation on more than one core.""" def testBasic(self): if not multiple_tpus(): self.skipTest('MultiDeviceTest requires multiple TPU devices.') # Compute 10 on TPU core 0 with ops.device('device:TPU:0'): two = constant_op.constant(2) five = constant_op.constant(5) ten = two * five self.assertAllEqual(10, ten) # Compute 6 on TPU core 1 with ops.device('device:TPU:1'): two = constant_op.constant(2) three = constant_op.constant(3) six = two * three self.assertAllEqual(6, six) # Copy 10 and 6 to CPU and sum them self.assertAllEqual(16, ten + six) if __name__ == '__main__': ops.enable_eager_execution( config=config_pb2.ConfigProto(log_device_placement=True)) googletest.main()
mbareta/edx-platform-ft
refs/heads/open-release/eucalyptus.master
common/djangoapps/django_comment_common/migrations/0002_forumsconfig.py
24
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('django_comment_common', '0001_initial'), ] operations = [ migrations.CreateModel( name='ForumsConfig', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('change_date', models.DateTimeField(auto_now_add=True, verbose_name='Change date')), ('enabled', models.BooleanField(default=False, verbose_name='Enabled')), ('connection_timeout', models.FloatField(default=5.0)), ('changed_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, editable=False, to=settings.AUTH_USER_MODEL, null=True, verbose_name='Changed by')), ], options={ 'ordering': ('-change_date',), 'abstract': False, }, ), ]
stevenbrichards/boto
refs/heads/develop
tests/integration/s3/mock_storage_service.py
108
# Copyright 2010 Google Inc. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. """ Provides basic mocks of core storage service classes, for unit testing: ACL, Key, Bucket, Connection, and StorageUri. We implement a subset of the interfaces defined in the real boto classes, but don't handle most of the optional params (which we indicate with the constant "NOT_IMPL"). """ import copy import boto import base64 import re from hashlib import md5 from boto.utils import compute_md5 from boto.utils import find_matching_headers from boto.utils import merge_headers_by_name from boto.s3.prefix import Prefix from boto.compat import six NOT_IMPL = None class MockAcl(object): def __init__(self, parent=NOT_IMPL): pass def startElement(self, name, attrs, connection): pass def endElement(self, name, value, connection): pass def to_xml(self): return '<mock_ACL_XML/>' class MockKey(object): def __init__(self, bucket=None, name=None): self.bucket = bucket self.name = name self.data = None self.etag = None self.size = None self.closed = True self.content_encoding = None self.content_language = None self.content_type = None self.last_modified = 'Wed, 06 Oct 2010 05:11:54 GMT' self.BufferSize = 8192 def __repr__(self): if self.bucket: return '<MockKey: %s,%s>' % (self.bucket.name, self.name) else: return '<MockKey: %s>' % self.name def get_contents_as_string(self, headers=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, torrent=NOT_IMPL, version_id=NOT_IMPL): return self.data def get_contents_to_file(self, fp, headers=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, torrent=NOT_IMPL, version_id=NOT_IMPL, res_download_handler=NOT_IMPL): fp.write(self.data) def get_file(self, fp, headers=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, torrent=NOT_IMPL, version_id=NOT_IMPL, override_num_retries=NOT_IMPL): fp.write(self.data) def _handle_headers(self, headers): if not headers: return if find_matching_headers('Content-Encoding', headers): self.content_encoding = merge_headers_by_name('Content-Encoding', headers) if find_matching_headers('Content-Type', headers): self.content_type = merge_headers_by_name('Content-Type', headers) if find_matching_headers('Content-Language', headers): self.content_language = merge_headers_by_name('Content-Language', headers) # Simplistic partial implementation for headers: Just supports range GETs # of flavor 'Range: bytes=xyz-'. def open_read(self, headers=None, query_args=NOT_IMPL, override_num_retries=NOT_IMPL): if self.closed: self.read_pos = 0 self.closed = False if headers and 'Range' in headers: match = re.match('bytes=([0-9]+)-$', headers['Range']) if match: self.read_pos = int(match.group(1)) def close(self, fast=NOT_IMPL): self.closed = True def read(self, size=0): self.open_read() if size == 0: data = self.data[self.read_pos:] self.read_pos = self.size else: data = self.data[self.read_pos:self.read_pos+size] self.read_pos += size if not data: self.close() return data def set_contents_from_file(self, fp, headers=None, replace=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL, md5=NOT_IMPL, res_upload_handler=NOT_IMPL): self.data = fp.read() self.set_etag() self.size = len(self.data) self._handle_headers(headers) def set_contents_from_stream(self, fp, headers=None, replace=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL, reduced_redundancy=NOT_IMPL, query_args=NOT_IMPL, size=NOT_IMPL): self.data = '' chunk = fp.read(self.BufferSize) while chunk: self.data += chunk chunk = fp.read(self.BufferSize) self.set_etag() self.size = len(self.data) self._handle_headers(headers) def set_contents_from_string(self, s, headers=NOT_IMPL, replace=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL, md5=NOT_IMPL, reduced_redundancy=NOT_IMPL): self.data = copy.copy(s) self.set_etag() self.size = len(s) self._handle_headers(headers) def set_contents_from_filename(self, filename, headers=None, replace=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL, md5=NOT_IMPL, res_upload_handler=NOT_IMPL): fp = open(filename, 'rb') self.set_contents_from_file(fp, headers, replace, cb, num_cb, policy, md5, res_upload_handler) fp.close() def copy(self, dst_bucket_name, dst_key, metadata=NOT_IMPL, reduced_redundancy=NOT_IMPL, preserve_acl=NOT_IMPL): dst_bucket = self.bucket.connection.get_bucket(dst_bucket_name) return dst_bucket.copy_key(dst_key, self.bucket.name, self.name, metadata) @property def provider(self): provider = None if self.bucket and self.bucket.connection: provider = self.bucket.connection.provider return provider def set_etag(self): """ Set etag attribute by generating hex MD5 checksum on current contents of mock key. """ m = md5() if not isinstance(self.data, bytes): m.update(self.data.encode('utf-8')) else: m.update(self.data) hex_md5 = m.hexdigest() self.etag = hex_md5 def compute_md5(self, fp): """ :type fp: file :param fp: File pointer to the file to MD5 hash. The file pointer will be reset to the beginning of the file before the method returns. :rtype: tuple :return: A tuple containing the hex digest version of the MD5 hash as the first element and the base64 encoded version of the plain digest as the second element. """ tup = compute_md5(fp) # Returned values are MD5 hash, base64 encoded MD5 hash, and file size. # The internal implementation of compute_md5() needs to return the # file size but we don't want to return that value to the external # caller because it changes the class interface (i.e. it might # break some code) so we consume the third tuple value here and # return the remainder of the tuple to the caller, thereby preserving # the existing interface. self.size = tup[2] return tup[0:2] class MockBucket(object): def __init__(self, connection=None, name=None, key_class=NOT_IMPL): self.name = name self.keys = {} self.acls = {name: MockAcl()} # default object ACLs are one per bucket and not supported for keys self.def_acl = MockAcl() self.subresources = {} self.connection = connection self.logging = False def __repr__(self): return 'MockBucket: %s' % self.name def copy_key(self, new_key_name, src_bucket_name, src_key_name, metadata=NOT_IMPL, src_version_id=NOT_IMPL, storage_class=NOT_IMPL, preserve_acl=NOT_IMPL, encrypt_key=NOT_IMPL, headers=NOT_IMPL, query_args=NOT_IMPL): new_key = self.new_key(key_name=new_key_name) src_key = self.connection.get_bucket( src_bucket_name).get_key(src_key_name) new_key.data = copy.copy(src_key.data) new_key.size = len(new_key.data) return new_key def disable_logging(self): self.logging = False def enable_logging(self, target_bucket_prefix): self.logging = True def get_logging_config(self): return {"Logging": {}} def get_versioning_status(self, headers=NOT_IMPL): return False def get_acl(self, key_name='', headers=NOT_IMPL, version_id=NOT_IMPL): if key_name: # Return ACL for the key. return self.acls[key_name] else: # Return ACL for the bucket. return self.acls[self.name] def get_def_acl(self, key_name=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): # Return default ACL for the bucket. return self.def_acl def get_subresource(self, subresource, key_name=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): if subresource in self.subresources: return self.subresources[subresource] else: return '<Subresource/>' def new_key(self, key_name=None): mock_key = MockKey(self, key_name) self.keys[key_name] = mock_key self.acls[key_name] = MockAcl() return mock_key def delete_key(self, key_name, headers=NOT_IMPL, version_id=NOT_IMPL, mfa_token=NOT_IMPL): if key_name not in self.keys: raise boto.exception.StorageResponseError(404, 'Not Found') del self.keys[key_name] def get_all_keys(self, headers=NOT_IMPL): return six.itervalues(self.keys) def get_key(self, key_name, headers=NOT_IMPL, version_id=NOT_IMPL): # Emulate behavior of boto when get_key called with non-existent key. if key_name not in self.keys: return None return self.keys[key_name] def list(self, prefix='', delimiter='', marker=NOT_IMPL, headers=NOT_IMPL): prefix = prefix or '' # Turn None into '' for prefix match. # Return list instead of using a generator so we don't get # 'dictionary changed size during iteration' error when performing # deletions while iterating (e.g., during test cleanup). result = [] key_name_set = set() for k in six.itervalues(self.keys): if k.name.startswith(prefix): k_name_past_prefix = k.name[len(prefix):] if delimiter: pos = k_name_past_prefix.find(delimiter) else: pos = -1 if (pos != -1): key_or_prefix = Prefix( bucket=self, name=k.name[:len(prefix)+pos+1]) else: key_or_prefix = MockKey(bucket=self, name=k.name) if key_or_prefix.name not in key_name_set: key_name_set.add(key_or_prefix.name) result.append(key_or_prefix) return result def set_acl(self, acl_or_str, key_name='', headers=NOT_IMPL, version_id=NOT_IMPL): # We only handle setting ACL XML here; if you pass a canned ACL # the get_acl call will just return that string name. if key_name: # Set ACL for the key. self.acls[key_name] = MockAcl(acl_or_str) else: # Set ACL for the bucket. self.acls[self.name] = MockAcl(acl_or_str) def set_def_acl(self, acl_or_str, key_name=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): # We only handle setting ACL XML here; if you pass a canned ACL # the get_acl call will just return that string name. # Set default ACL for the bucket. self.def_acl = acl_or_str def set_subresource(self, subresource, value, key_name=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): self.subresources[subresource] = value class MockProvider(object): def __init__(self, provider): self.provider = provider def get_provider_name(self): return self.provider class MockConnection(object): def __init__(self, aws_access_key_id=NOT_IMPL, aws_secret_access_key=NOT_IMPL, is_secure=NOT_IMPL, port=NOT_IMPL, proxy=NOT_IMPL, proxy_port=NOT_IMPL, proxy_user=NOT_IMPL, proxy_pass=NOT_IMPL, host=NOT_IMPL, debug=NOT_IMPL, https_connection_factory=NOT_IMPL, calling_format=NOT_IMPL, path=NOT_IMPL, provider='s3', bucket_class=NOT_IMPL): self.buckets = {} self.provider = MockProvider(provider) def create_bucket(self, bucket_name, headers=NOT_IMPL, location=NOT_IMPL, policy=NOT_IMPL, storage_class=NOT_IMPL): if bucket_name in self.buckets: raise boto.exception.StorageCreateError( 409, 'BucketAlreadyOwnedByYou', "<Message>Your previous request to create the named bucket " "succeeded and you already own it.</Message>") mock_bucket = MockBucket(name=bucket_name, connection=self) self.buckets[bucket_name] = mock_bucket return mock_bucket def delete_bucket(self, bucket, headers=NOT_IMPL): if bucket not in self.buckets: raise boto.exception.StorageResponseError( 404, 'NoSuchBucket', '<Message>no such bucket</Message>') del self.buckets[bucket] def get_bucket(self, bucket_name, validate=NOT_IMPL, headers=NOT_IMPL): if bucket_name not in self.buckets: raise boto.exception.StorageResponseError(404, 'NoSuchBucket', 'Not Found') return self.buckets[bucket_name] def get_all_buckets(self, headers=NOT_IMPL): return six.itervalues(self.buckets) # We only mock a single provider/connection. mock_connection = MockConnection() class MockBucketStorageUri(object): delim = '/' def __init__(self, scheme, bucket_name=None, object_name=None, debug=NOT_IMPL, suppress_consec_slashes=NOT_IMPL, version_id=None, generation=None, is_latest=False): self.scheme = scheme self.bucket_name = bucket_name self.object_name = object_name self.suppress_consec_slashes = suppress_consec_slashes if self.bucket_name and self.object_name: self.uri = ('%s://%s/%s' % (self.scheme, self.bucket_name, self.object_name)) elif self.bucket_name: self.uri = ('%s://%s/' % (self.scheme, self.bucket_name)) else: self.uri = ('%s://' % self.scheme) self.version_id = version_id self.generation = generation and int(generation) self.is_version_specific = (bool(self.generation) or bool(self.version_id)) self.is_latest = is_latest if bucket_name and object_name: self.versionless_uri = '%s://%s/%s' % (scheme, bucket_name, object_name) def __repr__(self): """Returns string representation of URI.""" return self.uri def acl_class(self): return MockAcl def canned_acls(self): return boto.provider.Provider('aws').canned_acls def clone_replace_name(self, new_name): return self.__class__(self.scheme, self.bucket_name, new_name) def clone_replace_key(self, key): return self.__class__( key.provider.get_provider_name(), bucket_name=key.bucket.name, object_name=key.name, suppress_consec_slashes=self.suppress_consec_slashes, version_id=getattr(key, 'version_id', None), generation=getattr(key, 'generation', None), is_latest=getattr(key, 'is_latest', None)) def connect(self, access_key_id=NOT_IMPL, secret_access_key=NOT_IMPL): return mock_connection def create_bucket(self, headers=NOT_IMPL, location=NOT_IMPL, policy=NOT_IMPL, storage_class=NOT_IMPL): return self.connect().create_bucket(self.bucket_name) def delete_bucket(self, headers=NOT_IMPL): return self.connect().delete_bucket(self.bucket_name) def get_versioning_config(self, headers=NOT_IMPL): self.get_bucket().get_versioning_status(headers) def has_version(self): return (issubclass(type(self), MockBucketStorageUri) and ((self.version_id is not None) or (self.generation is not None))) def delete_key(self, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL, mfa_token=NOT_IMPL): self.get_bucket().delete_key(self.object_name) def disable_logging(self, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): self.get_bucket().disable_logging() def enable_logging(self, target_bucket, target_prefix, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): self.get_bucket().enable_logging(target_bucket) def get_logging_config(self, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): return self.get_bucket().get_logging_config() def equals(self, uri): return self.uri == uri.uri def get_acl(self, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): return self.get_bucket().get_acl(self.object_name) def get_def_acl(self, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): return self.get_bucket().get_def_acl(self.object_name) def get_subresource(self, subresource, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): return self.get_bucket().get_subresource(subresource, self.object_name) def get_all_buckets(self, headers=NOT_IMPL): return self.connect().get_all_buckets() def get_all_keys(self, validate=NOT_IMPL, headers=NOT_IMPL): return self.get_bucket().get_all_keys(self) def list_bucket(self, prefix='', delimiter='', headers=NOT_IMPL, all_versions=NOT_IMPL): return self.get_bucket().list(prefix=prefix, delimiter=delimiter) def get_bucket(self, validate=NOT_IMPL, headers=NOT_IMPL): return self.connect().get_bucket(self.bucket_name) def get_key(self, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): return self.get_bucket().get_key(self.object_name) def is_file_uri(self): return False def is_cloud_uri(self): return True def names_container(self): return bool(not self.object_name) def names_singleton(self): return bool(self.object_name) def names_directory(self): return False def names_provider(self): return bool(not self.bucket_name) def names_bucket(self): return self.names_container() def names_file(self): return False def names_object(self): return not self.names_container() def is_stream(self): return False def new_key(self, validate=NOT_IMPL, headers=NOT_IMPL): bucket = self.get_bucket() return bucket.new_key(self.object_name) def set_acl(self, acl_or_str, key_name='', validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): self.get_bucket().set_acl(acl_or_str, key_name) def set_def_acl(self, acl_or_str, key_name=NOT_IMPL, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): self.get_bucket().set_def_acl(acl_or_str) def set_subresource(self, subresource, value, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL): self.get_bucket().set_subresource(subresource, value, self.object_name) def copy_key(self, src_bucket_name, src_key_name, metadata=NOT_IMPL, src_version_id=NOT_IMPL, storage_class=NOT_IMPL, preserve_acl=NOT_IMPL, encrypt_key=NOT_IMPL, headers=NOT_IMPL, query_args=NOT_IMPL, src_generation=NOT_IMPL): dst_bucket = self.get_bucket() return dst_bucket.copy_key(new_key_name=self.object_name, src_bucket_name=src_bucket_name, src_key_name=src_key_name) def set_contents_from_string(self, s, headers=NOT_IMPL, replace=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL, md5=NOT_IMPL, reduced_redundancy=NOT_IMPL): key = self.new_key() key.set_contents_from_string(s) def set_contents_from_file(self, fp, headers=None, replace=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL, md5=NOT_IMPL, size=NOT_IMPL, rewind=NOT_IMPL, res_upload_handler=NOT_IMPL): key = self.new_key() return key.set_contents_from_file(fp, headers=headers) def set_contents_from_stream(self, fp, headers=NOT_IMPL, replace=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL, reduced_redundancy=NOT_IMPL, query_args=NOT_IMPL, size=NOT_IMPL): dst_key.set_contents_from_stream(fp) def get_contents_to_file(self, fp, headers=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, torrent=NOT_IMPL, version_id=NOT_IMPL, res_download_handler=NOT_IMPL, response_headers=NOT_IMPL): key = self.get_key() key.get_contents_to_file(fp) def get_contents_to_stream(self, fp, headers=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL, version_id=NOT_IMPL): key = self.get_key() return key.get_contents_to_file(fp)
coderfi/ansible-modules-extras
refs/heads/devel
packaging/portage.py
12
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Yap Sok Ann # Written by Yap Sok Ann <sokann@gmail.com> # Based on apt module written by Matthew Williams <matthew@flowroute.com> # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: portage short_description: Package manager for Gentoo description: - Manages Gentoo packages version_added: "1.6" options: package: description: - Package atom or set, e.g. C(sys-apps/foo) or C(>foo-2.13) or C(@world) required: false default: null state: description: - State of the package atom required: false default: "present" choices: [ "present", "installed", "emerged", "absent", "removed", "unmerged" ] update: description: - Update packages to the best version available (--update) required: false default: null choices: [ "yes" ] deep: description: - Consider the entire dependency tree of packages (--deep) required: false default: null choices: [ "yes" ] newuse: description: - Include installed packages where USE flags have changed (--newuse) required: false default: null choices: [ "yes" ] changed_use: description: - Include installed packages where USE flags have changed, except when - flags that the user has not enabled are added or removed - (--changed-use) required: false default: null choices: [ "yes" ] version_added: 1.8 oneshot: description: - Do not add the packages to the world file (--oneshot) required: false default: null choices: [ "yes" ] noreplace: description: - Do not re-emerge installed packages (--noreplace) required: false default: null choices: [ "yes" ] nodeps: description: - Only merge packages but not their dependencies (--nodeps) required: false default: null choices: [ "yes" ] onlydeps: description: - Only merge packages' dependencies but not the packages (--onlydeps) required: false default: null choices: [ "yes" ] depclean: description: - Remove packages not needed by explicitly merged packages (--depclean) - If no package is specified, clean up the world's dependencies - Otherwise, --depclean serves as a dependency aware version of --unmerge required: false default: null choices: [ "yes" ] quiet: description: - Run emerge in quiet mode (--quiet) required: false default: null choices: [ "yes" ] verbose: description: - Run emerge in verbose mode (--verbose) required: false default: null choices: [ "yes" ] sync: description: - Sync package repositories first - If yes, perform "emerge --sync" - If web, perform "emerge-webrsync" required: false default: null choices: [ "yes", "web" ] requirements: [ gentoolkit ] author: Yap Sok Ann notes: [] ''' EXAMPLES = ''' # Make sure package foo is installed - portage: package=foo state=present # Make sure package foo is not installed - portage: package=foo state=absent # Update package foo to the "best" version - portage: package=foo update=yes # Sync repositories and update world - portage: package=@world update=yes deep=yes sync=yes # Remove unneeded packages - portage: depclean=yes # Remove package foo if it is not explicitly needed - portage: package=foo state=absent depclean=yes ''' import os import pipes def query_package(module, package, action): if package.startswith('@'): return query_set(module, package, action) return query_atom(module, package, action) def query_atom(module, atom, action): cmd = '%s list %s' % (module.equery_path, atom) rc, out, err = module.run_command(cmd) return rc == 0 def query_set(module, set, action): system_sets = [ '@live-rebuild', '@module-rebuild', '@preserved-rebuild', '@security', '@selected', '@system', '@world', '@x11-module-rebuild', ] if set in system_sets: if action == 'unmerge': module.fail_json(msg='set %s cannot be removed' % set) return False world_sets_path = '/var/lib/portage/world_sets' if not os.path.exists(world_sets_path): return False cmd = 'grep %s %s' % (set, world_sets_path) rc, out, err = module.run_command(cmd) return rc == 0 def sync_repositories(module, webrsync=False): if module.check_mode: module.exit_json(msg='check mode not supported by sync') if webrsync: webrsync_path = module.get_bin_path('emerge-webrsync', required=True) cmd = '%s --quiet' % webrsync_path else: cmd = '%s --sync --quiet' % module.emerge_path rc, out, err = module.run_command(cmd) if rc != 0: module.fail_json(msg='could not sync package repositories') # Note: In the 3 functions below, equery is done one-by-one, but emerge is done # in one go. If that is not desirable, split the packages into multiple tasks # instead of joining them together with comma. def emerge_packages(module, packages): p = module.params if not (p['update'] or p['noreplace']): for package in packages: if not query_package(module, package, 'emerge'): break else: module.exit_json(changed=False, msg='Packages already present.') args = [] emerge_flags = { 'update': '--update', 'deep': '--deep', 'newuse': '--newuse', 'changed_use': '--changed-use', 'oneshot': '--oneshot', 'noreplace': '--noreplace', 'nodeps': '--nodeps', 'onlydeps': '--onlydeps', 'quiet': '--quiet', 'verbose': '--verbose', } for flag, arg in emerge_flags.iteritems(): if p[flag]: args.append(arg) cmd, (rc, out, err) = run_emerge(module, packages, *args) if rc != 0: module.fail_json( cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Packages not installed.', ) changed = True for line in out.splitlines(): if line.startswith('>>> Emerging (1 of'): break else: changed = False module.exit_json( changed=changed, cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Packages installed.', ) def unmerge_packages(module, packages): p = module.params for package in packages: if query_package(module, package, 'unmerge'): break else: module.exit_json(changed=False, msg='Packages already absent.') args = ['--unmerge'] for flag in ['quiet', 'verbose']: if p[flag]: args.append('--%s' % flag) cmd, (rc, out, err) = run_emerge(module, packages, *args) if rc != 0: module.fail_json( cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Packages not removed.', ) module.exit_json( changed=True, cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Packages removed.', ) def cleanup_packages(module, packages): p = module.params if packages: for package in packages: if query_package(module, package, 'unmerge'): break else: module.exit_json(changed=False, msg='Packages already absent.') args = ['--depclean'] for flag in ['quiet', 'verbose']: if p[flag]: args.append('--%s' % flag) cmd, (rc, out, err) = run_emerge(module, packages, *args) if rc != 0: module.fail_json(cmd=cmd, rc=rc, stdout=out, stderr=err) removed = 0 for line in out.splitlines(): if not line.startswith('Number removed:'): continue parts = line.split(':') removed = int(parts[1].strip()) changed = removed > 0 module.exit_json( changed=changed, cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Depclean completed.', ) def run_emerge(module, packages, *args): args = list(args) if module.check_mode: args.append('--pretend') cmd = [module.emerge_path] + args + packages return cmd, module.run_command(cmd) portage_present_states = ['present', 'emerged', 'installed'] portage_absent_states = ['absent', 'unmerged', 'removed'] def main(): module = AnsibleModule( argument_spec=dict( package=dict(default=None, aliases=['name']), state=dict( default=portage_present_states[0], choices=portage_present_states + portage_absent_states, ), update=dict(default=None, choices=['yes']), deep=dict(default=None, choices=['yes']), newuse=dict(default=None, choices=['yes']), changed_use=dict(default=None, choices=['yes']), oneshot=dict(default=None, choices=['yes']), noreplace=dict(default=None, choices=['yes']), nodeps=dict(default=None, choices=['yes']), onlydeps=dict(default=None, choices=['yes']), depclean=dict(default=None, choices=['yes']), quiet=dict(default=None, choices=['yes']), verbose=dict(default=None, choices=['yes']), sync=dict(default=None, choices=['yes', 'web']), ), required_one_of=[['package', 'sync', 'depclean']], mutually_exclusive=[['nodeps', 'onlydeps'], ['quiet', 'verbose']], supports_check_mode=True, ) module.emerge_path = module.get_bin_path('emerge', required=True) module.equery_path = module.get_bin_path('equery', required=True) p = module.params if p['sync']: sync_repositories(module, webrsync=(p['sync'] == 'web')) if not p['package']: module.exit_json(msg='Sync successfully finished.') packages = p['package'].split(',') if p['package'] else [] if p['depclean']: if packages and p['state'] not in portage_absent_states: module.fail_json( msg='Depclean can only be used with package when the state is ' 'one of: %s' % portage_absent_states, ) cleanup_packages(module, packages) elif p['state'] in portage_present_states: emerge_packages(module, packages) elif p['state'] in portage_absent_states: unmerge_packages(module, packages) # import module snippets from ansible.module_utils.basic import * main()
DrDaveD/cvmfs
refs/heads/devel
cvmfs/shrinkwrap/scripts/docker_inject/docker_injector.py
2
# # This file is part of the CernVM File System. # from datetime import datetime, timezone from dxf import DXF, hash_file, hash_bytes from dxf.exceptions import DXFUnauthorizedError import json import subprocess import tarfile import tempfile from requests.exceptions import HTTPError import os import zlib def exec_bash(cmd): process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = process.communicate() return (output, error) class FatManifest: """ Class which represents a "fat" OCI image configuration manifest """ def __init__(self, manif): self.manif = json.loads(manif) def init_cvmfs_layer(self, tar_digest, gz_digest): """ Method which initializes the cvmfs injection capability by adding an empty /cvmfs layer to the image's fat manifest """ if self.manif["rootfs"]["type"] != "layers": raise ValueError("Cannot inject in rootfs of type " + self.manif["rootfs"]["type"]) self.manif["rootfs"]["diff_ids"].append(tar_digest) # Write history local_time = datetime.now(timezone.utc).astimezone() self.manif["history"].append({ "created":local_time.isoformat(), "created_by":"/bin/sh -c #(nop) ADD file:"+tar_digest+" in / ", "author":"cvmfs_shrinkwrap", "comment": "This change was executed through the CVMFS Shrinkwrap Docker Injector" }) # Setup labels if "Labels" not in self.manif["config"]: self.manif["config"]["Labels"] = {} self.manif["config"]["Labels"]["cvmfs_injection_tar"] = tar_digest self.manif["config"]["Labels"]["cvmfs_injection_gz"] = gz_digest if "container_config" in self.manif: if "Labels" not in self.manif["config"]: self.manif["container_config"]["Labels"] = {} self.manif["container_config"]["Labels"]["cvmfs_injection_tar"] = tar_digest self.manif["container_config"]["Labels"]["cvmfs_injection_gz"] = gz_digest def inject(self, tar_digest, gz_digest): """ Injects a new version of the layer by replacing the corresponding digests """ if not self.is_cvmfs_prepared(): raise ValueError("Cannot inject in unprepated image") old_tar_digest = self.manif["config"]["Labels"]["cvmfs_injection_tar"] self.manif["container_config"]["Labels"]["cvmfs_injection_tar"] = tar_digest self.manif["container_config"]["Labels"]["cvmfs_injection_gz"] = gz_digest self.manif["config"]["Labels"]["cvmfs_injection_tar"] = tar_digest self.manif["config"]["Labels"]["cvmfs_injection_gz"] = gz_digest found = False for i in range(len(self.manif["rootfs"]["diff_ids"])): if self.manif["rootfs"]["diff_ids"][i] == old_tar_digest: self.manif["rootfs"]["diff_ids"][i] = tar_digest found = True break if not found: raise ValueError("Image did not contain old cvmfs injection!") local_time = datetime.now(timezone.utc).astimezone() self.manif["history"].append({ "created":local_time.isoformat(), "created_by":"/bin/sh -c #(nop) UPDATE file: from "+old_tar_digest+" to "+tar_digest+" in / ", "author":"cvmfs_shrinkwrap", "comment": "This change was executed through the CVMFS Shrinkwrap Docker Injector", "empty_layer":True }) def is_cvmfs_prepared(self): """ Checks whether image is prepared for cvmfs injection """ return "cvmfs_injection_gz" in self.manif["config"]["Labels"]\ and "cvmfs_injection_tar" in self.manif["config"]["Labels"] def get_gz_digest(self): """ Retrieves the GZ digest necessary for layer downloading """ return self.manif["config"]["Labels"]["cvmfs_injection_gz"] def as_JSON(self): """ Retrieve JSON version of OCI manifest (for upload) """ res = json.dumps(self.manif) return res class ImageManifest: """ Class which represents the "slim" image manifest used by the OCI distribution spec """ def __init__(self, manif): self.manif = json.loads(manif) def get_fat_manif_digest(self): """ Method for retrieving the digest (content address) of the manifest. """ return self.manif['config']['digest'] def init_cvmfs_layer(self, layer_digest, layer_size, manifest_digest, manifest_size): """ Method which initializes the cvmfs injection capability by adding an empty /cvmfs layer to the image's slim manifest """ self.manif["layers"].append({ 'mediaType':'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size':layer_size, 'digest':layer_digest }) self.manif["config"]["size"] = manifest_size self.manif["config"]["digest"] = manifest_digest def inject(self ,old, new, layer_size, manifest_digest, manifest_size): """ Injects a new version of the layer by replacing the corresponding digest """ for i in range(len(self.manif["layers"])): if self.manif["layers"][i]["digest"] == old: self.manif["layers"][i]["digest"] = new self.manif["layers"][i]["size"] = layer_size self.manif["config"]["size"] = manifest_size self.manif["config"]["digest"] = manifest_digest def as_JSON(self): res = json.dumps(self.manif) return res class DockerInjector: """ The main class of the Docker injector which injects new versions of a layer into OCI images retrieved from an OCI compliant distribution API """ def __init__(self, host, repo, alias, user, pw): """ Initializes the injector by downloading both the slim and the fat image manifest """ def auth(dxf, response): dxf.authenticate(user, pw, response=response) self.dxfObject = DXF(host, repo, tlsverify=True, auth=auth) self.image_manifest = self._get_manifest(alias) self.fat_manifest = self._get_fat_manifest(self.image_manifest) def setup(self, push_alias): """ Sets an image up for layer injection """ tar_digest, gz_digest = self._build_init_tar() layer_size = self.dxfObject.blob_size(gz_digest) self.fat_manifest.init_cvmfs_layer(tar_digest, gz_digest) fat_man_json = self.fat_manifest.as_JSON() manifest_digest = hash_bytes(bytes(fat_man_json, 'utf-8')) self.dxfObject.push_blob(data=fat_man_json, digest=manifest_digest) manifest_size = self.dxfObject.blob_size(manifest_digest) self.image_manifest.init_cvmfs_layer(gz_digest, layer_size, manifest_digest, manifest_size) image_man_json = self.image_manifest.as_JSON() self.dxfObject.set_manifest(push_alias, image_man_json) def unpack(self, dest_dir): """ Unpacks the current version of a layer into the dest_dir directory in order to update it """ if not self.fat_manifest.is_cvmfs_prepared(): os.makedirs(dest_dir+"/cvmfs", exist_ok=True) return gz_digest = self.fat_manifest.get_gz_digest() # Write out tar file decompress_object = zlib.decompressobj(16+zlib.MAX_WBITS) try: chunk_it = self.dxfObject.pull_blob(gz_digest) except HTTPError as e: if e.response.status_code == 404: print("ERROR: The hash of the CVMFS layer must have changed.") print("This is a known issue. Please do not reupload images to other repositories after CVMFS injection!") else: raise e with tempfile.TemporaryFile() as tmp_file: for chunk in chunk_it: tmp_file.write(decompress_object.decompress(chunk)) tmp_file.write(decompress_object.flush()) tmp_file.seek(0) tar = tarfile.TarFile(fileobj=tmp_file) tar.extractall(dest_dir) tar.close() def update(self, src_dir, push_alias): """ Packs and uploads the contents of src_dir as a layer and injects the layer into the image. The new layer version is stored under the tag push_alias """ if not self.fat_manifest.is_cvmfs_prepared(): print("Preparing image for CVMFS injection...") self.setup(push_alias) with tempfile.NamedTemporaryFile(delete=False) as tmp_file: print("Bundling file into tar...") _, error = exec_bash("tar --xattrs -C "+src_dir+" -cvf "+tmp_file.name+" .") if error: raise RuntimeError("Failed to tar with error " + str(error)) tar_digest = hash_file(tmp_file.name) print("Bundling tar into gz...") gz_dest = tmp_file.name+".gz" _, error = exec_bash("gzip "+tmp_file.name) if error: raise RuntimeError("Failed to tar with error " + str(error)) print("Uploading...") gz_digest = self.dxfObject.push_blob(gz_dest) os.unlink(gz_dest) print("Refreshing manifests...") old_gz_digest = self.fat_manifest.get_gz_digest() layer_size = self.dxfObject.blob_size(gz_digest) self.fat_manifest.inject(tar_digest, gz_digest) fat_man_json = self.fat_manifest.as_JSON() manifest_digest = hash_bytes(bytes(fat_man_json, 'utf-8')) self.dxfObject.push_blob(data=fat_man_json, digest=manifest_digest) manifest_size = self.dxfObject.blob_size(manifest_digest) self.image_manifest.inject(old_gz_digest, gz_digest, layer_size, manifest_digest, manifest_size) image_man_json = self.image_manifest.as_JSON() self.dxfObject.set_manifest(push_alias, image_man_json) def _get_manifest(self, alias): return ImageManifest(self.dxfObject.get_manifest(alias)) def _get_fat_manifest(self, image_manifest): fat_manifest = "" (readIter, _) = self.dxfObject.pull_blob(self.image_manifest.get_fat_manif_digest(), size=True, chunk_size=4096) for chunk in readIter: fat_manifest += str(chunk)[2:-1] fat_manifest = fat_manifest.replace("\\\\","\\") return FatManifest(fat_manifest) def _build_init_tar(self): """ Builds an empty /cvmfs tar and uploads it to the registry :rtype: tuple :returns: Tuple containing the tar digest and gz digest """ ident = self.image_manifest.get_fat_manif_digest()[5:15] tmp_name = "/tmp/injector-"+ident os.makedirs(tmp_name+"/cvmfs", exist_ok=True) tar_dest = "/tmp/"+ident+".tar" _, error = exec_bash("tar --xattrs -C "+tmp_name+" -cvf "+tar_dest+" .") if error: print("Failed to tar with error " + str(error)) return tar_digest = hash_file(tar_dest) _, error = exec_bash("gzip -n "+tar_dest) if error: print("Failed to tar with error " + str(error)) return gz_dest = tar_dest+".gz" gzip_digest = self.dxfObject.push_blob(tar_dest+".gz") # Cleanup os.rmdir(tmp_name+"/cvmfs") os.rmdir(tmp_name) os.unlink(gz_dest) return (tar_digest, gzip_digest)
so3500/volttron-kafka
refs/heads/master
Test/pub_server.py
1
import zmq import random import sys import time port = '5556' if len(sys.argv) > 1: port = sys.argv[1] int(port) context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind('tcp://*:%s' % port) new_value = 0 write_topic = "fake-campus/fake-building/fake-device/PowerState" # message_data = { # 'new_value': 0, # 'write_topic': "fake-campus/fake-building/fake-device/temperature" # } message_data = '{},{}'.format(new_value, write_topic) while True: topic = random.randrange(9999, 10005) new_value = random.randrange(1, 215) - 80 message_data = '{} {}'.format(write_topic, new_value) # message_data['new_value'] = new_value print('{} {}'.format(topic, message_data)) socket.send('{} {}'.format(topic, message_data)) time.sleep(1)
notrinsa/DongerBot
refs/heads/master
config.default.py
1
#!/usr/bin/env python # server.address .port .pass .channel # IRC Address Configuration server = { 'address': 'irc.redditairfrance.fr', 'port': 6697, 'pass': None, 'channel': '#reddit' } donger_nick = "donger" donger_pass = "donger" hostnames = ["redd.it"] # MySQL database = { 'name': 'donger', 'user': 'donger', 'pass': 'donger' } # super_secret_command super_secret_command = "aha" # Youtube Key youtube_key = "" # File Info bot_path = "/path/to/the/bot" actions_file = bot_path + "liste.json" stopwords_file = bot_path + "stopwords-fr.txt" rehost = { 'folder': '/path/where/to/rehost/images', 'url': 'url to link', 'domains': ["usercontent\.irccloud-cdn\.com/", "i\.imgur\.com/", "i\.redd\.it/"] }
NEricN/RobotCSimulator
refs/heads/master
Python/App/Lib/encodings/shift_jis.py
816
# # shift_jis.py: Python Unicode Codec for SHIFT_JIS # # Written by Hye-Shik Chang <perky@FreeBSD.org> # import _codecs_jp, codecs import _multibytecodec as mbc codec = _codecs_jp.getcodec('shift_jis') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): codec = codec class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): codec = codec class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): codec = codec class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): codec = codec def getregentry(): return codecs.CodecInfo( name='shift_jis', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
bala4901/odoo
refs/heads/master
addons/website_forum_doc/models/documentation.py
52
# -*- coding: utf-8 -*- import openerp from openerp.osv import osv, fields class Documentation(osv.Model): _name = 'forum.documentation.toc' _description = 'Documentation ToC' _inherit = ['website.seo.metadata'] _order = "parent_left" _parent_order = "sequence, name" _parent_store = True def name_get(self, cr, uid, ids, context=None): if isinstance(ids, (list, tuple)) and not len(ids): return [] if isinstance(ids, (long, int)): ids = [ids] reads = self.read(cr, uid, ids, ['name','parent_id'], context=context) res = [] for record in reads: name = record['name'] if record['parent_id']: name = record['parent_id'][1]+' / '+name res.append((record['id'], name)) return res def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None): res = self.name_get(cr, uid, ids, context=context) return dict(res) _columns = { 'sequence': fields.integer('Sequence'), 'display_name': fields.function(_name_get_fnc, type="char", string='Full Name'), 'name': fields.char('Name', required=True, translate=True), 'introduction': fields.html('Introduction', translate=True), 'parent_id': fields.many2one('forum.documentation.toc', 'Parent Table Of Content', ondelete='cascade'), 'child_ids': fields.one2many('forum.documentation.toc', 'parent_id', 'Children Table Of Content'), 'parent_left': fields.integer('Left Parent', select=True), 'parent_right': fields.integer('Right Parent', select=True), 'post_ids': fields.one2many('forum.post', 'documentation_toc_id', 'Posts'), 'forum_id': fields.many2one('forum.forum', 'Forum', required=True), } _constraints = [ (osv.osv._check_recursion, 'Error ! You cannot create recursive categories.', ['parent_id']) ] class DocumentationStage(osv.Model): _name = 'forum.documentation.stage' _description = 'Post Stage' _order = 'sequence' _columns = { 'sequence': fields.integer('Sequence'), 'name': fields.char('Stage Name', required=True, translate=True), } class Post(osv.Model): _inherit = 'forum.post' _columns = { 'documentation_toc_id': fields.many2one('forum.documentation.toc', 'Documentation ToC', ondelete='set null'), 'documentation_stage_id': fields.many2one('forum.documentation.stage', 'Documentation Stage'), 'color': fields.integer('Color Index') } def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None): stage_obj = self.pool.get('forum.documentation.stage') stage_ids = stage_obj.search(cr, uid, [], context=context) result = stage_obj.name_get(cr, uid, stage_ids, context=context) return result, {} _group_by_full = { 'documentation_stage_id': _read_group_stage_ids, }
chris-wood/SCoNet
refs/heads/master
ns-3-dev/src/network/bindings/modulegen__gcc_LP64.py
14
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']) ## 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') ## 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') ## 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']) ## 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']) ## 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 [enumeration] module.add_enum('', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO', 'DLT_IEEE802_15_4'], outer_class=root_module['ns3::PcapHelper']) ## 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-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', 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') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', 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::Queue [class] module.add_class('Queue', 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']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader [class] module.add_class('RadiotapHeader', 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']) ## 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']) ## 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', 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']) ## red-queue.h (module 'network'): ns3::RedQueue::Stats [struct] module.add_class('Stats', outer_class=root_module['ns3::RedQueue']) ## 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, 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::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', 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::SocketAddressTag [class] module.add_class('SocketAddressTag', parent=root_module['ns3::Tag']) ## 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::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']) ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue [class] module.add_class('DropTailQueue', 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', 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']) ## 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-factory.h (module 'network'): ns3::PacketSocketFactory [class] module.add_class('PacketSocketFactory', parent=root_module['ns3::SocketFactory']) ## 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']) ## 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::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']) ## 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']) 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') 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'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 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_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_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_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_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_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_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_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__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_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__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_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_Ns3PacketSocketFactory_methods(root_module, root_module['ns3::PacketSocketFactory']) 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_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_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_output_stream_operator() cls.add_binary_comparison_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'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_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'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateTxTime', 'double', [param('uint32_t', 'bytes')], is_const=True) ## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function] cls.add_method('GetBitRate', 'uint64_t', [], is_const=True) return def register_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_output_stream_operator() cls.add_binary_comparison_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_output_stream_operator() cls.add_binary_comparison_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_output_stream_operator() cls.add_binary_comparison_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_output_stream_operator() cls.add_binary_comparison_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_output_stream_operator() cls.add_binary_comparison_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_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_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 [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_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 snapLen=ns3::PcapFile::SNAPLEN_DEFAULT) [member function] cls.add_method('Diff', 'bool', [param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint32_t &', 'sec'), param('uint32_t &', 'usec'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT')], is_static=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file.h (module 'network'): bool ns3::PcapFile::GetSwapMode() [member function] cls.add_method('GetSwapMode', 'bool', []) ## pcap-file.h (module 'network'): int32_t ns3::PcapFile::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Init(uint32_t dataLinkType, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT, int32_t timeZoneCorrection=ns3::PcapFile::ZONE_DEFAULT, bool swapMode=false) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT'), param('int32_t', 'timeZoneCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT'), param('bool', 'swapMode', default_value='false')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Read(uint8_t * const data, uint32_t maxBytes, uint32_t & tsSec, uint32_t & tsUsec, uint32_t & inclLen, uint32_t & origLen, uint32_t & readLen) [member function] cls.add_method('Read', 'void', [param('uint8_t * const', 'data'), param('uint32_t', 'maxBytes'), param('uint32_t &', 'tsSec'), param('uint32_t &', 'tsUsec'), param('uint32_t &', 'inclLen'), param('uint32_t &', 'origLen'), param('uint32_t &', 'readLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, uint8_t const * const data, uint32_t totalLen) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('uint8_t const * const', 'data'), param('uint32_t', 'totalLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Ptr<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 & 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 &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): ns3::PcapFile::SNAPLEN_DEFAULT [variable] cls.add_static_attribute('SNAPLEN_DEFAULT', 'uint32_t const', is_const=True) ## pcap-file.h (module 'network'): ns3::PcapFile::ZONE_DEFAULT [variable] cls.add_static_attribute('ZONE_DEFAULT', 'int32_t const', is_const=True) return def register_Ns3PcapHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper(ns3::PcapHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::PcapFileWrapper> ns3::PcapHelper::CreateFile(std::string filename, std::_Ios_Openmode filemode, uint32_t dataLinkType, uint32_t snapLen=65535, int32_t tzCorrection=0) [member function] cls.add_method('CreateFile', 'ns3::Ptr< ns3::PcapFileWrapper >', [param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode'), param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='65535'), param('int32_t', 'tzCorrection', default_value='0')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3PcapHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function] cls.add_method('EnablePcapAll', 'void', [param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_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_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')], is_static=True) return def register_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_output_stream_operator() cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_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_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_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 & header, ns3::Ptr<ns3::Packet const> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')]) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) return def register_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'): 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::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'): 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::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::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')]) 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_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__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_output_stream_operator() 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_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_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'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3ConstantRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function] cls.add_method('GetConstant', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function] cls.add_method('GetValue', 'double', [param('double', 'constant')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'constant')]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_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'): 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'): 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() [member function] cls.add_method('GetMode', 'ns3::Queue::QueueMode', []) ## 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 arg0, double arg1, double arg2, double arg3, double arg4) [member function] cls.add_method('Interpolate', 'double', [param('double', 'arg0'), param('double', 'arg1'), param('double', 'arg2'), param('double', 'arg3'), param('double', 'arg4')], visibility='private', is_virtual=True) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function] cls.add_method('Validate', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_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 v, std::string name) [member function] cls.add_method('Add', 'void', [param('int', 'v'), param('std::string', 'name')]) ## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int v, std::string name) [member function] cls.add_method('AddDefault', 'void', [param('int', 'v'), 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 v) [constructor] cls.add_constructor([param('int', 'v')]) ## 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 v) [member function] cls.add_method('Set', 'void', [param('int', 'v')]) 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__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'): 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_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'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) return def register_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'): 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_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_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_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_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'): 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) 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'): 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::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_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_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'): 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'): 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 ## 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_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_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()