diff --git "a/codeparrot-valid_1037.txt" "b/codeparrot-valid_1037.txt" new file mode 100644--- /dev/null +++ "b/codeparrot-valid_1037.txt" @@ -0,0 +1,10000 @@ + 'evaluate_perfect_model_once') + + # Train a Model to completion: + self._train_model(checkpoint_dir, num_steps=300) + + # Run + inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) + labels = constant_op.constant(self._labels, dtype=dtypes.float32) + logits = logistic_classifier(inputs) + predictions = math_ops.round(logits) + + accuracy, update_op = metrics.accuracy( + predictions=predictions, labels=labels) + + checkpoint_path = evaluation.wait_for_new_checkpoint(checkpoint_dir) + + final_ops_values = evaluation.evaluate_once( + checkpoint_path=checkpoint_path, + eval_ops=update_op, + final_ops={'accuracy': accuracy}, + hooks=[ + evaluation.StopAfterNEvalsHook(1), + ]) + self.assertTrue(final_ops_values['accuracy'] > .99) + + def testEvalOpAndFinalOp(self): + checkpoint_dir = os.path.join(self.get_temp_dir(), 'eval_ops_and_final_ops') + + # Train a model for a single step to get a checkpoint. + self._train_model(checkpoint_dir, num_steps=1) + checkpoint_path = evaluation.wait_for_new_checkpoint(checkpoint_dir) + + # Create the model so we have something to restore. + inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) + logistic_classifier(inputs) + + num_evals = 5 + final_increment = 9.0 + + my_var = variables.local_variable(0.0, name='MyVar') + eval_ops = state_ops.assign_add(my_var, 1.0) + final_ops = array_ops.identity(my_var) + final_increment + + final_ops_values = evaluation.evaluate_once( + checkpoint_path=checkpoint_path, + eval_ops=eval_ops, + final_ops={'value': final_ops}, + hooks=[ + evaluation.StopAfterNEvalsHook(num_evals), + ]) + self.assertEqual(final_ops_values['value'], num_evals + final_increment) + + def testOnlyFinalOp(self): + checkpoint_dir = os.path.join(self.get_temp_dir(), 'only_final_ops') + + # Train a model for a single step to get a checkpoint. + self._train_model(checkpoint_dir, num_steps=1) + checkpoint_path = evaluation.wait_for_new_checkpoint(checkpoint_dir) + + # Create the model so we have something to restore. + inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) + logistic_classifier(inputs) + + final_increment = 9.0 + + my_var = variables.local_variable(0.0, name='MyVar') + final_ops = array_ops.identity(my_var) + final_increment + + final_ops_values = evaluation.evaluate_once( + checkpoint_path=checkpoint_path, final_ops={'value': final_ops}) + self.assertEqual(final_ops_values['value'], final_increment) + + +class EvaluateRepeatedlyTest(test.TestCase): + + def setUp(self): + super(EvaluateRepeatedlyTest, self).setUp() + + # Create an easy training set: + np.random.seed(0) + + self._inputs = np.zeros((16, 4)) + self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) + + for i in range(16): + j = int(2 * self._labels[i] + np.random.randint(0, 2)) + self._inputs[i, j] = 1 + + def _train_model(self, checkpoint_dir, num_steps): + """Trains a simple classification model. + + Note that the data has been configured such that after around 300 steps, + the model has memorized the dataset (e.g. we can expect %100 accuracy). + + Args: + checkpoint_dir: The directory where the checkpoint is written to. + num_steps: The number of steps to train for. + """ + with ops.Graph().as_default(): + random_seed.set_random_seed(0) + tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) + tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) + + tf_predictions = logistic_classifier(tf_inputs) + loss = loss_ops.log_loss(tf_predictions, tf_labels) + + optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) + train_op = training.create_train_op(loss, optimizer) + + loss = training.train( + train_op, + checkpoint_dir, + hooks=[basic_session_run_hooks.StopAtStepHook(num_steps)]) + + def testEvaluatePerfectModel(self): + checkpoint_dir = os.path.join(self.get_temp_dir(), + 'evaluate_perfect_model_repeated') + + # Train a Model to completion: + self._train_model(checkpoint_dir, num_steps=300) + + # Run + inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) + labels = constant_op.constant(self._labels, dtype=dtypes.float32) + logits = logistic_classifier(inputs) + predictions = math_ops.round(logits) + + accuracy, update_op = metrics.accuracy( + predictions=predictions, labels=labels) + + final_values = evaluation.evaluate_repeatedly( + checkpoint_dir=checkpoint_dir, + eval_ops=update_op, + final_ops={'accuracy': accuracy}, + hooks=[ + evaluation.StopAfterNEvalsHook(1), + ], + max_number_of_evaluations=1) + self.assertTrue(final_values['accuracy'] > .99) + + def testEvaluationLoopTimeout(self): + checkpoint_dir = os.path.join(self.get_temp_dir(), + 'evaluation_loop_timeout') + if not gfile.Exists(checkpoint_dir): + gfile.MakeDirs(checkpoint_dir) + + # We need a variable that the saver will try to restore. + variables.get_or_create_global_step() + + # Run with placeholders. If we actually try to evaluate this, we'd fail + # since we're not using a feed_dict. + cant_run_op = array_ops.placeholder(dtype=dtypes.float32) + + start = time.time() + final_values = evaluation.evaluate_repeatedly( + checkpoint_dir=checkpoint_dir, + eval_ops=cant_run_op, + hooks=[evaluation.StopAfterNEvalsHook(10)], + timeout=6) + end = time.time() + self.assertFalse(final_values) + + # Assert that we've waited for the duration of the timeout (minus the sleep + # time). + self.assertGreater(end - start, 5.0) + + # Then the timeout kicked in and stops the loop. + self.assertLess(end - start, 7) + + def testEvaluationLoopTimeoutWithTimeoutFn(self): + checkpoint_dir = os.path.join(self.get_temp_dir(), + 'evaluation_loop_timeout_with_timeout_fn') + + # Train a Model to completion: + self._train_model(checkpoint_dir, num_steps=300) + + # Run + inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) + labels = constant_op.constant(self._labels, dtype=dtypes.float32) + logits = logistic_classifier(inputs) + predictions = math_ops.round(logits) + + accuracy, update_op = metrics.accuracy( + predictions=predictions, labels=labels) + + timeout_fn_calls = [0] + def timeout_fn(): + timeout_fn_calls[0] += 1 + return timeout_fn_calls[0] > 3 + + final_values = evaluation.evaluate_repeatedly( + checkpoint_dir=checkpoint_dir, + eval_ops=update_op, + final_ops={'accuracy': accuracy}, + hooks=[ + evaluation.StopAfterNEvalsHook(1), + ], + eval_interval_secs=1, + max_number_of_evaluations=2, + timeout=0.1, + timeout_fn=timeout_fn) + # We should have evaluated once. + self.assertTrue(final_values['accuracy'] > .99) + # And called 4 times the timeout fn + self.assertEqual(4, timeout_fn_calls[0]) + + def testEvaluateWithEvalFeedDict(self): + # Create a checkpoint. + checkpoint_dir = os.path.join(self.get_temp_dir(), + 'evaluate_with_eval_feed_dict') + self._train_model(checkpoint_dir, num_steps=1) + + # We need a variable that the saver will try to restore. + variables.get_or_create_global_step() + + # Create a variable and an eval op that increments it with a placeholder. + my_var = variables.local_variable(0.0, name='my_var') + increment = array_ops.placeholder(dtype=dtypes.float32) + eval_ops = state_ops.assign_add(my_var, increment) + + increment_value = 3 + num_evals = 5 + expected_value = increment_value * num_evals + final_values = evaluation.evaluate_repeatedly( + checkpoint_dir=checkpoint_dir, + eval_ops=eval_ops, + feed_dict={increment: 3}, + final_ops={'my_var': array_ops.identity(my_var)}, + hooks=[ + evaluation.StopAfterNEvalsHook(num_evals), + ], + max_number_of_evaluations=1) + self.assertEqual(final_values['my_var'], expected_value) + + def _create_names_to_metrics(self, predictions, labels): + accuracy0, update_op0 = metrics.accuracy(labels, predictions) + accuracy1, update_op1 = metrics.accuracy(labels, predictions + 1) + + names_to_values = {'Accuracy': accuracy0, 'Another_accuracy': accuracy1} + names_to_updates = {'Accuracy': update_op0, 'Another_accuracy': update_op1} + return names_to_values, names_to_updates + + def _verify_events(self, output_dir, names_to_values): + """Verifies that the given `names_to_values` are found in the summaries. + + Also checks that a GraphDef was written out to the events file. + + Args: + output_dir: An existing directory where summaries are found. + names_to_values: A dictionary of strings to values. + """ + # Check that the results were saved. The events file may have additional + # entries, e.g. the event version stamp, so have to parse things a bit. + output_filepath = glob.glob(os.path.join(output_dir, '*')) + self.assertEqual(len(output_filepath), 1) + + events = summary_iterator.summary_iterator(output_filepath[0]) + summaries = [] + graph_def = None + for event in events: + if event.summary.value: + summaries.append(event.summary) + elif event.graph_def: + graph_def = event.graph_def + values = [] + for summary in summaries: + for value in summary.value: + values.append(value) + saved_results = {v.tag: v.simple_value for v in values} + for name in names_to_values: + self.assertAlmostEqual(names_to_values[name], saved_results[name], 5) + self.assertIsNotNone(graph_def) + + def testSummariesAreFlushedToDisk(self): + checkpoint_dir = os.path.join(self.get_temp_dir(), 'summaries_are_flushed') + logdir = os.path.join(self.get_temp_dir(), 'summaries_are_flushed_eval') + if gfile.Exists(logdir): + gfile.DeleteRecursively(logdir) + + # Train a Model to completion: + self._train_model(checkpoint_dir, num_steps=300) + + # Create the model (which can be restored). + inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) + logistic_classifier(inputs) + + names_to_values = {'bread': 3.4, 'cheese': 4.5, 'tomato': 2.0} + + for k in names_to_values: + v = names_to_values[k] + summary_lib.scalar(k, v) + + evaluation.evaluate_repeatedly( + checkpoint_dir=checkpoint_dir, + hooks=[ + evaluation.SummaryAtEndHook(log_dir=logdir), + ], + max_number_of_evaluations=1) + + self._verify_events(logdir, names_to_values) + + def testSummaryAtEndHookWithoutSummaries(self): + logdir = os.path.join(self.get_temp_dir(), + 'summary_at_end_hook_without_summaires') + if gfile.Exists(logdir): + gfile.DeleteRecursively(logdir) + + with ops.Graph().as_default(): + # Purposefully don't add any summaries. The hook will just dump the + # GraphDef event. + hook = evaluation.SummaryAtEndHook(log_dir=logdir) + hook.begin() + with self.cached_session() as session: + hook.after_create_session(session, None) + hook.end(session) + self._verify_events(logdir, {}) + + +if __name__ == '__main__': + test.main() + +"""SCons.Tool.dvi + +Common DVI Builder definition for various other Tool modules that use it. + +""" + +# +# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# + +__revision__ = "src/engine/SCons/Tool/dvi.py 5134 2010/08/16 23:02:40 bdeegan" + +import SCons.Builder +import SCons.Tool + +DVIBuilder = None + +def generate(env): + try: + env['BUILDERS']['DVI'] + except KeyError: + global DVIBuilder + + if DVIBuilder is None: + # The suffix is hard-coded to '.dvi', not configurable via a + # construction variable like $DVISUFFIX, because the output + # file name is hard-coded within TeX. + DVIBuilder = SCons.Builder.Builder(action = {}, + source_scanner = SCons.Tool.LaTeXScanner, + suffix = '.dvi', + emitter = {}, + source_ext_match = None) + + env['BUILDERS']['DVI'] = DVIBuilder + +def exists(env): + # This only puts a skeleton Builder in place, so if someone + # references this Tool directly, it's always "available." + return 1 + +# Local Variables: +# tab-width:4 +# indent-tabs-mode:nil +# End: +# vim: set expandtab tabstop=4 shiftwidth=4: + +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for tensorflow.python.client.Timeline.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import json + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import session +from tensorflow.python.client import timeline +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import test_util +from tensorflow.python.framework import ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test + + +class TimelineTest(test.TestCase): + + def _validateTrace(self, chrome_trace_format): + # Check that the supplied string is valid JSON. + trace = json.loads(chrome_trace_format) + # It should have a top-level key containing events. + self.assertTrue('traceEvents' in trace) + # Every event in the list should have a 'ph' field. + for event in trace['traceEvents']: + self.assertTrue('ph' in event) + + def testSimpleTimeline(self): + run_options = config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE) + run_metadata = config_pb2.RunMetadata() + + with ops.device('/cpu:0'): + with session.Session() as sess: + sess.run(constant_op.constant(1.0), + options=run_options, + run_metadata=run_metadata) + self.assertTrue(run_metadata.HasField('step_stats')) + tl = timeline.Timeline(run_metadata.step_stats) + ctf = tl.generate_chrome_trace_format() + self._validateTrace(ctf) + + def testTimelineCpu(self): + run_options = config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE) + run_metadata = config_pb2.RunMetadata() + + with self.test_session(use_gpu=False) as sess: + const1 = constant_op.constant(1.0, name='const1') + const2 = constant_op.constant(2.0, name='const2') + result = math_ops.add(const1, const2) + const1 * const2 + sess.run(result, options=run_options, run_metadata=run_metadata) + self.assertTrue(run_metadata.HasField('step_stats')) + step_stats = run_metadata.step_stats + devices = [d.device for d in step_stats.dev_stats] + self.assertTrue('/job:localhost/replica:0/task:0/device:CPU:0' in devices) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format() + self._validateTrace(ctf) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format(show_dataflow=False) + self._validateTrace(ctf) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format(show_memory=False) + self._validateTrace(ctf) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format( + show_memory=False, show_dataflow=False) + self._validateTrace(ctf) + + def testTimelineGpu(self): + if not test.is_gpu_available(cuda_only=True): + return + + run_options = config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE) + run_metadata = config_pb2.RunMetadata() + + with self.test_session(force_gpu=True) as sess: + const1 = constant_op.constant(1.0, name='const1') + const2 = constant_op.constant(2.0, name='const2') + result = math_ops.add(const1, const2) + const1 * const2 + sess.run(result, options=run_options, run_metadata=run_metadata) + self.assertTrue(run_metadata.HasField('step_stats')) + step_stats = run_metadata.step_stats + devices = [d.device for d in step_stats.dev_stats] + self.assertTrue('/job:localhost/replica:0/task:0/device:GPU:0' in devices) + self.assertTrue('/device:GPU:0/stream:all' in devices) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format() + self._validateTrace(ctf) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format(show_dataflow=False) + self._validateTrace(ctf) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format(show_memory=False) + self._validateTrace(ctf) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format( + show_memory=False, show_dataflow=False) + self._validateTrace(ctf) + + def testTimelineWithRPCs(self): + """Tests that Timeline can handle RPC tracing.""" + metadata = config_pb2.RunMetadata() + step_stats = metadata.step_stats + dev_stats = step_stats.dev_stats.add() + dev_stats.device = '/job:worker/replica:0/task:0/cpu:0' + node_stats = dev_stats.node_stats.add() + node_stats.node_name = 'RecvTensor' + node_stats.all_start_micros = 12345 + node_stats.op_end_rel_micros = 42 + node_stats.timeline_label = ('[1024B] edge_160_conv2/biases/read from ' + '/job:ps/replica:0/task:3/cpu:0 to ' + '/job:worker/replica:0/task:0/cpu:0') + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format() + self._validateTrace(ctf) + + def testAnalysisAndAllocations(self): + run_options = config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE) + run_metadata = config_pb2.RunMetadata() + config = config_pb2.ConfigProto(device_count={'CPU': 3}) + + with session.Session(config=config) as sess: + with ops.device('/cpu:0'): + num1 = variables.Variable(1.0, name='num1') + with ops.device('/cpu:1'): + num2 = variables.Variable(2.0, name='num2') + with ops.device('/cpu:2'): + result = num1 + num2 + num1 * num2 + sess.run(variables.global_variables_initializer()) + sess.run(result, options=run_options, run_metadata=run_metadata) + + self.assertTrue(run_metadata.HasField('step_stats')) + tl = timeline.Timeline(run_metadata.step_stats) + step_analysis = tl.analyze_step_stats() + ctf = step_analysis.chrome_trace.format_to_string() + self._validateTrace(ctf) + maximums = step_analysis.allocator_maximums + cpuname = 'mklcpu' if test_util.IsMklEnabled() else 'cpu' + self.assertTrue(cpuname in maximums) + cpu_max = maximums[ + 'cuda_host_bfc'] if 'cuda_host_bfc' in maximums else maximums[cpuname] + # At least num1 + num2, both float32s (4 bytes each) + self.assertGreater(cpu_max.num_bytes, 8) + self.assertGreater(cpu_max.timestamp, 0) + self.assertTrue('num1' in cpu_max.tensors or 'num1/read' in cpu_max.tensors) + self.assertTrue('num2' in cpu_max.tensors or 'num2/read' in cpu_max.tensors) + + def testManyCPUs(self): + run_options = config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE) + run_metadata = config_pb2.RunMetadata() + config = config_pb2.ConfigProto(device_count={'CPU': 3}) + with session.Session(config=config) as sess: + with ops.device('/cpu:0'): + num1 = variables.Variable(1.0, name='num1') + with ops.device('/cpu:1'): + num2 = variables.Variable(2.0, name='num2') + with ops.device('/cpu:2'): + result = num1 + num2 + num1 * num2 + sess.run(variables.global_variables_initializer()) + sess.run(result, options=run_options, run_metadata=run_metadata) + self.assertTrue(run_metadata.HasField('step_stats')) + step_stats = run_metadata.step_stats + devices = [d.device for d in step_stats.dev_stats] + self.assertTrue('/job:localhost/replica:0/task:0/device:CPU:0' in devices) + self.assertTrue('/job:localhost/replica:0/task:0/device:CPU:1' in devices) + self.assertTrue('/job:localhost/replica:0/task:0/device:CPU:2' in devices) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format() + self._validateTrace(ctf) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format(show_dataflow=False) + self._validateTrace(ctf) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format(show_memory=False) + self._validateTrace(ctf) + tl = timeline.Timeline(step_stats) + ctf = tl.generate_chrome_trace_format( + show_memory=False, show_dataflow=False) + self._validateTrace(ctf) + + +if __name__ == '__main__': + test.main() + +""" +K-Neighbors for Photometric Redshifts +------------------------------------- + +Estimate redshifts from the colors of sdss galaxies and quasars. +This uses colors from a sample of 50,000 objects with SDSS photometry +and ugriz magnitudes. The example shows how far one can get with an +extremely simple machine learning approach to the photometric redshift +problem. + +The function :func:`fetch_sdss_galaxy_colors` used below actually queries +the SDSS CASjobs server for the colors of the 50,000 galaxies. +""" +# Author: Jake VanderPlas +# License: BSD +# The figure is an example from astroML: see http://astroML.github.com +from __future__ import print_function, division + +import numpy as np +from matplotlib import pyplot as plt + +from sklearn.neighbors import KNeighborsRegressor + +from astroML.datasets import fetch_sdss_galaxy_colors +from astroML.plotting import scatter_contour + +n_neighbors = 1 + +data = fetch_sdss_galaxy_colors() + +N = len(data) + +# shuffle data +np.random.seed(0) +np.random.shuffle(data) + +# put colors in a matrix +X = np.zeros((N, 4)) +X[:, 0] = data['u'] - data['g'] +X[:, 1] = data['g'] - data['r'] +X[:, 2] = data['r'] - data['i'] +X[:, 3] = data['i'] - data['z'] +z = data['redshift'] + +# divide into training and testing data +Ntrain = N // 2 +Xtrain = X[:Ntrain] +ztrain = z[:Ntrain] + +Xtest = X[Ntrain:] +ztest = z[Ntrain:] + +knn = KNeighborsRegressor(n_neighbors, weights='uniform') +zpred = knn.fit(Xtrain, ztrain).predict(Xtest) + +axis_lim = np.array([-0.1, 2.5]) + +rms = np.sqrt(np.mean((ztest - zpred) ** 2)) +print("RMS error = %.2g" % rms) + +ax = plt.axes() +plt.scatter(ztest, zpred, c='k', lw=0, s=4) +plt.plot(axis_lim, axis_lim, '--k') +plt.plot(axis_lim, axis_lim + rms, ':k') +plt.plot(axis_lim, axis_lim - rms, ':k') +plt.xlim(axis_lim) +plt.ylim(axis_lim) + +plt.text(0.99, 0.02, "RMS error = %.2g" % rms, + ha='right', va='bottom', transform=ax.transAxes, + bbox=dict(ec='w', fc='w'), fontsize=16) + +plt.title('Photo-z: Nearest Neigbor Regression') +plt.xlabel(r'$\mathrm{z_{spec}}$', fontsize=14) +plt.ylabel(r'$\mathrm{z_{phot}}$', fontsize=14) +plt.show() + +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + MultipartToSingleparts.py + --------------------- + Date : August 2012 + Copyright : (C) 2012 by Victor Olaya + Email : volayaf at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Victor Olaya' +__date__ = 'August 2012' +__copyright__ = '(C) 2012, Victor Olaya' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from PyQt4.QtCore import * +from qgis.core import * +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.GeoAlgorithmExecutionException import \ + GeoAlgorithmExecutionException +from processing.parameters.ParameterVector import ParameterVector +from processing.outputs.OutputVector import OutputVector +from processing.tools import dataobjects, vector + + +class MultipartToSingleparts(GeoAlgorithm): + + INPUT = 'INPUT' + OUTPUT = 'OUTPUT' + + # ========================================================================= + # def getIcon(self): + # return QIcon(os.path.dirname(__file__) + "/icons/multi_to_single.png") + # ========================================================================= + + def defineCharacteristics(self): + self.name = 'Multipart to singleparts' + self.group = 'Vector geometry tools' + + self.addParameter(ParameterVector(self.INPUT, 'Input layer')) + self.addOutput(OutputVector(self.OUTPUT, 'Output layer')) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri( + self.getParameterValue(self.INPUT)) + + geomType = self.multiToSingleGeom(layer.dataProvider().geometryType()) + + writer = self.getOutputFromName( + self.OUTPUT).getVectorWriter(layer.pendingFields().toList(), + geomType, layer.crs()) + + outFeat = QgsFeature() + inGeom = QgsGeometry() + + current = 0 + features = vector.features(layer) + total = 100.0 / float(len(features)) + for f in features: + inGeom = f.geometry() + attrs = f.attributes() + + geometries = self.extractAsSingle(inGeom) + outFeat.setAttributes(attrs) + + for g in geometries: + outFeat.setGeometry(g) + writer.addFeature(outFeat) + + current += 1 + progress.setPercentage(int(current * total)) + + del writer + + def multiToSingleGeom(self, wkbType): + try: + if wkbType in (QGis.WKBPoint, QGis.WKBMultiPoint, + QGis.WKBPoint25D, QGis.WKBMultiPoint25D): + return QGis.WKBPoint + elif wkbType in (QGis.WKBLineString, QGis.WKBMultiLineString, + QGis.WKBMultiLineString25D, + QGis.WKBLineString25D): + + return QGis.WKBLineString + elif wkbType in (QGis.WKBPolygon, QGis.WKBMultiPolygon, + QGis.WKBMultiPolygon25D, QGis.WKBPolygon25D): + + return QGis.WKBPolygon + else: + return QGis.WKBUnknown + except Exception, err: + raise GeoAlgorithmExecutionException(unicode(err)) + + def extractAsSingle(self, geom): + multiGeom = QgsGeometry() + geometries = [] + if geom.type() == QGis.Point: + if geom.isMultipart(): + multiGeom = geom.asMultiPoint() + for i in multiGeom: + geometries.append(QgsGeometry().fromPoint(i)) + else: + geometries.append(geom) + elif geom.type() == QGis.Line: + if geom.isMultipart(): + multiGeom = geom.asMultiPolyline() + for i in multiGeom: + geometries.append(QgsGeometry().fromPolyline(i)) + else: + geometries.append(geom) + elif geom.type() == QGis.Polygon: + if geom.isMultipart(): + multiGeom = geom.asMultiPolygon() + for i in multiGeom: + geometries.append(QgsGeometry().fromPolygon(i)) + else: + geometries.append(geom) + return geometries + +# Copyright (c) 2012 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Traffic control library for constraining the network configuration on a port. + +The traffic controller sets up a constrained network configuration on a port. +Traffic to the constrained port is forwarded to a specified server port. +""" + +import logging +import os +import re +import subprocess + +# The maximum bandwidth limit. +_DEFAULT_MAX_BANDWIDTH_KBIT = 1000000 + + +class TrafficControlError(BaseException): + """Exception raised for errors in traffic control library. + + Attributes: + msg: User defined error message. + cmd: Command for which the exception was raised. + returncode: Return code of running the command. + stdout: Output of running the command. + stderr: Error output of running the command. + """ + + def __init__(self, msg, cmd=None, returncode=None, output=None, + error=None): + BaseException.__init__(self, msg) + self.msg = msg + self.cmd = cmd + self.returncode = returncode + self.output = output + self.error = error + + +def CheckRequirements(): + """Checks if permissions are available to run traffic control commands. + + Raises: + TrafficControlError: If permissions to run traffic control commands are not + available. + """ + if os.geteuid() != 0: + _Exec(['sudo', '-n', 'tc', '-help'], + msg=('Cannot run \'tc\' command. Traffic Control must be run as root ' + 'or have password-less sudo access to this command.')) + _Exec(['sudo', '-n', 'iptables', '-help'], + msg=('Cannot run \'iptables\' command. Traffic Control must be run ' + 'as root or have password-less sudo access to this command.')) + + +def CreateConstrainedPort(config): + """Creates a new constrained port. + + Imposes packet level constraints such as bandwidth, latency, and packet loss + on a given port using the specified configuration dictionary. Traffic to that + port is forwarded to a specified server port. + + Args: + config: Constraint configuration dictionary, format: + port: Port to constrain (integer 1-65535). + server_port: Port to redirect traffic on [port] to (integer 1-65535). + interface: Network interface name (string). + latency: Delay added on each packet sent (integer in ms). + bandwidth: Maximum allowed upload bandwidth (integer in kbit/s). + loss: Percentage of packets to drop (integer 0-100). + + Raises: + TrafficControlError: If any operation fails. The message in the exception + describes what failed. + """ + _CheckArgsExist(config, 'interface', 'port', 'server_port') + _AddRootQdisc(config['interface']) + + try: + _ConfigureClass('add', config) + _AddSubQdisc(config) + _AddFilter(config['interface'], config['port']) + _AddIptableRule(config['interface'], config['port'], config['server_port']) + except TrafficControlError as e: + logging.debug('Error creating constrained port %d.\nError: %s\n' + 'Deleting constrained port.', config['port'], e.error) + DeleteConstrainedPort(config) + raise e + + +def DeleteConstrainedPort(config): + """Deletes an existing constrained port. + + Deletes constraints set on a given port and the traffic forwarding rule from + the constrained port to a specified server port. + + The original constrained network configuration used to create the constrained + port must be passed in. + + Args: + config: Constraint configuration dictionary, format: + port: Port to constrain (integer 1-65535). + server_port: Port to redirect traffic on [port] to (integer 1-65535). + interface: Network interface name (string). + bandwidth: Maximum allowed upload bandwidth (integer in kbit/s). + + Raises: + TrafficControlError: If any operation fails. The message in the exception + describes what failed. + """ + _CheckArgsExist(config, 'interface', 'port', 'server_port') + try: + # Delete filters first so it frees the class. + _DeleteFilter(config['interface'], config['port']) + finally: + try: + # Deleting the class deletes attached qdisc as well. + _ConfigureClass('del', config) + finally: + _DeleteIptableRule(config['interface'], config['port'], + config['server_port']) + + +def TearDown(config): + """Deletes the root qdisc and all iptables rules. + + Args: + config: Constraint configuration dictionary, format: + interface: Network interface name (string). + + Raises: + TrafficControlError: If any operation fails. The message in the exception + describes what failed. + """ + _CheckArgsExist(config, 'interface') + + command = ['sudo', 'tc', 'qdisc', 'del', 'dev', config['interface'], 'root'] + try: + _Exec(command, msg='Could not delete root qdisc.') + finally: + _DeleteAllIpTableRules() + + +def _CheckArgsExist(config, *args): + """Check that the args exist in config dictionary and are not None. + + Args: + config: Any dictionary. + *args: The list of key names to check. + + Raises: + TrafficControlError: If any key name does not exist in config or is None. + """ + for key in args: + if key not in config.keys() or config[key] is None: + raise TrafficControlError('Missing "%s" parameter.' % key) + + +def _AddRootQdisc(interface): + """Sets up the default root qdisc. + + Args: + interface: Network interface name. + + Raises: + TrafficControlError: If adding the root qdisc fails for a reason other than + it already exists. + """ + command = ['sudo', 'tc', 'qdisc', 'add', 'dev', interface, 'root', 'handle', + '1:', 'htb'] + try: + _Exec(command, msg=('Error creating root qdisc. ' + 'Make sure you have root access')) + except TrafficControlError as e: + # Ignore the error if root already exists. + if not 'File exists' in e.error: + raise e + + +def _ConfigureClass(option, config): + """Adds or deletes a class and qdisc attached to the root. + + The class specifies bandwidth, and qdisc specifies delay and packet loss. The + class ID is based on the config port. + + Args: + option: Adds or deletes a class option [add|del]. + config: Constraint configuration dictionary, format: + port: Port to constrain (integer 1-65535). + interface: Network interface name (string). + bandwidth: Maximum allowed upload bandwidth (integer in kbit/s). + """ + # Use constrained port as class ID so we can attach the qdisc and filter to + # it, as well as delete the class, using only the port number. + class_id = '1:%x' % config['port'] + if 'bandwidth' not in config.keys() or not config['bandwidth']: + bandwidth = _DEFAULT_MAX_BANDWIDTH_KBIT + else: + bandwidth = config['bandwidth'] + + bandwidth = '%dkbit' % bandwidth + command = ['sudo', 'tc', 'class', option, 'dev', config['interface'], + 'parent', '1:', 'classid', class_id, 'htb', 'rate', bandwidth, + 'ceil', bandwidth] + _Exec(command, msg=('Error configuring class ID %s using "%s" command.' % + (class_id, option))) + + +def _AddSubQdisc(config): + """Adds a qdisc attached to the class identified by the config port. + + Args: + config: Constraint configuration dictionary, format: + port: Port to constrain (integer 1-65535). + interface: Network interface name (string). + latency: Delay added on each packet sent (integer in ms). + loss: Percentage of packets to drop (integer 0-100). + """ + port_hex = '%x' % config['port'] + class_id = '1:%x' % config['port'] + command = ['sudo', 'tc', 'qdisc', 'add', 'dev', config['interface'], 'parent', + class_id, 'handle', port_hex + ':0', 'netem'] + + # Check if packet-loss is set in the configuration. + if 'loss' in config.keys() and config['loss']: + loss = '%d%%' % config['loss'] + command.extend(['loss', loss]) + # Check if latency is set in the configuration. + if 'latency' in config.keys() and config['latency']: + latency = '%dms' % config['latency'] + command.extend(['delay', latency]) + + _Exec(command, msg='Could not attach qdisc to class ID %s.' % class_id) + + +def _AddFilter(interface, port): + """Redirects packets coming to a specified port into the constrained class. + + Args: + interface: Interface name to attach the filter to (string). + port: Port number to filter packets with (integer 1-65535). + """ + class_id = '1:%x' % port + + command = ['sudo', 'tc', 'filter', 'add', 'dev', interface, 'protocol', 'ip', + 'parent', '1:', 'prio', '1', 'u32', 'match', 'ip', 'sport', port, + '0xffff', 'flowid', class_id] + _Exec(command, msg='Error adding filter on port %d.' % port) + + +def _DeleteFilter(interface, port): + """Deletes the filter attached to the configured port. + + Args: + interface: Interface name the filter is attached to (string). + port: Port number being filtered (integer 1-65535). + """ + handle_id = _GetFilterHandleId(interface, port) + command = ['sudo', 'tc', 'filter', 'del', 'dev', interface, 'protocol', 'ip', + 'parent', '1:0', 'handle', handle_id, 'prio', '1', 'u32'] + _Exec(command, msg='Error deleting filter on port %d.' % port) + + +def _GetFilterHandleId(interface, port): + """Searches for the handle ID of the filter identified by the config port. + + Args: + interface: Interface name the filter is attached to (string). + port: Port number being filtered (integer 1-65535). + + Returns: + The handle ID. + + Raises: + TrafficControlError: If handle ID was not found. + """ + command = ['sudo', 'tc', 'filter', 'list', 'dev', interface, 'parent', '1:'] + output = _Exec(command, msg='Error listing filters.') + # Search for the filter handle ID associated with class ID '1:port'. + handle_id_re = re.search( + '([0-9a-fA-F]{3}::[0-9a-fA-F]{3}).*(?=flowid 1:%x\s)' % port, output) + if handle_id_re: + return handle_id_re.group(1) + raise TrafficControlError(('Could not find filter handle ID for class ID ' + '1:%x.') % port) + + +def _AddIptableRule(interface, port, server_port): + """Forwards traffic from constrained port to a specified server port. + + Args: + interface: Interface name to attach the filter to (string). + port: Port of incoming packets (integer 1-65535). + server_port: Server port to forward the packets to (integer 1-65535). + """ + # Preroute rules for accessing the port through external connections. + command = ['sudo', 'iptables', '-t', 'nat', '-A', 'PREROUTING', '-i', + interface, '-p', 'tcp', '--dport', port, '-j', 'REDIRECT', + '--to-port', server_port] + _Exec(command, msg='Error adding iptables rule for port %d.' % port) + + # Output rules for accessing the rule through localhost or 127.0.0.1 + command = ['sudo', 'iptables', '-t', 'nat', '-A', 'OUTPUT', '-p', 'tcp', + '--dport', port, '-j', 'REDIRECT', '--to-port', server_port] + _Exec(command, msg='Error adding iptables rule for port %d.' % port) + + +def _DeleteIptableRule(interface, port, server_port): + """Deletes the iptable rule associated with specified port number. + + Args: + interface: Interface name to attach the filter to (string). + port: Port of incoming packets (integer 1-65535). + server_port: Server port packets are forwarded to (integer 1-65535). + """ + command = ['sudo', 'iptables', '-t', 'nat', '-D', 'PREROUTING', '-i', + interface, '-p', 'tcp', '--dport', port, '-j', 'REDIRECT', + '--to-port', server_port] + _Exec(command, msg='Error deleting iptables rule for port %d.' % port) + + command = ['sudo', 'iptables', '-t', 'nat', '-D', 'OUTPUT', '-p', 'tcp', + '--dport', port, '-j', 'REDIRECT', '--to-port', server_port] + _Exec(command, msg='Error adding iptables rule for port %d.' % port) + + +def _DeleteAllIpTableRules(): + """Deletes all iptables rules.""" + command = ['sudo', 'iptables', '-t', 'nat', '-F'] + _Exec(command, msg='Error deleting all iptables rules.') + + +def _Exec(command, msg=None): + """Executes a command. + + Args: + command: Command list to execute. + msg: Message describing the error in case the command fails. + + Returns: + The standard output from running the command. + + Raises: + TrafficControlError: If command fails. Message is set by the msg parameter. + """ + cmd_list = [str(x) for x in command] + cmd = ' '.join(cmd_list) + logging.debug('Running command: %s', cmd) + + p = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + output, error = p.communicate() + if p.returncode != 0: + raise TrafficControlError(msg, cmd, p.returncode, output, error) + return output.strip() + +# ---------------------------------------------------------------------- +# Numenta Platform for Intelligent Computing (NuPIC) +# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement +# with Numenta, Inc., for a separate license for this software code, the +# following terms and conditions apply: +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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. +# +# http://numenta.org/licenses/ +# ---------------------------------------------------------------------- + +import math +import numpy as np + +from nupic.data import SENTINEL_VALUE_FOR_MISSING_DATA +from nupic.encoders.scalar import ScalarEncoder +from nupic.utils import MovingAverage + +class AdaptiveScalarEncoder(ScalarEncoder): + """ + This is an implementation of the scalar encoder that adapts the min and + max of the scalar encoder dynamically. This is essential to the streaming + model of the online prediction framework. + + Initialization of an adapive encoder using resolution or radius is not supported; + it must be intitialized with n. This n is kept constant while the min and max of the + encoder changes. + + The adaptive encoder must be have periodic set to false. + + The adaptive encoder may be initialized with a minval and maxval or with `None` + for each of these. In the latter case, the min and max are set as the 1st and 99th + percentile over a window of the past 100 records. + + **Note:** the sliding window may record duplicates of the values in the dataset, + and therefore does not reflect the statistical distribution of the input data + and may not be used to calculate the median, mean etc. + """ + + + def __init__(self, w, minval=None, maxval=None, periodic=False, n=0, radius=0, + resolution=0, name=None, verbosity=0, clipInput=True, forced=False): + """ + [overrides nupic.encoders.scalar.ScalarEncoder.__init__] + """ + self._learningEnabled = True + if periodic: + #Adaptive scalar encoders take non-periodic inputs only + raise Exception('Adaptive scalar encoder does not encode periodic inputs') + assert n!=0 #An adaptive encoder can only be intialized using n + + super(AdaptiveScalarEncoder, self).__init__(w=w, n=n, minval=minval, maxval=maxval, + clipInput=True, name=name, verbosity=verbosity, forced=forced) + self.recordNum=0 #how many inputs have been sent to the encoder? + self.slidingWindow = MovingAverage(300) + + + def _setEncoderParams(self): + """ + Set the radius, resolution and range. These values are updated when minval + and/or maxval change. + """ + + self.rangeInternal = float(self.maxval - self.minval) + + self.resolution = float(self.rangeInternal) / (self.n - self.w) + self.radius = self.w * self.resolution + self.range = self.rangeInternal + self.resolution + + # nInternal represents the output area excluding the possible padding on each side + self.nInternal = self.n - 2 * self.padding + + # Invalidate the bucket values cache so that they get recomputed + self._bucketValues = None + + + def setFieldStats(self, fieldName, fieldStats): + """ + TODO: document + """ + #If the stats are not fully formed, ignore. + if fieldStats[fieldName]['min'] == None or \ + fieldStats[fieldName]['max'] == None: + return + self.minval = fieldStats[fieldName]['min'] + self.maxval = fieldStats[fieldName]['max'] + if self.minval == self.maxval: + self.maxval+=1 + self._setEncoderParams() + + + def _setMinAndMax(self, input, learn): + """ + Potentially change the minval and maxval using input. + **The learn flag is currently not supported by cla regions.** + """ + + self.slidingWindow.next(input) + + if self.minval is None and self.maxval is None: + self.minval = input + self.maxval = input+1 #When the min and max and unspecified and only one record has been encoded + self._setEncoderParams() + + elif learn: + sorted = self.slidingWindow.getSlidingWindow() + sorted.sort() + + minOverWindow = sorted[0] + maxOverWindow = sorted[len(sorted)-1] + + if minOverWindow < self.minval: + #initialBump = abs(self.minval-minOverWindow)*(1-(min(self.recordNum, 200.0)/200.0))*2 #decrement minval more aggressively in the beginning + if self.verbosity >= 2: + print "Input %s=%.2f smaller than minval %.2f. Adjusting minval to %.2f"\ + % (self.name, input, self.minval, minOverWindow) + self.minval = minOverWindow #-initialBump + self._setEncoderParams() + + if maxOverWindow > self.maxval: + #initialBump = abs(self.maxval-maxOverWindow)*(1-(min(self.recordNum, 200.0)/200.0))*2 #decrement maxval more aggressively in the beginning + if self.verbosity >= 2: + print "Input %s=%.2f greater than maxval %.2f. Adjusting maxval to %.2f" \ + % (self.name, input, self.maxval, maxOverWindow) + self.maxval = maxOverWindow #+initialBump + self._setEncoderParams() + + + def getBucketIndices(self, input, learn=None): + """ + [overrides nupic.encoders.scalar.ScalarEncoder.getBucketIndices] + """ + + self.recordNum +=1 + if learn is None: + learn = self._learningEnabled + + if type(input) is float and math.isnan(input): + input = SENTINEL_VALUE_FOR_MISSING_DATA + + if input == SENTINEL_VALUE_FOR_MISSING_DATA: + return [None] + else: + self._setMinAndMax(input, learn) + return super(AdaptiveScalarEncoder, self).getBucketIndices(input) + + + def encodeIntoArray(self, input, output,learn=None): + """ + [overrides nupic.encoders.scalar.ScalarEncoder.encodeIntoArray] + """ + + self.recordNum +=1 + if learn is None: + learn = self._learningEnabled + if input == SENTINEL_VALUE_FOR_MISSING_DATA: + output[0:self.n] = 0 + elif not math.isnan(input): + self._setMinAndMax(input, learn) + + super(AdaptiveScalarEncoder, self).encodeIntoArray(input, output) + + def getBucketInfo(self, buckets): + """ + [overrides nupic.encoders.scalar.ScalarEncoder.getBucketInfo] + """ + + if self.minval is None or self.maxval is None: + return [EncoderResult(value=0, scalar=0, + encoding=numpy.zeros(self.n))] + + return super(AdaptiveScalarEncoder, self).getBucketInfo(buckets) + + + def topDownCompute(self, encoded): + """ + [overrides nupic.encoders.scalar.ScalarEncoder.topDownCompute] + """ + + if self.minval is None or self.maxval is None: + return [EncoderResult(value=0, scalar=0, + encoding=numpy.zeros(self.n))] + return super(AdaptiveScalarEncoder, self).topDownCompute(encoded) + + + def dump(self): + """ + Prints details about current state to stdout. + """ + print "AdaptiveScalarEncoder:" + print " min: %f" % self.minval + print " max: %f" % self.maxval + print " w: %d" % self.w + print " n: %d" % self.n + print " resolution: %f" % self.resolution + print " radius: %f" % self.radius + print " periodic: %s" % self.periodic + print " nInternal: %d" % self.nInternal + print " rangeInternal: %f" % self.rangeInternal + print " padding: %d" % self.padding + + + @classmethod + def read(cls, proto): + encoder = super(AdaptiveScalarEncoder, cls).read(proto) + encoder.recordNum = proto.recordNum + encoder.slidingWindow = MovingAverage.read(proto.slidingWindow) + return encoder + + + def write(self, proto): + super(AdaptiveScalarEncoder, self).write(proto) + proto.recordNum = self.recordNum + self.slidingWindow.write(proto.slidingWindow) + +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (c) 2017, René Moser +# +# 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 . + +ANSIBLE_METADATA = {'metadata_version': '1.0', + 'status': ['preview'], + 'supported_by': 'community'} + + +DOCUMENTATION = ''' +--- +module: cs_vpn_gateway +short_description: Manages site-to-site VPN gateways on Apache CloudStack based clouds. +description: + - Creates and removes VPN site-to-site gateways. +version_added: "2.4" +author: "René Moser (@resmo)" +options: + vpc: + description: + - Name of the VPC. + required: true + state: + description: + - State of the VPN gateway. + required: false + default: "present" + choices: [ 'present', 'absent' ] + domain: + description: + - Domain the VPN gateway is related to. + required: false + default: null + account: + description: + - Account the VPN gateway is related to. + required: false + default: null + project: + description: + - Name of the project the VPN gateway is related to. + required: false + default: null + zone: + description: + - Name of the zone the VPC is related to. + - If not set, default zone is used. + required: false + default: null + poll_async: + description: + - Poll async jobs until job has finished. + required: false + default: true +extends_documentation_fragment: cloudstack +''' + +EXAMPLES = ''' +# Ensure a vpn gateway is present +- local_action: + module: cs_vpn_gateway + vpc: my VPC + +# Ensure a vpn gateway is absent +- local_action: + module: cs_vpn_gateway + vpc: my VPC + state: absent +''' + +RETURN = ''' +--- +id: + description: UUID of the VPN site-to-site gateway. + returned: success + type: string + sample: 04589590-ac63-4ffc-93f5-b698b8ac38b6 +public_ip: + description: IP address of the VPN site-to-site gateway. + returned: success + type: string + sample: 10.100.212.10 +vpc: + description: Name of the VPC. + returned: success + type: string + sample: My VPC +domain: + description: Domain the VPN site-to-site gateway is related to. + returned: success + type: string + sample: example domain +account: + description: Account the VPN site-to-site gateway is related to. + returned: success + type: string + sample: example account +project: + description: Name of project the VPN site-to-site gateway is related to. + returned: success + type: string + sample: Production +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.cloudstack import ( + AnsibleCloudStack, + CloudStackException, + cs_argument_spec, + cs_required_together +) + + +class AnsibleCloudStackVpnGateway(AnsibleCloudStack): + + def __init__(self, module): + super(AnsibleCloudStackVpnGateway, self).__init__(module) + self.returns = { + 'publicip': 'public_ip' + } + + def get_vpn_gateway(self): + args = { + 'vpcid': self.get_vpc(key='id'), + 'account': self.get_account(key='name'), + 'domainid': self.get_domain(key='id'), + 'projectid': self.get_project(key='id') + } + vpn_gateways = self.cs.listVpnGateways(**args) + if vpn_gateways: + return vpn_gateways['vpngateway'][0] + return None + + def present_vpn_gateway(self): + vpn_gateway = self.get_vpn_gateway() + if not vpn_gateway: + self.result['changed'] = True + args = { + 'vpcid': self.get_vpc(key='id'), + 'account': self.get_account(key='name'), + 'domainid': self.get_domain(key='id'), + 'projectid': self.get_project(key='id') + } + if not self.module.check_mode: + res = self.cs.createVpnGateway(**args) + if 'errortext' in res: + self.module.fail_json(msg="Failed: '%s'" % res['errortext']) + + poll_async = self.module.params.get('poll_async') + if poll_async: + vpn_gateway = self.poll_job(res, 'vpngateway') + + return vpn_gateway + + def absent_vpn_gateway(self): + vpn_gateway = self.get_vpn_gateway() + if vpn_gateway: + self.result['changed'] = True + args = { + 'id': vpn_gateway['id'] + } + if not self.module.check_mode: + res = self.cs.deleteVpnGateway(**args) + if 'errortext' in res: + self.module.fail_json(msg="Failed: '%s'" % res['errortext']) + + poll_async = self.module.params.get('poll_async') + if poll_async: + self.poll_job(res, 'vpngateway') + + return vpn_gateway + + def get_result(self, vpn_gateway): + super(AnsibleCloudStackVpnGateway, self).get_result(vpn_gateway) + if vpn_gateway: + self.result['vpc'] = self.get_vpc(key='name') + return self.result + + +def main(): + argument_spec = cs_argument_spec() + argument_spec.update(dict( + vpc=dict(required=True), + state=dict(choices=['present', 'absent'], default='present'), + domain=dict(), + account=dict(), + project=dict(), + zone=dict(), + poll_async=dict(type='bool', default=True), + )) + + module = AnsibleModule( + argument_spec=argument_spec, + required_together=cs_required_together(), + supports_check_mode=True + ) + + try: + acs_vpn_gw = AnsibleCloudStackVpnGateway(module) + + state = module.params.get('state') + if state == "absent": + vpn_gateway = acs_vpn_gw.absent_vpn_gateway() + else: + vpn_gateway = acs_vpn_gw.present_vpn_gateway() + + result = acs_vpn_gw.get_result(vpn_gateway) + + except CloudStackException as e: + module.fail_json(msg='CloudStackException: %s' % str(e)) + + module.exit_json(**result) + + +if __name__ == '__main__': + main() + +import pytest +import mock + +from framework.auth.core import Auth +from api.base.settings.defaults import API_BASE +from rest_framework import exceptions +from osf_tests.factories import ( + NodeFactory, + ProjectFactory, + RegistrationFactory, + AuthUserFactory, + WithdrawnRegistrationFactory, + ForkFactory +) + + +@pytest.fixture() +def user(): + return AuthUserFactory() + + +@pytest.mark.django_db +class TestRegistrationForksList: + + @pytest.fixture() + def pointer(self, user): + return ProjectFactory(creator=user) + + @pytest.fixture() + def private_project(self, user, pointer): + private_project = ProjectFactory(creator=user) + private_project.add_pointer(pointer, auth=Auth(user), save=True) + return private_project + + @pytest.fixture() + def public_project(self, user): + return ProjectFactory(is_public=True, creator=user) + + @pytest.fixture() + def private_component(self, user, private_project): + return NodeFactory(parent=private_project, creator=user) + + @pytest.fixture() + def public_component(self, user, public_project): + return NodeFactory(parent=public_project, creator=user, is_public=True) + + @pytest.fixture() + def private_registration(self, user, private_project, private_component): + return RegistrationFactory(project=private_project, creator=user) + + @pytest.fixture() + def public_registration(self, user, public_project, public_component): + return RegistrationFactory( + project=public_project, + creator=user, + is_public=True) + + @pytest.fixture() + def private_fork(self, user, private_registration): + return ForkFactory(project=private_registration, user=user) + + @pytest.fixture() + def public_fork(self, user, public_registration): + return ForkFactory(project=public_registration, user=user) + + @pytest.fixture() + def private_registration_url(self, private_registration): + return '/{}registrations/{}/forks/'.format( + API_BASE, private_registration._id) + + @pytest.fixture() + def public_registration_url(self, public_registration): + return '/{}registrations/{}/forks/'.format( + API_BASE, public_registration._id) + + def test_can_access_public_registration_forks_list_when_unauthenticated( + self, app, public_registration, public_fork, public_registration_url): + res = app.get(public_registration_url) + assert len(res.json['data']) == 0 + # Fork defaults to private + assert not public_fork.is_public + + public_fork.is_public = True + public_fork.save() + + res = app.get(public_registration_url) + assert res.status_code == 200 + assert len(res.json['data']) == 1 + assert public_fork.is_public is True + data = res.json['data'][0] + assert data['attributes']['title'] == 'Fork of ' + \ + public_registration.title + assert data['id'] == public_fork._id + assert not data['attributes']['registration'] + assert data['attributes']['fork'] is True + + def test_can_access_public_registration_forks_list_authenticated_contributor( + self, app, user, public_project, public_registration_url, public_fork): + res = app.get(public_registration_url, auth=user.auth) + assert res.status_code == 200 + + assert not public_fork.is_public + assert len(res.json['data']) == 1 + data = res.json['data'][0] + assert data['attributes']['title'] == 'Fork of ' + public_project.title + assert data['id'] == public_fork._id + assert not data['attributes']['registration'] + assert data['attributes']['fork'] is True + + def test_can_access_public_registration_forks_list_authenticated_non_contributor( + self, app, public_project, public_registration_url, public_fork): + non_contributor = AuthUserFactory() + + res = app.get(public_registration_url, auth=non_contributor.auth) + assert res.status_code == 200 + + assert len(res.json['data']) == 0 + # Fork defaults to private + assert not public_fork.is_public + + public_fork.is_public = True + public_fork.save() + + res = app.get(public_registration_url) + assert len(res.json['data']) == 1 + assert public_fork.is_public is True + data = res.json['data'][0] + assert data['attributes']['title'] == 'Fork of ' + public_project.title + assert data['id'] == public_fork._id + assert not data['attributes']['registration'] + assert data['attributes']['fork'] is True + + def test_authentication( + self, app, user, private_project, pointer, + private_registration, private_registration_url, + private_fork, private_component): + + # test_cannot_access_private_registration_forks_list_unauthenticated + res = app.get(private_registration_url, expect_errors=True) + assert res.status_code == 401 + assert res.json['errors'][0]['detail'] == exceptions.NotAuthenticated.default_detail + + # test_authenticated_contributor_can_access_private_registration_forks_list + res = app.get('{}?embed=children&embed=node_links&embed=logs&embed=contributors&embed=forked_from'.format( + private_registration_url), auth=user.auth) + assert res.status_code == 200 + assert len(res.json['data']) == 1 + data = res.json['data'][0] + assert data['attributes']['title'] == 'Fork of ' + \ + private_project.title + assert data['id'] == private_fork._id + + fork_contributors = data['embeds']['contributors']['data'][0]['embeds']['users']['data'] + assert fork_contributors['attributes']['family_name'] == user.family_name + assert fork_contributors['id'] == user._id + + forked_children = data['embeds']['children']['data'][0] + assert forked_children['id'] == private_registration.forks.first( + ).get_nodes(is_node_link=False)[0]._id + assert forked_children['attributes']['title'] == private_component.title + + forked_node_links = data['embeds']['node_links']['data'][0]['embeds']['target_node']['data'] + assert forked_node_links['id'] == pointer._id + assert forked_node_links['attributes']['title'] == pointer.title + assert not data['attributes']['registration'] + assert data['attributes']['fork'] is True + + expected_logs = list( + private_registration.logs.values_list( + 'action', flat=True)) + expected_logs.append( + private_registration.nodes[0].logs.latest().action) + expected_logs.append('node_forked') + expected_logs.append('node_forked') + + forked_logs = data['embeds']['logs']['data'] + assert set(expected_logs) == set( + log['attributes']['action'] for log in forked_logs) + assert len(forked_logs) == len(expected_logs) + + forked_from = data['embeds']['forked_from']['data'] + assert forked_from['id'] == private_registration._id + + # test_authenticated_non_contributor_cannot_access_private_registration_forks_list + non_contributor = AuthUserFactory() + + res = app.get( + private_registration_url, + auth=non_contributor.auth, + expect_errors=True) + assert res.status_code == 403 + assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail + + +@pytest.mark.django_db +class TestRegistrationForkCreate: + + @pytest.fixture() + def user_two(self): + return AuthUserFactory() + + @pytest.fixture() + def user_three(self): + return AuthUserFactory() + + @pytest.fixture() + def private_pointer(self, user_two): + return ProjectFactory(creator=user_two) + + @pytest.fixture() + def private_project(self, user, user_two, private_pointer): + private_project = ProjectFactory(creator=user) + private_project.add_pointer( + private_pointer, auth=Auth(user_two), save=True) + return private_project + + @pytest.fixture() + def private_registration(self, user, private_project): + return RegistrationFactory(creator=user, project=private_project) + + @pytest.fixture() + def fork_data(self): + return { + 'data': { + 'type': 'nodes' + } + } + + @pytest.fixture() + def fork_data_with_title(self): + return { + 'data': { + 'type': 'nodes', + 'attributes': { + 'title': 'My Forked Project' + } + } + } + + @pytest.fixture() + def private_registration_url(self, private_registration): + return '/{}registrations/{}/forks/'.format( + API_BASE, private_registration._id) + + @pytest.fixture() + def public_project(self, user): + return ProjectFactory(is_public=True, creator=user) + + @pytest.fixture() + def public_registration(self, user, public_project): + return RegistrationFactory( + creator=user, + project=public_project, + is_public=True) + + @pytest.fixture() + def public_registration_url(self, public_registration): + return '/{}registrations/{}/forks/'.format( + API_BASE, public_registration._id) + + def test_create_fork_from_public_registration_with_new_title( + self, app, user, public_registration, + public_registration_url, fork_data_with_title): + res = app.post_json_api( + public_registration_url, + fork_data_with_title, + auth=user.auth) + assert res.status_code == 201 + data = res.json['data'] + assert data['id'] == public_registration.forks.first()._id + assert data['attributes']['title'] == fork_data_with_title['data']['attributes']['title'] + assert not data['attributes']['registration'] + assert data['attributes']['fork'] is True + + def test_create_fork_from_private_registration_with_new_title( + self, app, user, private_registration, + private_registration_url, fork_data_with_title): + res = app.post_json_api( + private_registration_url, + fork_data_with_title, + auth=user.auth) + assert res.status_code == 201 + data = res.json['data'] + assert data['id'] == private_registration.forks.first()._id + assert data['attributes']['title'] == fork_data_with_title['data']['attributes']['title'] + assert not data['attributes']['registration'] + assert data['attributes']['fork'] is True + + def test_can_fork_public_registration_logged_in( + self, app, user_two, public_registration, + public_registration_url, fork_data): + res = app.post_json_api( + public_registration_url, + fork_data, + auth=user_two.auth) + assert res.status_code == 201 + data = res.json['data'] + assert data['id'] == public_registration.forks.first()._id + assert data['attributes']['title'] == 'Fork of ' + \ + public_registration.title + assert not data['attributes']['registration'] + assert data['attributes']['fork'] is True + + def test_cannot_fork_public_registration_logged_out( + self, app, public_registration_url, fork_data): + res = app.post_json_api( + public_registration_url, + fork_data, + expect_errors=True) + assert res.status_code == 401 + assert res.json['errors'][0]['detail'] == exceptions.NotAuthenticated.default_detail + + def test_can_fork_public_registration_logged_in_contributor( + self, app, user, public_registration, public_registration_url, fork_data): + res = app.post_json_api( + public_registration_url, + fork_data, + auth=user.auth) + assert res.status_code == 201 + data = res.json['data'] + assert data['id'] == public_registration.forks.first()._id + assert data['attributes']['title'] == 'Fork of ' + \ + public_registration.title + assert not data['attributes']['registration'] + assert data['attributes']['fork'] is True + + def test_cannot_fork_private_registration_logged_out( + self, app, private_registration_url, fork_data): + res = app.post_json_api( + private_registration_url, + fork_data, + expect_errors=True) + assert res.status_code == 401 + assert res.json['errors'][0]['detail'] == exceptions.NotAuthenticated.default_detail + + def test_cannot_fork_private_registration_logged_in_non_contributor( + self, app, user_two, private_registration_url, fork_data): + res = app.post_json_api( + private_registration_url, + fork_data, auth=user_two.auth, + expect_errors=True) + assert res.status_code == 403 + assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail + + def test_can_fork_private_registration_logged_in_contributor( + self, app, user, private_registration, private_registration_url, fork_data): + res = app.post_json_api('{}?embed=children&embed=node_links&embed=logs&embed=contributors&embed=forked_from'.format( + private_registration_url), fork_data, auth=user.auth) + assert res.status_code == 201 + + data = res.json['data'] + assert data['attributes']['title'] == 'Fork of ' + \ + private_registration.title + assert not data['attributes']['registration'] + assert data['attributes']['fork'] is True + + fork_contributors = data['embeds']['contributors']['data'][0]['embeds']['users']['data'] + assert fork_contributors['attributes']['family_name'] == user.family_name + assert fork_contributors['id'] == user._id + + forked_from = data['embeds']['forked_from']['data'] + assert forked_from['id'] == private_registration._id + + def test_fork_private_components_no_access( + self, app, user_two, user_three, public_registration, + public_registration_url, fork_data): + url = '{}?embed=children'.format(public_registration_url) + NodeFactory( + parent=public_registration, + creator=user_two, + is_public=False + ) + res = app.post_json_api(url, fork_data, auth=user_three.auth) + assert res.status_code == 201 + # Private components that you do not have access to are not forked + assert res.json['data']['embeds']['children']['links']['meta']['total'] == 0 + + def test_fork_components_you_can_access( + self, app, user, private_registration, + private_registration_url, fork_data): + url = '{}?embed=children'.format(private_registration_url) + new_component = NodeFactory(parent=private_registration, creator=user) + res = app.post_json_api(url, fork_data, auth=user.auth) + assert res.status_code == 201 + assert res.json['data']['embeds']['children']['links']['meta']['total'] == 1 + assert res.json['data']['embeds']['children']['data'][0]['id'] == new_component.forks.first( + )._id + + def test_fork_private_node_links( + self, app, user, private_registration_url, fork_data): + + url = '{}?embed=node_links'.format(private_registration_url) + + # Node link is forked, but shows up as a private node link + res = app.post_json_api(url, fork_data, auth=user.auth) + assert res.json['data']['embeds']['node_links']['data'][0]['embeds']['target_node'][ + 'errors'][0]['detail'] == exceptions.PermissionDenied.default_detail + assert res.json['data']['embeds']['node_links']['links']['meta']['total'] == 1 + + def test_fork_node_links_you_can_access( + self, app, user, private_project, fork_data): + pointer = ProjectFactory(creator=user) + private_project.add_pointer(pointer, auth=Auth(user), save=True) + + new_registration = RegistrationFactory( + project=private_project, creator=user) + + url = '/{}registrations/{}/forks/{}'.format( + API_BASE, new_registration._id, '?embed=node_links') + + res = app.post_json_api(url, fork_data, auth=user.auth) + assert res.json['data']['embeds']['node_links']['data'][1]['embeds']['target_node']['data']['id'] == pointer._id + assert res.json['data']['embeds']['node_links']['links']['meta']['total'] == 2 + + def test_cannot_fork_retractions( + self, app, user, private_registration, fork_data): + with mock.patch('osf.models.AbstractNode.update_search'): + WithdrawnRegistrationFactory( + registration=private_registration, user=user) + url = '/{}registrations/{}/forks/{}'.format( + API_BASE, private_registration._id, '?embed=forked_from') + + res = app.post_json_api( + url, fork_data, + auth=user.auth, + expect_errors=True) + assert res.status_code == 403 + + +__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError'] + +class Mark(object): + + def __init__(self, name, index, line, column, buffer, pointer): + self.name = name + self.index = index + self.line = line + self.column = column + self.buffer = buffer + self.pointer = pointer + + def get_snippet(self, indent=4, max_length=75): + if self.buffer is None: + return None + head = '' + start = self.pointer + while start > 0 and self.buffer[start-1] not in u'\0\r\n\x85\u2028\u2029': + start -= 1 + if self.pointer-start > max_length/2-1: + head = ' ... ' + start += 5 + break + tail = '' + end = self.pointer + while end < len(self.buffer) and self.buffer[end] not in u'\0\r\n\x85\u2028\u2029': + end += 1 + if end-self.pointer > max_length/2-1: + tail = ' ... ' + end -= 5 + break + snippet = self.buffer[start:end].encode('utf-8') + return ' '*indent + head + snippet + tail + '\n' \ + + ' '*(indent+self.pointer-start+len(head)) + '^' + + def __str__(self): + snippet = self.get_snippet() + where = " in \"%s\", line %d, column %d" \ + % (self.name, self.line+1, self.column+1) + if snippet is not None: + where += ":\n"+snippet + return where + +class YAMLError(Exception): + pass + +class MarkedYAMLError(YAMLError): + + def __init__(self, context=None, context_mark=None, + problem=None, problem_mark=None, note=None): + self.context = context + self.context_mark = context_mark + self.problem = problem + self.problem_mark = problem_mark + self.note = note + + def __str__(self): + lines = [] + if self.context is not None: + lines.append(self.context) + if self.context_mark is not None \ + and (self.problem is None or self.problem_mark is None + or self.context_mark.name != self.problem_mark.name + or self.context_mark.line != self.problem_mark.line + or self.context_mark.column != self.problem_mark.column): + lines.append(str(self.context_mark)) + if self.problem is not None: + lines.append(self.problem) + if self.problem_mark is not None: + lines.append(str(self.problem_mark)) + if self.note is not None: + lines.append(self.note) + return '\n'.join(lines) + + +import os + +import numpy +from numpy.distutils.misc_util import Configuration + + +def configuration(parent_package="", top_path=None): + config = Configuration("tree", parent_package, top_path) + libraries = [] + if os.name == 'posix': + libraries.append('m') + config.add_extension("_tree", + sources=["_tree.c"], + include_dirs=[numpy.get_include()], + libraries=libraries, + extra_compile_args=["-O3"]) + config.add_extension("_splitter", + sources=["_splitter.c"], + include_dirs=[numpy.get_include()], + libraries=libraries, + extra_compile_args=["-O3"]) + config.add_extension("_criterion", + sources=["_criterion.c"], + include_dirs=[numpy.get_include()], + libraries=libraries, + extra_compile_args=["-O3"]) + config.add_extension("_utils", + sources=["_utils.c"], + include_dirs=[numpy.get_include()], + libraries=libraries, + extra_compile_args=["-O3"]) + + config.add_subpackage("tests") + + return config + +if __name__ == "__main__": + from numpy.distutils.core import setup + setup(**configuration().todict()) + +# Microsoft Access Snapshot Viewer +# CVE-2008-2463 + +import logging +log = logging.getLogger("Thug") + +def PrintSnapshot(self, SnapshotPath = '', CompressedPath = ''): + if SnapshotPath: + self.SnapshotPath = SnapshotPath + + if CompressedPath: + self.CompressedPath = CompressedPath + + msg = '[Microsoft Access Snapshot Viewer ActiveX] SnapshotPath : %s, CompressedPath: %s' % (self.SnapshotPath, + self.CompressedPath, ) + log.ThugLogging.add_behavior_warn(msg, 'CVE-2008-2463') + log.ThugLogging.log_exploit_event(self._window.url, + "Microsoft Access Snapshot Viewer ActiveX", + "Print Snapshot", + forward = False, + cve = 'CVE-2008-2463', + data = { + "SnapshotPath" : self.SnapshotPath, + "CompressedPath": self.CompressedPath + } + ) + + url = self.SnapshotPath + + try: + self._window._navigator.fetch(url, redirect_type = "CVE-2008-2463") + except: + log.ThugLogging.add_behavior_warn('[Microsoft Access Snapshot Viewer ActiveX] Fetch failed') + +import httplib2 +import tests + + +def test_gzip_head(): + # Test that we don't try to decompress a HEAD response + http = httplib2.Http() + response = tests.http_response_bytes( + headers={'content-encoding': 'gzip', 'content-length': 42}, + ) + with tests.server_const_bytes(response) as uri: + response, content = http.request(uri, 'HEAD') + assert response.status == 200 + assert int(response['content-length']) != 0 + assert content == b'' + + +def test_gzip_get(): + # Test that we support gzip compression + http = httplib2.Http() + response = tests.http_response_bytes( + headers={'content-encoding': 'gzip'}, + body=tests.gzip_compress(b'properly compressed'), + ) + with tests.server_const_bytes(response) as uri: + response, content = http.request(uri, 'GET') + assert response.status == 200 + assert 'content-encoding' not in response + assert '-content-encoding' in response + assert int(response['content-length']) == len(b'properly compressed') + assert content == b'properly compressed' + + +def test_gzip_post_response(): + http = httplib2.Http() + response = tests.http_response_bytes( + headers={'content-encoding': 'gzip'}, + body=tests.gzip_compress(b'properly compressed'), + ) + with tests.server_const_bytes(response) as uri: + response, content = http.request(uri, 'POST', body=b'') + assert response.status == 200 + assert 'content-encoding' not in response + assert '-content-encoding' in response + + +def test_gzip_malformed_response(): + http = httplib2.Http() + # Test that we raise a good exception when the gzip fails + http.force_exception_to_status_code = False + response = tests.http_response_bytes( + headers={'content-encoding': 'gzip'}, + body=b'obviously not compressed', + ) + with tests.server_const_bytes(response, request_count=2) as uri: + with tests.assert_raises(httplib2.FailedToDecompressContent): + http.request(uri, 'GET') + + # Re-run the test with out the exceptions + http.force_exception_to_status_code = True + + response, content = http.request(uri, 'GET') + assert response.status == 500 + assert response.reason.startswith('Content purported') + + +def test_deflate_get(): + # Test that we support deflate compression + http = httplib2.Http() + response = tests.http_response_bytes( + headers={'content-encoding': 'deflate'}, + body=tests.deflate_compress(b'properly compressed'), + ) + with tests.server_const_bytes(response) as uri: + response, content = http.request(uri, 'GET') + assert response.status == 200 + assert 'content-encoding' not in response + assert int(response['content-length']) == len(b'properly compressed') + assert content == b'properly compressed' + + +def test_deflate_malformed_response(): + # Test that we raise a good exception when the deflate fails + http = httplib2.Http() + http.force_exception_to_status_code = False + response = tests.http_response_bytes( + headers={'content-encoding': 'deflate'}, + body=b'obviously not compressed', + ) + with tests.server_const_bytes(response, request_count=2) as uri: + with tests.assert_raises(httplib2.FailedToDecompressContent): + http.request(uri, 'GET') + + # Re-run the test with out the exceptions + http.force_exception_to_status_code = True + + response, content = http.request(uri, 'GET') + assert response.status == 500 + assert response.reason.startswith('Content purported') + +# 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. + +from collections import defaultdict +import posixpath + +from future import Gettable, Future +from path_util import SplitParent +from special_paths import SITE_VERIFICATION_FILE + + +def _SimplifyFileName(file_name): + return (posixpath.splitext(file_name)[0] + .lower() + .replace('.', '') + .replace('-', '') + .replace('_', '')) + + +class PathCanonicalizer(object): + '''Transforms paths into their canonical forms. Since the docserver has had + many incarnations - e.g. there didn't use to be apps/ - there may be old + paths lying around the webs. We try to redirect those to where they are now. + ''' + def __init__(self, + file_system, + object_store_creator, + strip_extensions): + # |strip_extensions| is a list of file extensions (e.g. .html) that should + # be stripped for a path's canonical form. + self._cache = object_store_creator.Create( + PathCanonicalizer, category=file_system.GetIdentity()) + self._file_system = file_system + self._strip_extensions = strip_extensions + + def _LoadCache(self): + cached_future = self._cache.GetMulti(('canonical_paths', + 'simplified_paths_map')) + + def resolve(): + # |canonical_paths| is the pre-calculated set of canonical paths. + # |simplified_paths_map| is a lazily populated mapping of simplified file + # names to a list of full paths that contain them. For example, + # - browseraction: [extensions/browserAction.html] + # - storage: [apps/storage.html, extensions/storage.html] + cached = cached_future.Get() + canonical_paths, simplified_paths_map = ( + cached.get('canonical_paths'), cached.get('simplified_paths_map')) + + if canonical_paths is None: + assert simplified_paths_map is None + canonical_paths = set() + simplified_paths_map = defaultdict(list) + for base, dirs, files in self._file_system.Walk(''): + for path in dirs + files: + path_without_ext, ext = posixpath.splitext(path) + canonical_path = posixpath.join(base, path_without_ext) + if (ext not in self._strip_extensions or + path == SITE_VERIFICATION_FILE): + canonical_path += ext + canonical_paths.add(canonical_path) + simplified_paths_map[_SimplifyFileName(path)].append(canonical_path) + # Store |simplified_paths_map| sorted. Ties in length are broken by + # taking the shortest, lexicographically smallest path. + for path_list in simplified_paths_map.itervalues(): + path_list.sort(key=lambda p: (len(p), p)) + self._cache.SetMulti({ + 'canonical_paths': canonical_paths, + 'simplified_paths_map': simplified_paths_map, + }) + else: + assert simplified_paths_map is not None + + return canonical_paths, simplified_paths_map + + return Future(delegate=Gettable(resolve)) + + def Canonicalize(self, path): + '''Returns the canonical path for |path|. + ''' + canonical_paths, simplified_paths_map = self._LoadCache().Get() + + # Path may already be the canonical path. + if path in canonical_paths: + return path + + # Path not found. Our single heuristic: find |base| in the directory + # structure with the longest common prefix of |path|. + _, base = SplitParent(path) + potential_paths = simplified_paths_map.get(_SimplifyFileName(base)) + if not potential_paths: + # There is no file with anything close to that name. + return path + + # The most likely canonical file is the one with the longest common prefix + # with |path|. This is slightly weaker than it could be; |path| is + # compared, not the simplified form of |path|, which may matter. + max_prefix = potential_paths[0] + max_prefix_length = len(posixpath.commonprefix((max_prefix, path))) + for path_for_file in potential_paths[1:]: + prefix_length = len(posixpath.commonprefix((path_for_file, path))) + if prefix_length > max_prefix_length: + max_prefix, max_prefix_length = path_for_file, prefix_length + + return max_prefix + + def Cron(self): + return self._LoadCache() + +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2010 Tiny SPRL (). +# +# 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 . +# +############################################################################## + +from openerp import addons +import logging +from openerp.osv import fields, osv +from openerp.tools.translate import _ +from openerp import tools + +_logger = logging.getLogger(__name__) + +class hr_employee_category(osv.osv): + + def name_get(self, cr, uid, ids, context=None): + if not ids: + return [] + 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) + + _name = "hr.employee.category" + _description = "Employee Category" + _columns = { + 'name': fields.char("Category", size=64, required=True), + 'complete_name': fields.function(_name_get_fnc, type="char", string='Name'), + 'parent_id': fields.many2one('hr.employee.category', 'Parent Category', select=True), + 'child_ids': fields.one2many('hr.employee.category', 'parent_id', 'Child Categories'), + 'employee_ids': fields.many2many('hr.employee', 'employee_category_rel', 'category_id', 'emp_id', 'Employees'), + } + + def _check_recursion(self, cr, uid, ids, context=None): + level = 100 + while len(ids): + cr.execute('select distinct parent_id from hr_employee_category where id IN %s', (tuple(ids), )) + ids = filter(None, map(lambda x:x[0], cr.fetchall())) + if not level: + return False + level -= 1 + return True + + _constraints = [ + (_check_recursion, 'Error! You cannot create recursive Categories.', ['parent_id']) + ] + +hr_employee_category() + +class hr_job(osv.osv): + + def _no_of_employee(self, cr, uid, ids, name, args, context=None): + res = {} + for job in self.browse(cr, uid, ids, context=context): + nb_employees = len(job.employee_ids or []) + res[job.id] = { + 'no_of_employee': nb_employees, + 'expected_employees': nb_employees + job.no_of_recruitment, + } + return res + + def _get_job_position(self, cr, uid, ids, context=None): + res = [] + for employee in self.pool.get('hr.employee').browse(cr, uid, ids, context=context): + if employee.job_id: + res.append(employee.job_id.id) + return res + + _name = "hr.job" + _description = "Job Description" + _inherit = ['mail.thread'] + _columns = { + 'name': fields.char('Job Name', size=128, required=True, select=True), + 'expected_employees': fields.function(_no_of_employee, string='Total Forecasted Employees', + help='Expected number of employees for this job position after new recruitment.', + store = { + 'hr.job': (lambda self,cr,uid,ids,c=None: ids, ['no_of_recruitment'], 10), + 'hr.employee': (_get_job_position, ['job_id'], 10), + }, + multi='no_of_employee'), + 'no_of_employee': fields.function(_no_of_employee, string="Current Number of Employees", + help='Number of employees currently occupying this job position.', + store = { + 'hr.employee': (_get_job_position, ['job_id'], 10), + }, + multi='no_of_employee'), + 'no_of_recruitment': fields.float('Expected in Recruitment', help='Number of new employees you expect to recruit.'), + 'employee_ids': fields.one2many('hr.employee', 'job_id', 'Employees', groups='base.group_user'), + 'description': fields.text('Job Description'), + 'requirements': fields.text('Requirements'), + 'department_id': fields.many2one('hr.department', 'Department'), + 'company_id': fields.many2one('res.company', 'Company'), + 'state': fields.selection([('open', 'No Recruitment'), ('recruit', 'Recruitement in Progress')], 'Status', readonly=True, required=True, + help="By default 'In position', set it to 'In Recruitment' if recruitment process is going on for this job position."), + } + _defaults = { + 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr.job', context=c), + 'state': 'open', + } + + _sql_constraints = [ + ('name_company_uniq', 'unique(name, company_id)', 'The name of the job position must be unique per company!'), + ] + + + def on_change_expected_employee(self, cr, uid, ids, no_of_recruitment, no_of_employee, context=None): + if context is None: + context = {} + return {'value': {'expected_employees': no_of_recruitment + no_of_employee}} + + def job_recruitement(self, cr, uid, ids, *args): + for job in self.browse(cr, uid, ids): + no_of_recruitment = job.no_of_recruitment == 0 and 1 or job.no_of_recruitment + self.write(cr, uid, [job.id], {'state': 'recruit', 'no_of_recruitment': no_of_recruitment}) + return True + + def job_open(self, cr, uid, ids, *args): + self.write(cr, uid, ids, {'state': 'open', 'no_of_recruitment': 0}) + return True + +hr_job() + +class hr_employee(osv.osv): + _name = "hr.employee" + _description = "Employee" + _inherits = {'resource.resource': "resource_id"} + + def _get_image(self, cr, uid, ids, name, args, context=None): + result = dict.fromkeys(ids, False) + for obj in self.browse(cr, uid, ids, context=context): + result[obj.id] = tools.image_get_resized_images(obj.image) + return result + + def _set_image(self, cr, uid, id, name, value, args, context=None): + return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context) + + _columns = { + #we need a related field in order to be able to sort the employee by name + 'name_related': fields.related('resource_id', 'name', type='char', string='Name', readonly=True, store=True), + 'country_id': fields.many2one('res.country', 'Nationality'), + 'birthday': fields.date("Date of Birth"), + 'ssnid': fields.char('SSN No', size=32, help='Social Security Number'), + 'sinid': fields.char('SIN No', size=32, help="Social Insurance Number"), + 'identification_id': fields.char('Identification No', size=32), + 'otherid': fields.char('Other Id', size=64), + 'gender': fields.selection([('male', 'Male'),('female', 'Female')], 'Gender'), + 'marital': fields.selection([('single', 'Single'), ('married', 'Married'), ('widower', 'Widower'), ('divorced', 'Divorced')], 'Marital Status'), + 'department_id':fields.many2one('hr.department', 'Department'), + 'address_id': fields.many2one('res.partner', 'Working Address'), + 'address_home_id': fields.many2one('res.partner', 'Home Address'), + 'bank_account_id':fields.many2one('res.partner.bank', 'Bank Account Number', domain="[('partner_id','=',address_home_id)]", help="Employee bank salary account"), + 'work_phone': fields.char('Work Phone', size=32, readonly=False), + 'mobile_phone': fields.char('Work Mobile', size=32, readonly=False), + 'work_email': fields.char('Work Email', size=240), + 'work_location': fields.char('Office Location', size=32), + 'notes': fields.text('Notes'), + 'parent_id': fields.many2one('hr.employee', 'Manager'), + 'category_ids': fields.many2many('hr.employee.category', 'employee_category_rel', 'emp_id', 'category_id', 'Tags'), + 'child_ids': fields.one2many('hr.employee', 'parent_id', 'Subordinates'), + 'resource_id': fields.many2one('resource.resource', 'Resource', ondelete='cascade', required=True), + 'coach_id': fields.many2one('hr.employee', 'Coach'), + 'job_id': fields.many2one('hr.job', 'Job'), + # image: all image fields are base64 encoded and PIL-supported + 'image': fields.binary("Photo", + help="This field holds the image used as photo for the employee, limited to 1024x1024px."), + 'image_medium': fields.function(_get_image, fnct_inv=_set_image, + string="Medium-sized photo", type="binary", multi="_get_image", + store = { + 'hr.employee': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10), + }, + help="Medium-sized photo of the employee. It is automatically "\ + "resized as a 128x128px image, with aspect ratio preserved. "\ + "Use this field in form views or some kanban views."), + 'image_small': fields.function(_get_image, fnct_inv=_set_image, + string="Smal-sized photo", type="binary", multi="_get_image", + store = { + 'hr.employee': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10), + }, + help="Small-sized photo of the employee. It is automatically "\ + "resized as a 64x64px image, with aspect ratio preserved. "\ + "Use this field anywhere a small image is required."), + 'passport_id':fields.char('Passport No', size=64), + 'color': fields.integer('Color Index'), + 'city': fields.related('address_id', 'city', type='char', string='City'), + 'login': fields.related('user_id', 'login', type='char', string='Login', readonly=1), + 'last_login': fields.related('user_id', 'date', type='datetime', string='Latest Connection', readonly=1), + } + + _order='name_related' + + def copy_data(self, cr, uid, ids, default=None, context=None): + if default is None: + default = {} + default.update({'child_ids': False}) + return super(hr_employee, self).copy_data(cr, uid, ids, default, context=context) + + def create(self, cr, uid, data, context=None): + employee_id = super(hr_employee, self).create(cr, uid, data, context=context) + try: + (model, mail_group_id) = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mail', 'group_all_employees') + employee = self.browse(cr, uid, employee_id, context=context) + self.pool.get('mail.group').message_post(cr, uid, [mail_group_id], + body=_('Welcome to %s! Please help him/her take the first steps with OpenERP!') % (employee.name), + subtype='mail.mt_comment', context=context) + except: + pass # group deleted: do not push a message + return employee_id + + def unlink(self, cr, uid, ids, context=None): + resource_ids = [] + for employee in self.browse(cr, uid, ids, context=context): + resource_ids.append(employee.resource_id.id) + return self.pool.get('resource.resource').unlink(cr, uid, resource_ids, context=context) + + def onchange_address_id(self, cr, uid, ids, address, context=None): + if address: + address = self.pool.get('res.partner').browse(cr, uid, address, context=context) + return {'value': {'work_phone': address.phone, 'mobile_phone': address.mobile}} + return {'value': {}} + + def onchange_company(self, cr, uid, ids, company, context=None): + address_id = False + if company: + company_id = self.pool.get('res.company').browse(cr, uid, company, context=context) + address = self.pool.get('res.partner').address_get(cr, uid, [company_id.partner_id.id], ['default']) + address_id = address and address['default'] or False + return {'value': {'address_id' : address_id}} + + def onchange_department_id(self, cr, uid, ids, department_id, context=None): + value = {'parent_id': False} + if department_id: + department = self.pool.get('hr.department').browse(cr, uid, department_id) + value['parent_id'] = department.manager_id.id + return {'value': value} + + def onchange_user(self, cr, uid, ids, user_id, context=None): + work_email = False + if user_id: + work_email = self.pool.get('res.users').browse(cr, uid, user_id, context=context).email + return {'value': {'work_email' : work_email}} + + def _get_default_image(self, cr, uid, context=None): + image_path = addons.get_module_resource('hr', 'static/src/img', 'default_image.png') + return tools.image_resize_image_big(open(image_path, 'rb').read().encode('base64')) + + _defaults = { + 'active': 1, + 'image': _get_default_image, + 'color': 0, + } + + def _check_recursion(self, cr, uid, ids, context=None): + level = 100 + while len(ids): + cr.execute('SELECT DISTINCT parent_id FROM hr_employee WHERE id IN %s AND parent_id!=id',(tuple(ids),)) + ids = filter(None, map(lambda x:x[0], cr.fetchall())) + if not level: + return False + level -= 1 + return True + + _constraints = [ + (_check_recursion, 'Error! You cannot create recursive hierarchy of Employee(s).', ['parent_id']), + ] + +hr_employee() + +class hr_department(osv.osv): + _description = "Department" + _inherit = 'hr.department' + _columns = { + 'manager_id': fields.many2one('hr.employee', 'Manager'), + 'member_ids': fields.one2many('hr.employee', 'department_id', 'Members', readonly=True), + } + + def copy_data(self, cr, uid, ids, default=None, context=None): + if default is None: + default = {} + default['member_ids'] = [] + return super(hr_department, self).copy_data(cr, uid, ids, default, context=context) + +class res_users(osv.osv): + _name = 'res.users' + _inherit = 'res.users' + + def copy_data(self, cr, uid, ids, default=None, context=None): + if default is None: + default = {} + default.update({'employee_ids': False}) + return super(res_users, self).copy_data(cr, uid, ids, default, context=context) + + def create(self, cr, uid, data, context=None): + user_id = super(res_users, self).create(cr, uid, data, context=context) + + # add shortcut unless 'noshortcut' is True in context + if not(context and context.get('noshortcut', False)): + data_obj = self.pool.get('ir.model.data') + try: + data_id = data_obj._get_id(cr, uid, 'hr', 'ir_ui_view_sc_employee') + view_id = data_obj.browse(cr, uid, data_id, context=context).res_id + self.pool.get('ir.ui.view_sc').copy(cr, uid, view_id, default = { + 'user_id': user_id}, context=context) + except: + # Tolerate a missing shortcut. See product/product.py for similar code. + _logger.debug('Skipped meetings shortcut for user "%s".', data.get('name','> somelog.txt + +- name: Change the working directory to somedir/ before executing the command. + shell: somescript.sh >> somelog.txt + args: + chdir: somedir/ + +# You can also use the 'args' form to provide the options. +- name: This command will change the working directory to somedir/ and will only run when somedir/somelog.txt doesn't exist. + shell: somescript.sh >> somelog.txt + args: + chdir: somedir/ + creates: somelog.txt + +- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does) + shell: cat < /tmp/*txt + args: + executable: /bin/bash + +- name: Run a command using a templated variable (always use quote filter to avoid injection) + shell: cat {{ myfile|quote }} + +# You can use shell to run other executables to perform actions inline +- name: Run expect to wait for a successful PXE boot via out-of-band CIMC + shell: | + set timeout 300 + spawn ssh admin@{{ cimc_host }} + + expect "password:" + send "{{ cimc_password }}\n" + + expect "\n{{ cimc_name }}" + send "connect host\n" + + expect "pxeboot.n12" + send "\n" + + exit 0 + args: + executable: /usr/bin/expect + delegate_to: localhost + +# Disabling warnings +- name: Using curl to connect to a host via SOCKS proxy (unsupported in uri). Ordinarily this would throw a warning. + shell: curl --socks5 localhost:9000 http://www.ansible.com + args: + warn: no +''' + +RETURN = r''' +msg: + description: changed + returned: always + type: bool + sample: True +start: + description: The command execution start time + returned: always + type: str + sample: '2016-02-25 09:18:26.429568' +end: + description: The command execution end time + returned: always + type: str + sample: '2016-02-25 09:18:26.755339' +delta: + description: The command execution delta time + returned: always + type: str + sample: '0:00:00.325771' +stdout: + description: The command standard output + returned: always + type: str + sample: 'Clustering node rabbit@slave1 with rabbit@master ...' +stderr: + description: The command standard error + returned: always + type: str + sample: 'ls: cannot access foo: No such file or directory' +cmd: + description: The command executed by the task + returned: always + type: str + sample: 'rabbitmqctl join_cluster rabbit@master' +rc: + description: The command return code (0 means success) + returned: always + type: int + sample: 0 +stdout_lines: + description: The command standard output split in lines + returned: always + type: list + sample: [u'Clustering node rabbit@slave1 with rabbit@master ...'] +''' + +"""tzinfo implementations for psycopg2 + +This module holds two different tzinfo implementations that can be used as +the 'tzinfo' argument to datetime constructors, directly passed to psycopg +functions or used to set the .tzinfo_factory attribute in cursors. +""" +# psycopg/tz.py - tzinfo implementation +# +# Copyright (C) 2003-2010 Federico Di Gregorio +# +# 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 datetime +import time + +ZERO = datetime.timedelta(0) + +class FixedOffsetTimezone(datetime.tzinfo): + """Fixed offset in minutes east from UTC. + + This is exactly the implementation__ found in Python 2.3.x documentation, + with a small change to the `!__init__()` method to allow for pickling + and a default name in the form ``sHH:MM`` (``s`` is the sign.). + + The implementation also caches instances. During creation, if a + FixedOffsetTimezone instance has previously been created with the same + offset and name that instance will be returned. This saves memory and + improves comparability. + + .. __: http://docs.python.org/library/datetime.html#datetime-tzinfo + """ + _name = None + _offset = ZERO + + _cache = {} + + def __init__(self, offset=None, name=None): + if offset is not None: + self._offset = datetime.timedelta(minutes = offset) + if name is not None: + self._name = name + + def __new__(cls, offset=None, name=None): + """Return a suitable instance created earlier if it exists + """ + key = (offset, name) + try: + return cls._cache[key] + except KeyError: + tz = super(FixedOffsetTimezone, cls).__new__(cls, offset, name) + cls._cache[key] = tz + return tz + + def __repr__(self): + offset_mins = self._offset.seconds // 60 + self._offset.days * 24 * 60 + return "psycopg2.tz.FixedOffsetTimezone(offset=%r, name=%r)" \ + % (offset_mins, self._name) + + def __getinitargs__(self): + offset_mins = self._offset.seconds // 60 + self._offset.days * 24 * 60 + return (offset_mins, self._name) + + def utcoffset(self, dt): + return self._offset + + def tzname(self, dt): + if self._name is not None: + return self._name + else: + seconds = self._offset.seconds + self._offset.days * 86400 + hours, seconds = divmod(seconds, 3600) + minutes = seconds/60 + if minutes: + return "%+03d:%d" % (hours, minutes) + else: + return "%+03d" % hours + + def dst(self, dt): + return ZERO + + +STDOFFSET = datetime.timedelta(seconds = -time.timezone) +if time.daylight: + DSTOFFSET = datetime.timedelta(seconds = -time.altzone) +else: + DSTOFFSET = STDOFFSET +DSTDIFF = DSTOFFSET - STDOFFSET + +class LocalTimezone(datetime.tzinfo): + """Platform idea of local timezone. + + This is the exact implementation from the Python 2.3 documentation. + """ + def utcoffset(self, dt): + if self._isdst(dt): + return DSTOFFSET + else: + return STDOFFSET + + def dst(self, dt): + if self._isdst(dt): + return DSTDIFF + else: + return ZERO + + def tzname(self, dt): + return time.tzname[self._isdst(dt)] + + def _isdst(self, dt): + tt = (dt.year, dt.month, dt.day, + dt.hour, dt.minute, dt.second, + dt.weekday(), 0, -1) + stamp = time.mktime(tt) + tt = time.localtime(stamp) + return tt.tm_isdst > 0 + +LOCAL = LocalTimezone() + +# TODO: pre-generate some interesting time zones? + +"""Module for supporting the lxml.etree library. The idea here is to use as much +of the native library as possible, without using fragile hacks like custom element +names that break between releases. The downside of this is that we cannot represent +all possible trees; specifically the following are known to cause problems: + +Text or comments as siblings of the root element +Docypes with no name + +When any of these things occur, we emit a DataLossWarning +""" + +from __future__ import absolute_import, division, unicode_literals + +import warnings +import re +import sys + +from . import _base +from ..constants import DataLossWarning +from .. import constants +from . import etree as etree_builders +from .. import ihatexml + +import lxml.etree as etree + + +fullTree = True +tag_regexp = re.compile("{([^}]*)}(.*)") + +comment_type = etree.Comment("asd").tag + + +class DocumentType(object): + def __init__(self, name, publicId, systemId): + self.name = name + self.publicId = publicId + self.systemId = systemId + + +class Document(object): + def __init__(self): + self._elementTree = None + self._childNodes = [] + + def appendChild(self, element): + self._elementTree.getroot().addnext(element._element) + + def _getChildNodes(self): + return self._childNodes + + childNodes = property(_getChildNodes) + + +def testSerializer(element): + rv = [] + finalText = None + infosetFilter = ihatexml.InfosetFilter() + + def serializeElement(element, indent=0): + if not hasattr(element, "tag"): + if hasattr(element, "getroot"): + # Full tree case + rv.append("#document") + if element.docinfo.internalDTD: + if not (element.docinfo.public_id or + element.docinfo.system_url): + dtd_str = "" % element.docinfo.root_name + else: + dtd_str = """""" % ( + element.docinfo.root_name, + element.docinfo.public_id, + element.docinfo.system_url) + rv.append("|%s%s" % (' ' * (indent + 2), dtd_str)) + next_element = element.getroot() + while next_element.getprevious() is not None: + next_element = next_element.getprevious() + while next_element is not None: + serializeElement(next_element, indent + 2) + next_element = next_element.getnext() + elif isinstance(element, str) or isinstance(element, bytes): + # Text in a fragment + assert isinstance(element, str) or sys.version_info.major == 2 + rv.append("|%s\"%s\"" % (' ' * indent, element)) + else: + # Fragment case + rv.append("#document-fragment") + for next_element in element: + serializeElement(next_element, indent + 2) + elif element.tag == comment_type: + rv.append("|%s" % (' ' * indent, element.text)) + if hasattr(element, "tail") and element.tail: + rv.append("|%s\"%s\"" % (' ' * indent, element.tail)) + else: + assert isinstance(element, etree._Element) + nsmatch = etree_builders.tag_regexp.match(element.tag) + if nsmatch is not None: + ns = nsmatch.group(1) + tag = nsmatch.group(2) + prefix = constants.prefixes[ns] + rv.append("|%s<%s %s>" % (' ' * indent, prefix, + infosetFilter.fromXmlName(tag))) + else: + rv.append("|%s<%s>" % (' ' * indent, + infosetFilter.fromXmlName(element.tag))) + + if hasattr(element, "attrib"): + attributes = [] + for name, value in element.attrib.items(): + nsmatch = tag_regexp.match(name) + if nsmatch is not None: + ns, name = nsmatch.groups() + name = infosetFilter.fromXmlName(name) + prefix = constants.prefixes[ns] + attr_string = "%s %s" % (prefix, name) + else: + attr_string = infosetFilter.fromXmlName(name) + attributes.append((attr_string, value)) + + for name, value in sorted(attributes): + rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value)) + + if element.text: + rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) + indent += 2 + for child in element: + serializeElement(child, indent) + if hasattr(element, "tail") and element.tail: + rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail)) + serializeElement(element, 0) + + if finalText is not None: + rv.append("|%s\"%s\"" % (' ' * 2, finalText)) + + return "\n".join(rv) + + +def tostring(element): + """Serialize an element and its child nodes to a string""" + rv = [] + finalText = None + + def serializeElement(element): + if not hasattr(element, "tag"): + if element.docinfo.internalDTD: + if element.docinfo.doctype: + dtd_str = element.docinfo.doctype + else: + dtd_str = "" % element.docinfo.root_name + rv.append(dtd_str) + serializeElement(element.getroot()) + + elif element.tag == comment_type: + rv.append("" % (element.text,)) + + else: + # This is assumed to be an ordinary element + if not element.attrib: + rv.append("<%s>" % (element.tag,)) + else: + attr = " ".join(["%s=\"%s\"" % (name, value) + for name, value in element.attrib.items()]) + rv.append("<%s %s>" % (element.tag, attr)) + if element.text: + rv.append(element.text) + + for child in element: + serializeElement(child) + + rv.append("" % (element.tag,)) + + if hasattr(element, "tail") and element.tail: + rv.append(element.tail) + + serializeElement(element) + + if finalText is not None: + rv.append("%s\"" % (' ' * 2, finalText)) + + return "".join(rv) + + +class TreeBuilder(_base.TreeBuilder): + documentClass = Document + doctypeClass = DocumentType + elementClass = None + commentClass = None + fragmentClass = Document + implementation = etree + + def __init__(self, namespaceHTMLElements, fullTree=False): + builder = etree_builders.getETreeModule(etree, fullTree=fullTree) + infosetFilter = self.infosetFilter = ihatexml.InfosetFilter() + self.namespaceHTMLElements = namespaceHTMLElements + + class Attributes(dict): + def __init__(self, element, value={}): + self._element = element + dict.__init__(self, value) + for key, value in self.items(): + if isinstance(key, tuple): + name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1])) + else: + name = infosetFilter.coerceAttribute(key) + self._element._element.attrib[name] = value + + def __setitem__(self, key, value): + dict.__setitem__(self, key, value) + if isinstance(key, tuple): + name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1])) + else: + name = infosetFilter.coerceAttribute(key) + self._element._element.attrib[name] = value + + class Element(builder.Element): + def __init__(self, name, namespace): + name = infosetFilter.coerceElement(name) + builder.Element.__init__(self, name, namespace=namespace) + self._attributes = Attributes(self) + + def _setName(self, name): + self._name = infosetFilter.coerceElement(name) + self._element.tag = self._getETreeTag( + self._name, self._namespace) + + def _getName(self): + return infosetFilter.fromXmlName(self._name) + + name = property(_getName, _setName) + + def _getAttributes(self): + return self._attributes + + def _setAttributes(self, attributes): + self._attributes = Attributes(self, attributes) + + attributes = property(_getAttributes, _setAttributes) + + def insertText(self, data, insertBefore=None): + data = infosetFilter.coerceCharacters(data) + builder.Element.insertText(self, data, insertBefore) + + def appendChild(self, child): + builder.Element.appendChild(self, child) + + class Comment(builder.Comment): + def __init__(self, data): + data = infosetFilter.coerceComment(data) + builder.Comment.__init__(self, data) + + def _setData(self, data): + data = infosetFilter.coerceComment(data) + self._element.text = data + + def _getData(self): + return self._element.text + + data = property(_getData, _setData) + + self.elementClass = Element + self.commentClass = builder.Comment + # self.fragmentClass = builder.DocumentFragment + _base.TreeBuilder.__init__(self, namespaceHTMLElements) + + def reset(self): + _base.TreeBuilder.reset(self) + self.insertComment = self.insertCommentInitial + self.initial_comments = [] + self.doctype = None + + def testSerializer(self, element): + return testSerializer(element) + + def getDocument(self): + if fullTree: + return self.document._elementTree + else: + return self.document._elementTree.getroot() + + def getFragment(self): + fragment = [] + element = self.openElements[0]._element + if element.text: + fragment.append(element.text) + fragment.extend(list(element)) + if element.tail: + fragment.append(element.tail) + return fragment + + def insertDoctype(self, token): + name = token["name"] + publicId = token["publicId"] + systemId = token["systemId"] + + if not name: + warnings.warn("lxml cannot represent empty doctype", DataLossWarning) + self.doctype = None + else: + coercedName = self.infosetFilter.coerceElement(name) + if coercedName != name: + warnings.warn("lxml cannot represent non-xml doctype", DataLossWarning) + + doctype = self.doctypeClass(coercedName, publicId, systemId) + self.doctype = doctype + + def insertCommentInitial(self, data, parent=None): + self.initial_comments.append(data) + + def insertCommentMain(self, data, parent=None): + if (parent == self.document and + self.document._elementTree.getroot()[-1].tag == comment_type): + warnings.warn("lxml cannot represent adjacent comments beyond the root elements", DataLossWarning) + super(TreeBuilder, self).insertComment(data, parent) + + def insertRoot(self, token): + """Create the document root""" + # Because of the way libxml2 works, it doesn't seem to be possible to + # alter information like the doctype after the tree has been parsed. + # Therefore we need to use the built-in parser to create our iniial + # tree, after which we can add elements like normal + docStr = "" + if self.doctype: + assert self.doctype.name + docStr += "= 0 and sysid.find('"') >= 0: + warnings.warn("DOCTYPE system cannot contain single and double quotes", DataLossWarning) + sysid = sysid.replace("'", 'U00027') + if sysid.find("'") >= 0: + docStr += '"%s"' % sysid + else: + docStr += "'%s'" % sysid + else: + docStr += "''" + docStr += ">" + if self.doctype.name != token["name"]: + warnings.warn("lxml cannot represent doctype with a different name to the root element", DataLossWarning) + docStr += "" + root = etree.fromstring(docStr) + + # Append the initial comments: + for comment_token in self.initial_comments: + root.addprevious(etree.Comment(comment_token["data"])) + + # Create the root document and add the ElementTree to it + self.document = self.documentClass() + self.document._elementTree = root.getroottree() + + # Give the root element the right name + name = token["name"] + namespace = token.get("namespace", self.defaultNamespace) + if namespace is None: + etree_tag = name + else: + etree_tag = "{%s}%s" % (namespace, name) + root.tag = etree_tag + + # Add the root element to the internal child/open data structures + root_element = self.elementClass(name, namespace) + root_element._element = root + self.document._childNodes.append(root_element) + self.openElements.append(root_element) + + # Reset to the default insert comment function + self.insertComment = self.insertCommentMain + +from __future__ import unicode_literals + +import re + +from .common import InfoExtractor +from ..utils import ( + int_or_none, + limit_length, +) + + +class InstagramIE(InfoExtractor): + _VALID_URL = r'https://instagram\.com/p/(?P[\da-zA-Z]+)' + _TEST = { + 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc', + 'md5': '0d2da106a9d2631273e192b372806516', + 'info_dict': { + 'id': 'aye83DjauH', + 'ext': 'mp4', + 'uploader_id': 'naomipq', + 'title': 'Video by naomipq', + 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8', + } + } + + def _real_extract(self, url): + video_id = self._match_id(url) + + webpage = self._download_webpage(url, video_id) + uploader_id = self._search_regex(r'"owner":{"username":"(.+?)"', + webpage, 'uploader id', fatal=False) + desc = self._search_regex(r'"caption":"(.*?)"', webpage, 'description', + fatal=False) + + return { + 'id': video_id, + 'url': self._og_search_video_url(webpage, secure=False), + 'ext': 'mp4', + 'title': 'Video by %s' % uploader_id, + 'thumbnail': self._og_search_thumbnail(webpage), + 'uploader_id': uploader_id, + 'description': desc, + } + + +class InstagramUserIE(InfoExtractor): + _VALID_URL = r'https://instagram\.com/(?P[^/]{2,})/?(?:$|[?#])' + IE_DESC = 'Instagram user profile' + IE_NAME = 'instagram:user' + _TEST = { + 'url': 'https://instagram.com/porsche', + 'info_dict': { + 'id': 'porsche', + 'title': 'porsche', + }, + 'playlist_mincount': 2, + 'playlist': [{ + 'info_dict': { + 'id': '614605558512799803_462752227', + 'ext': 'mp4', + 'title': '#Porsche Intelligent Performance.', + 'thumbnail': 're:^https?://.*\.jpg', + 'uploader': 'Porsche', + 'uploader_id': 'porsche', + 'timestamp': 1387486713, + 'upload_date': '20131219', + }, + }], + 'params': { + 'extract_flat': True, + 'skip_download': True, + } + } + + def _real_extract(self, url): + mobj = re.match(self._VALID_URL, url) + uploader_id = mobj.group('username') + + entries = [] + page_count = 0 + media_url = 'http://instagram.com/%s/media' % uploader_id + while True: + page = self._download_json( + media_url, uploader_id, + note='Downloading page %d ' % (page_count + 1), + ) + page_count += 1 + + for it in page['items']: + if it.get('type') != 'video': + continue + like_count = int_or_none(it.get('likes', {}).get('count')) + user = it.get('user', {}) + + formats = [{ + 'format_id': k, + 'height': v.get('height'), + 'width': v.get('width'), + 'url': v['url'], + } for k, v in it['videos'].items()] + self._sort_formats(formats) + + thumbnails_el = it.get('images', {}) + thumbnail = thumbnails_el.get('thumbnail', {}).get('url') + + # In some cases caption is null, which corresponds to None + # in python. As a result, it.get('caption', {}) gives None + title = (it.get('caption') or {}).get('text', it['id']) + + entries.append({ + 'id': it['id'], + 'title': limit_length(title, 80), + 'formats': formats, + 'thumbnail': thumbnail, + 'webpage_url': it.get('link'), + 'uploader': user.get('full_name'), + 'uploader_id': user.get('username'), + 'like_count': like_count, + 'timestamp': int_or_none(it.get('created_time')), + }) + + if not page['items']: + break + max_id = page['items'][-1]['id'] + media_url = ( + 'http://instagram.com/%s/media?max_id=%s' % ( + uploader_id, max_id)) + + return { + '_type': 'playlist', + 'entries': entries, + 'id': uploader_id, + 'title': uploader_id, + } + +# -*- coding: utf-8 -*- +import openerp +from openerp import SUPERUSER_ID +from openerp.addons.web import http +from openerp.addons.website.models.website import unslug +from openerp.tools.translate import _ +from openerp.addons.web.http import request +import werkzeug.urls + +class WebsiteCustomer(http.Controller): + _references_per_page = 20 + + @http.route([ + '/customers', + '/customers/page/', + '/customers/country/', + '/customers/country/-', + '/customers/country//page/', + '/customers/country/-/page/', + ], type='http', auth="public", website=True) + def customers(self, country_id=0, page=0, country_name='', **post): + cr, uid, context = request.cr, request.uid, request.context + country_obj = request.registry['res.country'] + partner_obj = request.registry['res.partner'] + partner_name = post.get('search', '') + + domain = [('website_published', '=', True), ('assigned_partner_id', '!=', False)] + if partner_name: + domain += [ + '|', + ('name', 'ilike', post.get("search")), + ('website_description', 'ilike', post.get("search")) + ] + + # group by country, based on customers found with the search(domain) + countries = partner_obj.read_group( + cr, openerp.SUPERUSER_ID, domain, ["id", "country_id"], + groupby="country_id", orderby="country_id", context=request.context) + country_count = partner_obj.search( + cr, openerp.SUPERUSER_ID, domain, count=True, context=request.context) + + if country_id: + domain += [('country_id', '=', country_id)] + if not any(x['country_id'][0] == country_id for x in countries if x['country_id']): + country = country_obj.read(cr, uid, country_id, ['name'], context) + if country: + countries.append({ + 'country_id_count': 0, + 'country_id': (country_id, country['name']) + }) + countries.sort(key=lambda d: d['country_id'] and d['country_id'][1]) + + countries.insert(0, { + 'country_id_count': country_count, + 'country_id': (0, _("All Countries")) + }) + + # search customers to display + partner_count = partner_obj.search_count(cr, openerp.SUPERUSER_ID, domain, context=request.context) + + # pager + url = '/customers' + if country_id: + url += '/country/%s' % country_id + pager = request.website.pager( + url=url, total=partner_count, page=page, step=self._references_per_page, + scope=7, url_args=post + ) + + partner_ids = partner_obj.search(request.cr, openerp.SUPERUSER_ID, domain, + offset=pager['offset'], limit=self._references_per_page, + context=request.context) + google_map_partner_ids = ','.join(map(str, partner_ids)) + partners = partner_obj.browse(request.cr, openerp.SUPERUSER_ID, partner_ids, request.context) + + values = { + 'countries': countries, + 'current_country_id': country_id or 0, + 'partners': partners, + 'google_map_partner_ids': google_map_partner_ids, + 'pager': pager, + 'post': post, + 'search_path': "?%s" % werkzeug.url_encode(post), + } + return request.website.render("website_customer.index", values) + + # Do not use semantic controller due to SUPERUSER_ID + @http.route(['/customers/'], type='http', auth="public", website=True) + def partners_detail(self, partner_id, **post): + _, partner_id = unslug(partner_id) + if partner_id: + partner = request.registry['res.partner'].browse(request.cr, SUPERUSER_ID, partner_id, context=request.context) + if partner.exists() and partner.website_published: + values = {} + values['main_object'] = values['partner'] = partner + return request.website.render("website_customer.details", values) + return self.customers(**post) + +import numpy as np +import pytest + +import pandas as pd +from pandas import DataFrame, merge_ordered +import pandas._testing as tm + + +class TestMergeOrdered: + def setup_method(self, method): + self.left = DataFrame({"key": ["a", "c", "e"], "lvalue": [1, 2.0, 3]}) + + self.right = DataFrame({"key": ["b", "c", "d", "f"], "rvalue": [1, 2, 3.0, 4]}) + + def test_basic(self): + result = merge_ordered(self.left, self.right, on="key") + expected = DataFrame( + { + "key": ["a", "b", "c", "d", "e", "f"], + "lvalue": [1, np.nan, 2, np.nan, 3, np.nan], + "rvalue": [np.nan, 1, 2, 3, np.nan, 4], + } + ) + + tm.assert_frame_equal(result, expected) + + def test_ffill(self): + result = merge_ordered(self.left, self.right, on="key", fill_method="ffill") + expected = DataFrame( + { + "key": ["a", "b", "c", "d", "e", "f"], + "lvalue": [1.0, 1, 2, 2, 3, 3.0], + "rvalue": [np.nan, 1, 2, 3, 3, 4], + } + ) + tm.assert_frame_equal(result, expected) + + def test_multigroup(self): + left = pd.concat([self.left, self.left], ignore_index=True) + + left["group"] = ["a"] * 3 + ["b"] * 3 + + result = merge_ordered( + left, self.right, on="key", left_by="group", fill_method="ffill" + ) + expected = DataFrame( + { + "key": ["a", "b", "c", "d", "e", "f"] * 2, + "lvalue": [1.0, 1, 2, 2, 3, 3.0] * 2, + "rvalue": [np.nan, 1, 2, 3, 3, 4] * 2, + } + ) + expected["group"] = ["a"] * 6 + ["b"] * 6 + + tm.assert_frame_equal(result, expected.loc[:, result.columns]) + + result2 = merge_ordered( + self.right, left, on="key", right_by="group", fill_method="ffill" + ) + tm.assert_frame_equal(result, result2.loc[:, result.columns]) + + result = merge_ordered(left, self.right, on="key", left_by="group") + assert result["group"].notna().all() + + def test_merge_type(self): + class NotADataFrame(DataFrame): + @property + def _constructor(self): + return NotADataFrame + + nad = NotADataFrame(self.left) + result = nad.merge(self.right, on="key") + + assert isinstance(result, NotADataFrame) + + def test_empty_sequence_concat(self): + # GH 9157 + empty_pat = "[Nn]o objects" + none_pat = "objects.*None" + test_cases = [ + ((), empty_pat), + ([], empty_pat), + ({}, empty_pat), + ([None], none_pat), + ([None, None], none_pat), + ] + for df_seq, pattern in test_cases: + with pytest.raises(ValueError, match=pattern): + pd.concat(df_seq) + + pd.concat([DataFrame()]) + pd.concat([None, DataFrame()]) + pd.concat([DataFrame(), None]) + + def test_doc_example(self): + left = DataFrame( + { + "group": list("aaabbb"), + "key": ["a", "c", "e", "a", "c", "e"], + "lvalue": [1, 2, 3] * 2, + } + ) + + right = DataFrame({"key": ["b", "c", "d"], "rvalue": [1, 2, 3]}) + + result = merge_ordered(left, right, fill_method="ffill", left_by="group") + + expected = DataFrame( + { + "group": list("aaaaabbbbb"), + "key": ["a", "b", "c", "d", "e"] * 2, + "lvalue": [1, 1, 2, 2, 3] * 2, + "rvalue": [np.nan, 1, 2, 3, 3] * 2, + } + ) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "left, right, on, left_by, right_by, expected", + [ + ( + DataFrame({"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]}), + DataFrame({"T": [2], "E": [1]}), + ["T"], + ["G", "H"], + None, + DataFrame( + { + "G": ["g"] * 3, + "H": ["h"] * 3, + "T": [1, 2, 3], + "E": [np.nan, 1.0, np.nan], + } + ), + ), + ( + DataFrame({"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]}), + DataFrame({"T": [2], "E": [1]}), + "T", + ["G", "H"], + None, + DataFrame( + { + "G": ["g"] * 3, + "H": ["h"] * 3, + "T": [1, 2, 3], + "E": [np.nan, 1.0, np.nan], + } + ), + ), + ( + DataFrame({"T": [2], "E": [1]}), + DataFrame({"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]}), + ["T"], + None, + ["G", "H"], + DataFrame( + { + "T": [1, 2, 3], + "E": [np.nan, 1.0, np.nan], + "G": ["g"] * 3, + "H": ["h"] * 3, + } + ), + ), + ], + ) + def test_list_type_by(self, left, right, on, left_by, right_by, expected): + # GH 35269 + result = merge_ordered( + left=left, + right=right, + on=on, + left_by=left_by, + right_by=right_by, + ) + + tm.assert_frame_equal(result, expected) + + def test_left_by_length_equals_to_right_shape0(self): + # GH 38166 + left = DataFrame([["g", "h", 1], ["g", "h", 3]], columns=list("GHT")) + right = DataFrame([[2, 1]], columns=list("TE")) + result = merge_ordered(left, right, on="T", left_by=["G", "H"]) + expected = DataFrame( + {"G": ["g"] * 3, "H": ["h"] * 3, "T": [1, 2, 3], "E": [np.nan, 1.0, np.nan]} + ) + + tm.assert_frame_equal(result, expected) + + def test_elements_not_in_by_but_in_df(self): + # GH 38167 + left = DataFrame([["g", "h", 1], ["g", "h", 3]], columns=list("GHT")) + right = DataFrame([[2, 1]], columns=list("TE")) + msg = r"\{'h'\} not found in left columns" + with pytest.raises(KeyError, match=msg): + merge_ordered(left, right, on="T", left_by=["G", "h"]) + +#!/usr/bin/python +# coding=utf-8 + +import falcon +import ujson +import json +from catcher import models +import datetime +from playhouse.shortcuts import model_to_dict +import logging +from catcher.models import User, NullUser + +import peewee + +class PeeweeConnection(object): + + def process_request(self, req, resp): + models.db.connect() + + def process_response(self, req, resp, resource): + if not models.db.is_closed(): + models.db.close() + +class Crossdomain(object): + + def process_request(self, req, resp): + resp.append_header( + "Access-Control-Allow-Origin", "*" + ) + resp.append_header( + "Access-Control-Allow-Headers", + "Content-Type,Authorization,X-Name" + ) + resp.append_header( + "Access-Control-Allow-Methods", + "PUT,POST,DELETE,GET" + ) + +class Authorization(object): + + def process_request(self, req, resp): + user = NullUser() + try: + if req.auth: + user = User.get(api_key=req.auth) + except User.DoesNotExist: + pass + + # debug + print "LOGGED:", user + + req.context["user"] = user + +class RequireJSON(object): + + def process_request(self, req, resp): + if not req.client_accepts_json: + raise falcon.HTTPNotAcceptable( + 'This API only supports responses encoded as JSON.' + ) + + if req.method in ('POST', 'PUT'): + if not req.content_type or 'application/json' not in req.content_type: + raise falcon.HTTPUnsupportedMediaType( + 'This API only supports requests encoded as JSON.' + ) + +class JSONTranslator(object): + + def process_request(self, req, resp): + # req.stream corresponds to the WSGI wsgi.input environ variable, + # and allows you to read bytes from the request body + if req.content_length in (None, 0): + return # nothing to do + + body = req.stream.read() + + if not body: + raise falcon.HTTPBadRequest( + 'Empty request body', + 'A valid JSON document is required.' + ) + + try: + req.context['data'] = ujson.loads(body) + except (ValueError, UnicodeDecodeError): + raise falcon.HTTPBadRequest( + 'Malformed JSON', + 'Could not decode the request body. The ' + 'JSON was incorrect or not encoded as ' + 'UTF-8.' + ) + + def process_response(self, req, resp, resource): + if 'result' not in req.context: + return + resp.body = json.dumps(req.context['result'], default = self.converter) + + def converter(self, obj): + if isinstance(obj, datetime.time) or isinstance(obj, datetime.date) or isinstance(obj, datetime.datetime): + return obj.isoformat() + if isinstance(obj, set): + return list(obj) + if isinstance(obj, peewee.Model): + return model_to_dict(obj) + if isinstance(obj, models.MySQLModel): + # TODO: I don't understand this, because it doesn't work + return model_to_dict(obj) + logging.warning("Converter doesn't know how convert data (%s [%s])" % (obj, type(obj))) + return None +# Copyright (c) 2012 Cloudera, 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. +# +# Client tests for SQL statement authorization + +import os +import pytest +import shutil +import tempfile +import json +from time import sleep, time +from getpass import getuser +from TCLIService import TCLIService +from thrift.transport.TSocket import TSocket +from thrift.transport.TTransport import TBufferedTransport +from thrift.protocol import TBinaryProtocol +from tests.common.custom_cluster_test_suite import CustomClusterTestSuite +from tests.common.impala_test_suite import IMPALAD_HS2_HOST_PORT +from tests.hs2.hs2_test_suite import operation_id_to_query_id +from tests.util.filesystem_utils import WAREHOUSE + +AUTH_POLICY_FILE = "%s/authz-policy.ini" % WAREHOUSE + +class TestAuthorization(CustomClusterTestSuite): + AUDIT_LOG_DIR = tempfile.mkdtemp(dir=os.getenv('LOG_DIR')) + + def setup(self): + host, port = IMPALAD_HS2_HOST_PORT.split(":") + self.socket = TSocket(host, port) + self.transport = TBufferedTransport(self.socket) + self.transport.open() + self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport) + self.hs2_client = TCLIService.Client(self.protocol) + + def teardown(self): + if self.socket: + self.socket.close() + shutil.rmtree(self.AUDIT_LOG_DIR, ignore_errors=True) + + @pytest.mark.execute_serially + @CustomClusterTestSuite.with_args("--server_name=server1\ + --authorization_policy_file=%s\ + --authorization_policy_provider_class=%s" %\ + (AUTH_POLICY_FILE, + "org.apache.sentry.provider.file.LocalGroupResourceAuthorizationProvider")) + def test_custom_authorization_provider(self): + from tests.hs2.test_hs2 import TestHS2 + open_session_req = TCLIService.TOpenSessionReq() + # User is 'test_user' (defined in the authorization policy file) + open_session_req.username = 'test_user' + open_session_req.configuration = dict() + resp = self.hs2_client.OpenSession(open_session_req) + TestHS2.check_response(resp) + + # Try to query a table we are not authorized to access. + self.session_handle = resp.sessionHandle + execute_statement_req = TCLIService.TExecuteStatementReq() + execute_statement_req.sessionHandle = self.session_handle + execute_statement_req.statement = "describe tpch_seq.lineitem" + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + assert 'User \'%s\' does not have privileges to access' % 'test_user' in\ + str(execute_statement_resp) + + # Now try the same operation on a table we are authorized to access. + execute_statement_req = TCLIService.TExecuteStatementReq() + execute_statement_req.sessionHandle = self.session_handle + execute_statement_req.statement = "describe tpch.lineitem" + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + TestHS2.check_response(execute_statement_resp) + + @pytest.mark.execute_serially + @CustomClusterTestSuite.with_args("--server_name=server1\ + --authorization_policy_file=%s\ + --authorized_proxy_user_config=hue=%s\ + --audit_event_log_dir=%s" % (AUTH_POLICY_FILE, getuser(), AUDIT_LOG_DIR)) + def test_impersonation(self): + """End-to-end impersonation + authorization test. Expects authorization to be + configured before running this test""" + # TODO: To reuse the HS2 utility code from the TestHS2 test suite we need to import + # the module within this test function, rather than as a top-level import. This way + # the tests in that module will not get pulled when executing this test suite. The fix + # is to split the utility code out of the TestHS2 class and support HS2 as a first + # class citizen in our test framework. + from tests.hs2.test_hs2 import TestHS2 + open_session_req = TCLIService.TOpenSessionReq() + # Connected user is 'hue' + open_session_req.username = 'hue' + open_session_req.configuration = dict() + # Delegated user is the current user + open_session_req.configuration['impala.doas.user'] = getuser() + resp = self.hs2_client.OpenSession(open_session_req) + TestHS2.check_response(resp) + + # Try to query a table we are not authorized to access. + self.session_handle = resp.sessionHandle + execute_statement_req = TCLIService.TExecuteStatementReq() + execute_statement_req.sessionHandle = self.session_handle + execute_statement_req.statement = "describe tpch_seq.lineitem" + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + assert 'User \'%s\' does not have privileges to access' % getuser() in\ + str(execute_statement_resp) + + assert self.__wait_for_audit_record(user=getuser(), impersonator='hue'),\ + 'No matching audit event recorded in time window' + + # Now try the same operation on a table we are authorized to access. + execute_statement_req = TCLIService.TExecuteStatementReq() + execute_statement_req.sessionHandle = self.session_handle + execute_statement_req.statement = "describe tpch.lineitem" + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + + TestHS2.check_response(execute_statement_resp) + + # Verify the correct user information is in the runtime profile + query_id = operation_id_to_query_id( + execute_statement_resp.operationHandle.operationId) + profile_page = self.cluster.impalads[0].service.read_query_profile_page(query_id) + self.__verify_profile_user_fields(profile_page, effective_user=getuser(), + delegated_user=getuser(), connected_user='hue') + + # Try to user we are not authorized to delegate to. + open_session_req.configuration['impala.doas.user'] = 'some_user' + resp = self.hs2_client.OpenSession(open_session_req) + assert 'User \'hue\' is not authorized to delegate to \'some_user\'' in str(resp) + + # Create a new session which does not have a do_as_user. + open_session_req.username = 'hue' + open_session_req.configuration = dict() + resp = self.hs2_client.OpenSession(open_session_req) + TestHS2.check_response(resp) + + # Run a simple query, which should succeed. + execute_statement_req = TCLIService.TExecuteStatementReq() + execute_statement_req.sessionHandle = resp.sessionHandle + execute_statement_req.statement = "select 1" + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + TestHS2.check_response(execute_statement_resp) + + # Verify the correct user information is in the runtime profile. Since there is + # no do_as_user the Delegated User field should be empty. + query_id = operation_id_to_query_id( + execute_statement_resp.operationHandle.operationId) + profile_page = self.cluster.impalads[0].service.read_query_profile_page(query_id) + self.__verify_profile_user_fields(profile_page, effective_user='hue', + delegated_user='', connected_user='hue') + + self.socket.close() + self.socket = None + + def __verify_profile_user_fields(self, profile_str, effective_user, connected_user, + delegated_user): + """Verifies the given runtime profile string contains the specified values for + User, Connected User, and Delegated User""" + assert '\n User: %s\n' % effective_user in profile_str + assert '\n Connected User: %s\n' % connected_user in profile_str + assert '\n Delegated User: %s\n' % delegated_user in profile_str + + def __wait_for_audit_record(self, user, impersonator, timeout_secs=30): + """Waits until an audit log record is found that contains the given user and + impersonator, or until the timeout is reached. + """ + # The audit event might not show up immediately (the audit logs are flushed to disk + # on regular intervals), so poll the audit event logs until a matching record is + # found. + start_time = time() + while time() - start_time < timeout_secs: + for audit_file_name in os.listdir(self.AUDIT_LOG_DIR): + if self.__find_matching_audit_record(audit_file_name, user, impersonator): + return True + sleep(1) + return False + + def __find_matching_audit_record(self, audit_file_name, user, impersonator): + with open(os.path.join(self.AUDIT_LOG_DIR, audit_file_name)) as audit_log_file: + for line in audit_log_file.readlines(): + json_dict = json.loads(line) + if len(json_dict) == 0: continue + if json_dict[min(json_dict)]['user'] == user and\ + json_dict[min(json_dict)]['impersonator'] == impersonator: + return True + return False + +from ctypes import c_void_p + +from django.contrib.gis.gdal.base import GDALBase +from django.contrib.gis.gdal.error import GDALException +from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi +from django.utils import six +from django.utils.encoding import force_bytes, force_text + + +class Driver(GDALBase): + """ + Wraps a GDAL/OGR Data Source Driver. + For more information, see the C API source code: + http://www.gdal.org/gdal_8h.html - http://www.gdal.org/ogr__api_8h.html + """ + + # Case-insensitive aliases for some GDAL/OGR Drivers. + # For a complete list of original driver names see + # http://www.gdal.org/ogr_formats.html (vector) + # http://www.gdal.org/formats_list.html (raster) + _alias = { + # vector + 'esri': 'ESRI Shapefile', + 'shp': 'ESRI Shapefile', + 'shape': 'ESRI Shapefile', + 'tiger': 'TIGER', + 'tiger/line': 'TIGER', + # raster + 'tiff': 'GTiff', + 'tif': 'GTiff', + 'jpeg': 'JPEG', + 'jpg': 'JPEG', + } + + def __init__(self, dr_input): + """ + Initializes an GDAL/OGR driver on either a string or integer input. + """ + if isinstance(dr_input, six.string_types): + # If a string name of the driver was passed in + self.ensure_registered() + + # Checking the alias dictionary (case-insensitive) to see if an + # alias exists for the given driver. + if dr_input.lower() in self._alias: + name = self._alias[dr_input.lower()] + else: + name = dr_input + + # Attempting to get the GDAL/OGR driver by the string name. + for iface in (vcapi, rcapi): + driver = iface.get_driver_by_name(force_bytes(name)) + if driver: + break + elif isinstance(dr_input, int): + self.ensure_registered() + for iface in (vcapi, rcapi): + driver = iface.get_driver(dr_input) + if driver: + break + elif isinstance(dr_input, c_void_p): + driver = dr_input + else: + raise GDALException('Unrecognized input type for GDAL/OGR Driver: %s' % str(type(dr_input))) + + # Making sure we get a valid pointer to the OGR Driver + if not driver: + raise GDALException('Could not initialize GDAL/OGR Driver on input: %s' % str(dr_input)) + self.ptr = driver + + def __str__(self): + return self.name + + @classmethod + def ensure_registered(cls): + """ + Attempts to register all the data source drivers. + """ + # Only register all if the driver count is 0 (or else all drivers + # will be registered over and over again) + if not cls.driver_count(): + vcapi.register_all() + rcapi.register_all() + + @classmethod + def driver_count(cls): + """ + Returns the number of GDAL/OGR data source drivers registered. + """ + return vcapi.get_driver_count() + rcapi.get_driver_count() + + @property + def name(self): + """ + Returns description/name string for this driver. + """ + return force_text(rcapi.get_driver_description(self.ptr)) + +# -*- encoding: utf-8 -*- +# This file is distributed under the same license as the Django package. +# +from __future__ import unicode_literals + +# The *_FORMAT strings use the Django date format syntax, +# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date +DATE_FORMAT = r'Y \m. E j \d.' +TIME_FORMAT = 'H:i' +DATETIME_FORMAT = r'Y \m. E j \d., H:i' +YEAR_MONTH_FORMAT = r'Y \m. F' +MONTH_DAY_FORMAT = r'E j \d.' +SHORT_DATE_FORMAT = 'Y-m-d' +SHORT_DATETIME_FORMAT = 'Y-m-d H:i' +FIRST_DAY_OF_WEEK = 1 # Monday + +# The *_INPUT_FORMATS strings use the Python strftime format syntax, +# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior +DATE_INPUT_FORMATS = [ + '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' +] +TIME_INPUT_FORMATS = [ + '%H:%M:%S', # '14:30:59' + '%H:%M:%S.%f', # '14:30:59.000200' + '%H:%M', # '14:30' + '%H.%M.%S', # '14.30.59' + '%H.%M.%S.%f', # '14.30.59.000200' + '%H.%M', # '14.30' +] +DATETIME_INPUT_FORMATS = [ + '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' + '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' + '%Y-%m-%d %H:%M', # '2006-10-25 14:30' + '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' + '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' + '%d.%m.%Y %H:%M', # '25.10.2006 14:30' + '%d.%m.%Y', # '25.10.2006' + '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' + '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' + '%d.%m.%y %H:%M', # '25.10.06 14:30' + '%d.%m.%y %H.%M.%S', # '25.10.06 14.30.59' + '%d.%m.%y %H.%M.%S.%f', # '25.10.06 14.30.59.000200' + '%d.%m.%y %H.%M', # '25.10.06 14.30' + '%d.%m.%y', # '25.10.06' +] +DECIMAL_SEPARATOR = ',' +THOUSAND_SEPARATOR = '.' +NUMBER_GROUPING = 3 + +# coding: utf-8 +from __future__ import unicode_literals + +import re + +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + float_or_none, +) + + +class VGTVIE(InfoExtractor): + IE_DESC = 'VGTV and BTTV' + _VALID_URL = r'''(?x) + (?: + vgtv:| + http://(?:www\.)? + ) + (?Pvgtv|bt) + (?: + :| + \.no/(?:tv/)?\#!/(?:video|live)/ + ) + (?P[0-9]+) + ''' + _TESTS = [ + { + # streamType: vod + 'url': 'http://www.vgtv.no/#!/video/84196/hevnen-er-soet-episode-10-abu', + 'md5': 'b8be7a234cebb840c0d512c78013e02f', + 'info_dict': { + 'id': '84196', + 'ext': 'mp4', + 'title': 'Hevnen er søt: Episode 10 - Abu', + 'description': 'md5:e25e4badb5f544b04341e14abdc72234', + 'thumbnail': 're:^https?://.*\.jpg', + 'duration': 648.000, + 'timestamp': 1404626400, + 'upload_date': '20140706', + 'view_count': int, + }, + }, + { + # streamType: wasLive + 'url': 'http://www.vgtv.no/#!/live/100764/opptak-vgtv-foelger-em-kvalifiseringen', + 'info_dict': { + 'id': '100764', + 'ext': 'flv', + 'title': 'OPPTAK: VGTV følger EM-kvalifiseringen', + 'description': 'md5:3772d9c0dc2dff92a886b60039a7d4d3', + 'thumbnail': 're:^https?://.*\.jpg', + 'duration': 9103.0, + 'timestamp': 1410113864, + 'upload_date': '20140907', + 'view_count': int, + }, + 'params': { + # m3u8 download + 'skip_download': True, + }, + }, + { + # streamType: live + 'url': 'http://www.vgtv.no/#!/live/113063/direkte-v75-fra-solvalla', + 'info_dict': { + 'id': '113063', + 'ext': 'flv', + 'title': 're:^DIREKTE: V75 fra Solvalla [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$', + 'description': 'md5:b3743425765355855f88e096acc93231', + 'thumbnail': 're:^https?://.*\.jpg', + 'duration': 0, + 'timestamp': 1432975582, + 'upload_date': '20150530', + 'view_count': int, + }, + 'params': { + # m3u8 download + 'skip_download': True, + }, + }, + { + 'url': 'http://www.bt.no/tv/#!/video/100250/norling-dette-er-forskjellen-paa-1-divisjon-og-eliteserien', + 'only_matching': True, + }, + ] + + def _real_extract(self, url): + mobj = re.match(self._VALID_URL, url) + video_id = mobj.group('id') + host = mobj.group('host') + + HOST_WEBSITES = { + 'vgtv': 'vgtv', + 'bt': 'bttv', + } + + data = self._download_json( + 'http://svp.vg.no/svp/api/v1/%s/assets/%s?appName=%s-website' + % (host, video_id, HOST_WEBSITES[host]), + video_id, 'Downloading media JSON') + + if data.get('status') == 'inactive': + raise ExtractorError( + 'Video %s is no longer available' % video_id, expected=True) + + streams = data['streamUrls'] + stream_type = data.get('streamType') + + formats = [] + + hls_url = streams.get('hls') + if hls_url: + formats.extend(self._extract_m3u8_formats( + hls_url, video_id, 'mp4', m3u8_id='hls')) + + hds_url = streams.get('hds') + # wasLive hds are always 404 + if hds_url and stream_type != 'wasLive': + formats.extend(self._extract_f4m_formats( + hds_url + '?hdcore=3.2.0&plugin=aasp-3.2.0.77.18', + video_id, f4m_id='hds')) + + mp4_url = streams.get('mp4') + if mp4_url: + _url = hls_url or hds_url + MP4_URL_TEMPLATE = '%s/%%s.%s' % (mp4_url.rpartition('/')[0], mp4_url.rpartition('.')[-1]) + for mp4_format in _url.split(','): + m = re.search('(?P\d+)_(?P\d+)_(?P\d+)', mp4_format) + if not m: + continue + width = int(m.group('width')) + height = int(m.group('height')) + vbr = int(m.group('vbr')) + formats.append({ + 'url': MP4_URL_TEMPLATE % mp4_format, + 'format_id': 'mp4-%s' % vbr, + 'width': width, + 'height': height, + 'vbr': vbr, + 'preference': 1, + }) + self._sort_formats(formats) + + return { + 'id': video_id, + 'title': self._live_title(data['title']), + 'description': data['description'], + 'thumbnail': data['images']['main'] + '?t[]=900x506q80', + 'timestamp': data['published'], + 'duration': float_or_none(data['duration'], 1000), + 'view_count': data['displays'], + 'formats': formats, + 'is_live': True if stream_type == 'live' else False, + } + + +class BTArticleIE(InfoExtractor): + IE_NAME = 'bt:article' + IE_DESC = 'Bergens Tidende Articles' + _VALID_URL = 'http://(?:www\.)?bt\.no/(?:[^/]+/)+(?P[^/]+)-\d+\.html' + _TEST = { + 'url': 'http://www.bt.no/nyheter/lokalt/Kjemper-for-internatet-1788214.html', + 'md5': 'd055e8ee918ef2844745fcfd1a4175fb', + 'info_dict': { + 'id': '23199', + 'ext': 'mp4', + 'title': 'Alrekstad internat', + 'description': 'md5:dc81a9056c874fedb62fc48a300dac58', + 'thumbnail': 're:^https?://.*\.jpg', + 'duration': 191, + 'timestamp': 1289991323, + 'upload_date': '20101117', + 'view_count': int, + }, + } + + def _real_extract(self, url): + webpage = self._download_webpage(url, self._match_id(url)) + video_id = self._search_regex( + r'SVP\.Player\.load\(\s*(\d+)', webpage, 'video id') + return self.url_result('vgtv:bt:%s' % video_id, 'VGTV') + + +class BTVestlendingenIE(InfoExtractor): + IE_NAME = 'bt:vestlendingen' + IE_DESC = 'Bergens Tidende - Vestlendingen' + _VALID_URL = 'http://(?:www\.)?bt\.no/spesial/vestlendingen/#!/(?P\d+)' + _TEST = { + 'url': 'http://www.bt.no/spesial/vestlendingen/#!/86588', + 'md5': 'd7d17e3337dc80de6d3a540aefbe441b', + 'info_dict': { + 'id': '86588', + 'ext': 'mov', + 'title': 'Otto Wollertsen', + 'description': 'Vestlendingen Otto Fredrik Wollertsen', + 'timestamp': 1430473209, + 'upload_date': '20150501', + }, + } + + def _real_extract(self, url): + return self.url_result('xstream:btno:%s' % self._match_id(url), 'Xstream') + +# Copyright 2008-2015 Canonical +# +# 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 . +# +# For further info, check http://launchpad.net/filesync-server + +"""Some large jobs have to be done in smaller chunks, e.g. because you want to +report progress to a user, or you're holding locks that others may be waiting +for. But you can't always afford to stop and look at your watch every +iteration of your loop: sometimes you need to decide how big your chunk will +be before you start processing it. + +One way to solve this is to measure performance of your loop, and pick a chunk +size that will give you decent performance while also stopping at more or less +regular intervals to update your progress display, refresh your locks, or +whatever else you want to do. But what if the Moon is in the House of Uranus +and the server slows down? Conversely, you may be wasting time if you stop too +often. + +The LoopTuner solves this. You tell it what you want to do and how long each +chunk should take, and it will figure out how many items you need to process +per chunk to get close to your ideal time between stops. Chunk sizes will +adjust themselves dynamically to actual performance.""" + +__metaclass__ = type + +__all__ = [ + 'DBLoopTuner', + 'ITunableLoop', + 'LoopTuner', + 'TunableLoop', +] + + +import logging +import sys +import time + +from datetime import timedelta + +import transaction + +from zope.interface import ( + implements, + Interface, +) + + +class ITunableLoop(Interface): + """Interface for self-tuning loop bodies to be driven by LoopTuner. + + To construct a self-tuning batched loop, define your loop body as a class + implementing TunableLoop, and pass an instance to your LoopTuner. + """ + def isDone(self): + """Is this loop finished? + + Once this returns True, the LoopTuner will no longer touch this + object. + """ + + def __call__(self, chunk_size): + """Perform an iteration of the loop. + + The chunk_size parameter says (in some way you define) how much work + the LoopTuner believes you should try to do in this iteration in order + to get as close as possible to your time goal. + + Note that chunk_size is a float, so, for example, if you use it to + slice a list, be careful to round it to an int first. + """ + + def cleanUp(self): + """Clean up any open resources. + + Optional. + + This method is needed because loops may be aborted before + completion, so clean up code in the isDone() method may + never be invoked. + """ + + +class IDBTunableLoop(ITunableLoop): + """Almost the same as ITunableLoop, except that it expects the class to + implement getStore(), in order to get the appropriate Storm store.""" + + def getStore(self): + """Get the Storm store for which to execute the loop.""" + + +class LoopTuner: + """A loop that tunes itself to approximate an ideal time per iteration. + + Use this for large processing jobs that need to be broken down into chunks + of such size that processing a single chunk takes approximately a given + ideal time. For example, large database operations may have to be + performed and committed in a large number of small steps in order to avoid + locking out other clients that need to access the same data. Regular + commits allow other clients to get their work done. + + In such a situation, committing for every step is often far too costly. + Imagine inserting a million rows and committing after every row! You + could hand-pick a static number of steps per commit, but that takes a lot + of experimental guesswork and it will still waste time when things go + well, and on the other hand, it will still end up taking too much time per + batch when the system slows down for whatever reason. + + Instead, define your loop body in an ITunableLoop; parameterize it on the + number of steps per batch; say how much time you'd like to spend per + batch; and pass it to a LoopTuner. The LoopTuner will execute your loop, + dynamically tuning its batch-size parameter to stay close to your time + goal. If things go faster than expected, it will ask your loop body to do + more work for the next batch. If a batch takes too much time, the next + batch will be smaller. There is also some cushioning for one-off spikes + and troughs in processing speed. + """ + + def __init__(self, operation, goal_seconds, minimum_chunk_size=1, + maximum_chunk_size=1000000000, abort_time=None, + cooldown_time=None, log=None): + """Initialize a loop, to be run to completion at most once. + + Parameters: + + operation: an object implementing the loop body. It must support the + ITunableLoop interface. + + goal_seconds: the ideal number of seconds for any one iteration to + take. The algorithm will vary chunk size in order to stick close + to this ideal. + + minimum_chunk_size: the smallest chunk size that is reasonable. The + tuning algorithm will never let chunk size sink below this value. + + maximum_chunk_size: the largest allowable chunk size. A maximum is + needed even if the ITunableLoop ignores chunk size for whatever + reason, since reaching floating-point infinity would seriously + break the algorithm's arithmetic. + + cooldown_time: time (in seconds, float) to sleep between consecutive + operation runs. Defaults to None for no sleep. + + abort_time: abort the loop, logging a WARNING message, if the runtime + takes longer than this many seconds. + + log: The log object to use. DEBUG level messages are logged + giving iteration statistics. + """ + assert(ITunableLoop.providedBy(operation)) + self.operation = operation + self.goal_seconds = float(goal_seconds) + self.minimum_chunk_size = minimum_chunk_size + self.maximum_chunk_size = maximum_chunk_size + self.cooldown_time = cooldown_time + self.abort_time = abort_time + self.start_time = None + if log is None: + self.log = logging + else: + self.log = log + + # True if this task has timed out. Set by _isTimedOut(). + _has_timed_out = False + + def _isTimedOut(self, extra_seconds=0): + """Return True if the task will be timed out in extra_seconds. + + If this method returns True, all future calls will also return + True. + """ + if self.abort_time is None: + return False + if self._has_timed_out: + return True + if self._time() + extra_seconds >= self.start_time + self.abort_time: + self._has_timed_out = True + return True + return False + + def run(self): + """Run the loop to completion.""" + # Cleanup function, if we have one. + cleanup = getattr(self.operation, 'cleanUp', lambda: None) + try: + chunk_size = self.minimum_chunk_size + iteration = 0 + total_size = 0 + self.start_time = self._time() + last_clock = self.start_time + while not self.operation.isDone(): + + if self._isTimedOut(): + self.log.info( + "Task aborted after %d seconds.", self.abort_time) + break + + self.operation(chunk_size) + + new_clock = self._time() + time_taken = new_clock - last_clock + last_clock = new_clock + + self.log.debug( + "Iteration %d (size %.1f): %.3f seconds", + iteration, chunk_size, time_taken) + + last_clock = self._coolDown(last_clock) + + total_size += chunk_size + + # Adjust parameter value to approximate goal_seconds. + # The new value is the average of two numbers: the + # previous value, and an estimate of how many rows would + # take us to exactly goal_seconds seconds. The weight in + # this estimate of any given historic measurement decays + # exponentially with an exponent of 1/2. This softens + # the blows from spikes and dips in processing time. Set + # a reasonable minimum for time_taken, just in case we + # get weird values for whatever reason and destabilize + # the algorithm. + time_taken = max(self.goal_seconds / 10, time_taken) + chunk_size *= (1 + self.goal_seconds / time_taken) / 2 + chunk_size = max(chunk_size, self.minimum_chunk_size) + chunk_size = min(chunk_size, self.maximum_chunk_size) + iteration += 1 + + total_time = last_clock - self.start_time + average_size = total_size / max(1, iteration) + average_speed = total_size / max(1, total_time) + self.log.debug( + "Done. %d items in %d iterations, %3f seconds, " + "average size %f (%s/s)", + total_size, iteration, total_time, average_size, + average_speed) + except Exception: + exc_info = sys.exc_info() + try: + cleanup() + except Exception: + # We need to raise the original exception, but we don't + # want to lose the information about the cleanup + # failure, so log it. + self.log.exception("Unhandled exception in cleanUp") + # Reraise the original exception. + raise exc_info[0], exc_info[1], exc_info[2] + else: + cleanup() + + def _coolDown(self, bedtime): + """Sleep for `self.cooldown_time` seconds, if set. + + Assumes that anything the main LoopTuner loop does apart from + doing a chunk of work or sleeping takes zero time. + + :param bedtime: Time the cooldown started, i.e. the time the + chunk of real work was completed. + :return: Time when cooldown completed, i.e. the starting time + for a next chunk of work. + """ + if self.cooldown_time is None or self.cooldown_time <= 0.0: + return bedtime + else: + self._sleep(self.cooldown_time) + return self._time() + + def _time(self): + """Monotonic system timer with unit of 1 second. + + Overridable so tests can fake processing speeds accurately and without + actually waiting. + """ + return time.time() + + def _sleep(self, seconds): + """Sleep. + + If the sleep interval would put us over the tasks timeout, + do nothing. + """ + if not self._isTimedOut(seconds): + time.sleep(seconds) + + +class DBLoopTuner(LoopTuner): + """A LoopTuner that plays well with PostgreSQL and replication. + + This LoopTuner blocks when database replication is lagging. + Making updates faster than replication can deal with them is + counter productive and in extreme cases can put the database + into a death spiral. So we don't do that. + + This LoopTuner also blocks when there are long running + transactions. Vacuuming is ineffective when there are long + running transactions. We block when long running transactions + have been detected, as it means we have already been bloating + the database for some time and we shouldn't make it worse. Once + the long running transactions have completed, we know the dead + space we have already caused can be cleaned up so we can keep + going. + + INFO level messages are logged when the DBLoopTuner blocks in addition + to the DEBUG level messages emitted by the standard LoopTuner. + """ + + # We block until replication lag is under this threshold. + acceptable_replication_lag = timedelta(seconds=30) # In seconds. + + # We block if there are transactions running longer than this threshold. + long_running_transaction = 30 * 60 # In seconds. + + def __init__(self, operation, goal_seconds, minimum_chunk_size=1, + maximum_chunk_size=1000000000, + abort_time=None, cooldown_time=None, + log=None): + super(DBLoopTuner, self).__init__(operation, goal_seconds, + minimum_chunk_size, + maximum_chunk_size, + abort_time, cooldown_time, log) + assert(IDBTunableLoop.providedBy(operation)) + + def _blockForLongRunningTransactions(self): + """If there are long running transactions, block to avoid making + bloat worse.""" + if self.long_running_transaction is None: + return + store = self.operation.getStore() + msg_counter = 0 + while not self._isTimedOut(): + results = list(store.execute(""" + SELECT + CURRENT_TIMESTAMP - xact_start, + procpid, + usename, + datname, + current_query + FROM activity() + WHERE xact_start < CURRENT_TIMESTAMP - interval '%f seconds' + AND datname = current_database() + ORDER BY xact_start LIMIT 4 + """ % self.long_running_transaction).get_all()) + if not results: + break + + # Check for long running transactions every 10 seconds, but + # only report every 10 minutes to avoid log spam. + msg_counter += 1 + if msg_counter % 60 == 1: + for runtime, procpid, usename, datname, query in results: + self.log.info( + "Blocked on %s old xact %s@%s/%d - %s.", + runtime, usename, datname, procpid, query) + self.log.info("Sleeping for up to 10 minutes.") + # Don't become a long running transaction! + transaction.abort() + self._sleep(10) + + def _coolDown(self, bedtime): + """As per LoopTuner._coolDown, except we always wait until there + is no replication lag. + """ + self._blockForLongRunningTransactions() + if self.cooldown_time is not None and self.cooldown_time > 0.0: + remaining_nap = self._time() - bedtime + self.cooldown_time + if remaining_nap > 0.0: + self._sleep(remaining_nap) + return self._time() + + +class TunableLoop: + """A base implementation of `ITunableLoop`.""" + implements(ITunableLoop) + + # DBLoopTuner blocks on replication lag and long transactions. If a + # subclass wants to ignore them, it can override this to be a normal + # LoopTuner. + tuner_class = DBLoopTuner + + goal_seconds = 2 + minimum_chunk_size = 1 + maximum_chunk_size = None # Override. + cooldown_time = 0 + + def __init__(self, log, abort_time=None): + self.log = log + self.abort_time = abort_time + + def isDone(self): + """Return True when the TunableLoop is complete.""" + raise NotImplementedError(self.isDone) + + def run(self): + """Start running the loop.""" + assert self.maximum_chunk_size is not None, ( + "Did not override maximum_chunk_size.") + self.tuner_class( + self, self.goal_seconds, + minimum_chunk_size=self.minimum_chunk_size, + maximum_chunk_size=self.maximum_chunk_size, + cooldown_time=self.cooldown_time, + abort_time=self.abort_time, + log=self.log).run() + +######################################################################### +# +# Copyright (c) 2003-2004 Danny Brewer d29583@groovegarden.com +# Copyright (C) 2004-2010 OpenERP SA (). +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +# +# See: http://www.gnu.org/licenses/lgpl.html +# +############################################################################# + +import uno +import string +import unohelper +import xmlrpclib +from com.sun.star.task import XJobExecutor +if __name__<>"package": + from lib.gui import * + from lib.error import ErrorDialog + from lib.functions import * + from ServerParameter import * + from lib.logreport import * + from lib.rpc import * + from LoginTest import * + + database="test_db1" + uid = 3 + + +#class RepeatIn: +class RepeatIn( unohelper.Base, XJobExecutor ): + def __init__(self, sObject="", sVariable="", sFields="", sDisplayName="", bFromModify=False): + # Interface Design + LoginTest() + self.logobj=Logger() + if not loginstatus and __name__=="package": + exit(1) + + self.win = DBModalDialog(60, 50, 180, 250, "RepeatIn Builder") + self.win.addFixedText("lblVariable", 2, 12, 60, 15, "Objects to loop on :") + self.win.addComboBox("cmbVariable", 180-120-2, 10, 120, 15,True, itemListenerProc=self.cmbVariable_selected) + self.insVariable = self.win.getControl( "cmbVariable" ) + + self.win.addFixedText("lblFields", 10, 32, 60, 15, "Field to loop on :") + self.win.addComboListBox("lstFields", 180-120-2, 30, 120, 150, False,itemListenerProc=self.lstbox_selected) + self.insField = self.win.getControl( "lstFields" ) + + self.win.addFixedText("lblName", 12, 187, 60, 15, "Variable name :") + self.win.addEdit("txtName", 180-120-2, 185, 120, 15,) + + self.win.addFixedText("lblUName", 8, 207, 60, 15, "Displayed name :") + self.win.addEdit("txtUName", 180-120-2, 205, 120, 15,) + + self.win.addButton('btnOK',-2 ,-10,45,15,'Ok', actionListenerProc = self.btnOk_clicked ) + + self.win.addButton('btnCancel',-2 - 45 - 5 ,-10,45,15,'Cancel', actionListenerProc = self.btnCancel_clicked ) + + global passwd + self.password = passwd + global url + self.sock=RPCSession(url) + # Variable Declaration + self.sValue=None + self.sObj=None + self.aSectionList=[] + self.sGVariable=sVariable + self.sGDisplayName=sDisplayName + self.aItemList=[] + self.aComponentAdd=[] + self.aObjectList=[] + self.aListRepeatIn=[] + self.aVariableList=[] + # Call method to perform Enumration on Report Document + EnumDocument(self.aItemList,self.aComponentAdd) + # Perform checking that Field-1 and Field - 4 is available or not alos get Combobox + # filled if condition is true + desktop = getDesktop() + doc = desktop.getCurrentComponent() + docinfo = doc.getDocumentInfo() + # Check weather Field-1 is available if not then exit from application + self.sMyHost= "" + + if not docinfo.getUserFieldValue(3) == "" and not docinfo.getUserFieldValue(0)=="": + self.sMyHost= docinfo.getUserFieldValue(0) + self.count=0 + oParEnum = doc.getTextFields().createEnumeration() + + while oParEnum.hasMoreElements(): + oPar = oParEnum.nextElement() + if oPar.supportsService("com.sun.star.text.TextField.DropDown"): + self.count += 1 + + getList(self.aObjectList, self.sMyHost,self.count) + cursor = doc.getCurrentController().getViewCursor() + text = cursor.getText() + tcur = text.createTextCursorByRange(cursor) + + self.aVariableList.extend( filter( lambda obj: obj[:obj.find(" ")] == "List", self.aObjectList ) ) + + for i in range(len(self.aItemList)): + try: + anItem = self.aItemList[i][1] + component = self.aComponentAdd[i] + + if component == "Document": + sLVal = anItem[anItem.find(",'") + 2:anItem.find("')")] + self.aVariableList.extend( filter( lambda obj: obj[:obj.find("(")] == sLVal, self.aObjectList ) ) + + if tcur.TextSection: + getRecersiveSection(tcur.TextSection,self.aSectionList) + if component in self.aSectionList: + sLVal = anItem[anItem.find(",'") + 2:anItem.find("')")] + self.aVariableList.extend( filter( lambda obj: obj[:obj.find("(")] == sLVal, self.aObjectList ) ) + + if tcur.TextTable: + if not component == "Document" and component[component.rfind(".") + 1:] == tcur.TextTable.Name: + VariableScope( tcur, self.aVariableList, self.aObjectList, self.aComponentAdd, self.aItemList, component ) + except : + import traceback,sys + info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) + self.logobj.log_write('RepeatIn', LOG_ERROR, info) + self.bModify=bFromModify + + if self.bModify==True: + + if sObject=="": + self.insVariable.setText("List of "+docinfo.getUserFieldValue(3)) + self.insField.addItem("objects",self.win.getListBoxItemCount("lstFields")) + self.win.setEditText("txtName", sVariable) + self.win.setEditText("txtUName",sDisplayName) + self.sValue= "objects" + else: + sItem="" + for anObject in self.aObjectList: + if anObject[:anObject.find("(")] == sObject: + sItem = anObject + self.insVariable.setText( sItem ) + + genTree( + sItem[sItem.find("(")+1:sItem.find(")")], + self.aListRepeatIn, + self.insField, + self.sMyHost, + 2, + ending=['one2many','many2many'], + recur=['one2many','many2many'] + ) + + self.sValue= self.win.getListBoxItem("lstFields",self.aListRepeatIn.index(sFields)) + + for var in self.aVariableList: + + if var[:8] <> 'List of ': + self.model_ids = self.sock.execute(database, uid, self.password, 'ir.model' , 'search', [('model','=',var[var.find("(")+1:var.find(")")])]) + else: + self.model_ids = self.sock.execute(database, uid, self.password, 'ir.model' , 'search', [('model','=',var[8:])]) + fields=['name','model'] + self.model_res = self.sock.execute(database, uid, self.password, 'ir.model', 'read', self.model_ids,fields) + if self.model_res <> []: + if var[:8]<>'List of ': + self.insVariable.addItem(var[:var.find("(")+1] + self.model_res[0]['name'] + ")" ,self.insVariable.getItemCount()) + else: + self.insVariable.addItem('List of ' + self.model_res[0]['name'] ,self.insVariable.getItemCount()) + else: + self.insVariable.addItem(var ,self.insVariable.getItemCount()) + + self.win.doModalDialog("lstFields",self.sValue) + else: + ErrorDialog("Please Select Appropriate module" ,"Create new report from: \nOdoo -> Open a New Report") + self.win.endExecute() + + def lstbox_selected(self, oItemEvent): + sItem=self.win.getListBoxSelectedItem("lstFields") + sMain=self.aListRepeatIn[self.win.getListBoxSelectedItemPos("lstFields")] + + if self.bModify==True: + self.win.setEditText("txtName", self.sGVariable) + self.win.setEditText("txtUName",self.sGDisplayName) + else: + self.win.setEditText("txtName",sMain[sMain.rfind("/")+1:]) + self.win.setEditText("txtUName","|-."+sItem[sItem.rfind("/")+1:]+".-|") + + def cmbVariable_selected(self, oItemEvent): + + if self.count > 0 : + + desktop=getDesktop() + doc =desktop.getCurrentComponent() + docinfo=doc.getDocumentInfo() + self.win.removeListBoxItems("lstFields", 0, self.win.getListBoxItemCount("lstFields")) + sItem=self.win.getComboBoxText("cmbVariable") + for var in self.aVariableList: + if var[:8]=='List of ': + if var[:8]==sItem[:8]: + sItem = var + elif var[:var.find("(")+1] == sItem[:sItem.find("(")+1]: + sItem = var + self.aListRepeatIn=[] + + data = ( sItem[sItem.rfind(" ") + 1:] == docinfo.getUserFieldValue(3) ) and docinfo.getUserFieldValue(3) or sItem[sItem.find("(")+1:sItem.find(")")] + genTree( data, self.aListRepeatIn, self.insField, self.sMyHost, 2, ending=['one2many','many2many'], recur=['one2many','many2many'] ) + + self.win.selectListBoxItemPos("lstFields", 0, True ) + + else: + sItem=self.win.getComboBoxText("cmbVariable") + for var in self.aVariableList: + if var[:8]=='List of ' and var[:8] == sItem[:8]: + sItem = var + if sItem.find(".")==-1: + temp=sItem[sItem.rfind("x_"):] + else: + temp=sItem[sItem.rfind(".")+1:] + self.win.setEditText("txtName",temp) + self.win.setEditText("txtUName","|-."+temp+".-|") + self.insField.addItem("objects",self.win.getListBoxItemCount("lstFields")) + self.win.selectListBoxItemPos("lstFields", 0, True ) + + def btnOk_clicked(self, oActionEvent): + desktop=getDesktop() + doc = desktop.getCurrentComponent() + cursor = doc.getCurrentController().getViewCursor() + selectedItem = self.win.getListBoxSelectedItem( "lstFields" ) + selectedItemPos = self.win.getListBoxSelectedItemPos( "lstFields" ) + txtName = self.win.getEditText( "txtName" ) + txtUName = self.win.getEditText( "txtUName" ) + if selectedItem != "" and txtName != "" and txtUName != "": + sKey=u""+ txtUName + if selectedItem == "objects": + sValue=u"[[ repeatIn(" + selectedItem + ",'" + txtName + "') ]]" + else: + sObjName=self.win.getComboBoxText("cmbVariable") + sObjName=sObjName[:sObjName.find("(")] + sValue=u"[[ repeatIn(" + sObjName + self.aListRepeatIn[selectedItemPos].replace("/",".") + ",'" + txtName +"') ]]" + + if self.bModify == True: + oCurObj = cursor.TextField + oCurObj.Items = (sKey,sValue) + oCurObj.update() + else: + oInputList = doc.createInstance("com.sun.star.text.TextField.DropDown") + if self.win.getListBoxSelectedItem("lstFields") == "objects": + oInputList.Items = (sKey,sValue) + doc.Text.insertTextContent(cursor,oInputList,False) + else: + sValue=u"[[ repeatIn(" + sObjName + self.aListRepeatIn[selectedItemPos].replace("/",".") + ",'" + txtName +"') ]]" + if cursor.TextTable==None: + oInputList.Items = (sKey,sValue) + doc.Text.insertTextContent(cursor,oInputList,False) + else: + oInputList.Items = (sKey,sValue) + widget = ( cursor.TextTable or selectedItem <> 'objects' ) and cursor.TextTable.getCellByName( cursor.Cell.CellName ) or doc.Text + widget.insertTextContent(cursor,oInputList,False) + self.win.endExecute() + else: + ErrorDialog("Please fill appropriate data in Object Field or Name field \nor select particular value from the list of fields.") + + def btnCancel_clicked(self, oActionEvent): + self.win.endExecute() + +if __name__<>"package" and __name__=="__main__": + RepeatIn() +elif __name__=="package": + g_ImplementationHelper = unohelper.ImplementationHelper() + g_ImplementationHelper.addImplementation( RepeatIn, "org.openoffice.openerp.report.repeatln", ("com.sun.star.task.Job",),) + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: + +# (c) 2012-2014, Michael DeHaan +# +# 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 . + +# Make coding more python3-ish +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +from ansible.playbook.attribute import FieldAttribute +from ansible.playbook.base import FieldAttributeBase + + +class LoopControl(FieldAttributeBase): + + _loop_var = FieldAttribute(isa='str', default='item') + _index_var = FieldAttribute(isa='str') + _label = FieldAttribute(isa='str') + _pause = FieldAttribute(isa='int', default=0) + + def __init__(self): + super(LoopControl, self).__init__() + + @staticmethod + def load(data, variable_manager=None, loader=None): + t = LoopControl() + return t.load_data(data, variable_manager=variable_manager, loader=loader) + +#!/usr/bin/python +# +# Copyright 2009 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. + +# This module is used for version 2 of the Google Data APIs. +# These tests attempt to connect to Google servers. + + +__author__ = 'e.bidelman (Eric Bidelman)' + +import unittest +import gdata.client +import gdata.data +import gdata.gauth +import gdata.sites.client +import gdata.sites.data +import gdata.test_config as conf + +conf.options.register_option(conf.TEST_IMAGE_LOCATION_OPTION) +conf.options.register_option(conf.APPS_DOMAIN_OPTION) +conf.options.register_option(conf.SITES_NAME_OPTION) + + +class SitesClientTest(unittest.TestCase): + + def setUp(self): + self.client = None + if conf.options.get_value('runlive') == 'true': + self.client = gdata.sites.client.SitesClient( + site=conf.options.get_value('sitename'), + domain=conf.options.get_value('appsdomain')) + if conf.options.get_value('ssl') == 'true': + self.client.ssl = True + conf.configure_client(self.client, 'SitesTest', self.client.auth_service, + True) + + def tearDown(self): + conf.close_client(self.client) + + def testCreateUpdateDelete(self): + if not conf.options.get_value('runlive') == 'true': + return + + # Either load the recording or prepare to make a live request. + conf.configure_cache(self.client, 'testCreateUpdateDelete') + + new_entry = self.client.CreatePage( + 'webpage', 'Title Of Page', 'Your html content') + + self.assertEqual(new_entry.title.text, 'Title Of Page') + self.assertEqual(new_entry.page_name.text, 'title-of-page') + self.assert_(new_entry.GetAlternateLink().href is not None) + self.assertEqual(new_entry.Kind(), 'webpage') + + # Change the title of the webpage we just added. + new_entry.title.text = 'Edited' + updated_entry = self.client.update(new_entry) + + self.assertEqual(updated_entry.title.text, 'Edited') + self.assertEqual(updated_entry.page_name.text, 'title-of-page') + self.assert_(isinstance(updated_entry, gdata.sites.data.ContentEntry)) + + # Delete the test webpage from the Site. + self.client.delete(updated_entry) + + def testCreateAndUploadToFilecabinet(self): + if not conf.options.get_value('runlive') == 'true': + return + + # Either load the recording or prepare to make a live request. + conf.configure_cache(self.client, 'testCreateAndUploadToFilecabinet') + + filecabinet = self.client.CreatePage( + 'filecabinet', 'FilesGoHere', 'Your html content', + page_name='diff-pagename-than-title') + + self.assertEqual(filecabinet.title.text, 'FilesGoHere') + self.assertEqual(filecabinet.page_name.text, 'diff-pagename-than-title') + self.assert_(filecabinet.GetAlternateLink().href is not None) + self.assertEqual(filecabinet.Kind(), 'filecabinet') + + # Upload a file to the filecabinet + filepath = conf.options.get_value('imgpath') + attachment = self.client.UploadAttachment( + filepath, filecabinet, content_type='image/jpeg', title='TestImageFile', + description='description here') + + self.assertEqual(attachment.title.text, 'TestImageFile') + self.assertEqual(attachment.FindParentLink(), + filecabinet.GetSelfLink().href) + + # Delete the test filecabinet and attachment from the Site. + self.client.delete(attachment) + self.client.delete(filecabinet) + + +def suite(): + return conf.build_suite([SitesClientTest]) + + +if __name__ == '__main__': + unittest.TextTestRunner().run(suite()) + +import numpy as np +import pickle + +from sklearn.isotonic import (check_increasing, isotonic_regression, + IsotonicRegression) + +from sklearn.utils.testing import (assert_raises, assert_array_equal, + assert_true, assert_false, assert_equal, + assert_array_almost_equal, + assert_warns_message, assert_no_warnings) +from sklearn.utils import shuffle + + +def test_permutation_invariance(): + # check that fit is permuation invariant. + # regression test of missing sorting of sample-weights + ir = IsotonicRegression() + x = [1, 2, 3, 4, 5, 6, 7] + y = [1, 41, 51, 1, 2, 5, 24] + sample_weight = [1, 2, 3, 4, 5, 6, 7] + x_s, y_s, sample_weight_s = shuffle(x, y, sample_weight, random_state=0) + y_transformed = ir.fit_transform(x, y, sample_weight=sample_weight) + y_transformed_s = ir.fit(x_s, y_s, sample_weight=sample_weight_s).transform(x) + + assert_array_equal(y_transformed, y_transformed_s) + + +def test_check_increasing_up(): + x = [0, 1, 2, 3, 4, 5] + y = [0, 1.5, 2.77, 8.99, 8.99, 50] + + # Check that we got increasing=True and no warnings + is_increasing = assert_no_warnings(check_increasing, x, y) + assert_true(is_increasing) + + +def test_check_increasing_up_extreme(): + x = [0, 1, 2, 3, 4, 5] + y = [0, 1, 2, 3, 4, 5] + + # Check that we got increasing=True and no warnings + is_increasing = assert_no_warnings(check_increasing, x, y) + assert_true(is_increasing) + + +def test_check_increasing_down(): + x = [0, 1, 2, 3, 4, 5] + y = [0, -1.5, -2.77, -8.99, -8.99, -50] + + # Check that we got increasing=False and no warnings + is_increasing = assert_no_warnings(check_increasing, x, y) + assert_false(is_increasing) + + +def test_check_increasing_down_extreme(): + x = [0, 1, 2, 3, 4, 5] + y = [0, -1, -2, -3, -4, -5] + + # Check that we got increasing=False and no warnings + is_increasing = assert_no_warnings(check_increasing, x, y) + assert_false(is_increasing) + + +def test_check_ci_warn(): + x = [0, 1, 2, 3, 4, 5] + y = [0, -1, 2, -3, 4, -5] + + # Check that we got increasing=False and CI interval warning + is_increasing = assert_warns_message(UserWarning, "interval", + check_increasing, + x, y) + + assert_false(is_increasing) + + +def test_isotonic_regression(): + y = np.array([3, 7, 5, 9, 8, 7, 10]) + y_ = np.array([3, 6, 6, 8, 8, 8, 10]) + assert_array_equal(y_, isotonic_regression(y)) + + x = np.arange(len(y)) + ir = IsotonicRegression(y_min=0., y_max=1.) + ir.fit(x, y) + assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) + assert_array_equal(ir.transform(x), ir.predict(x)) + + # check that it is immune to permutation + perm = np.random.permutation(len(y)) + ir = IsotonicRegression(y_min=0., y_max=1.) + assert_array_equal(ir.fit_transform(x[perm], y[perm]), + ir.fit_transform(x, y)[perm]) + assert_array_equal(ir.transform(x[perm]), ir.transform(x)[perm]) + + # check we don't crash when all x are equal: + ir = IsotonicRegression() + assert_array_equal(ir.fit_transform(np.ones(len(x)), y), np.mean(y)) + + +def test_isotonic_regression_ties_min(): + # Setup examples with ties on minimum + x = [0, 1, 1, 2, 3, 4, 5] + y = [0, 1, 2, 3, 4, 5, 6] + y_true = [0, 1.5, 1.5, 3, 4, 5, 6] + + # Check that we get identical results for fit/transform and fit_transform + ir = IsotonicRegression() + ir.fit(x, y) + assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) + assert_array_equal(y_true, ir.fit_transform(x, y)) + + +def test_isotonic_regression_ties_max(): + # Setup examples with ties on maximum + x = [1, 2, 3, 4, 5, 5] + y = [1, 2, 3, 4, 5, 6] + y_true = [1, 2, 3, 4, 5.5, 5.5] + + # Check that we get identical results for fit/transform and fit_transform + ir = IsotonicRegression() + ir.fit(x, y) + assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) + assert_array_equal(y_true, ir.fit_transform(x, y)) + + +def test_isotonic_regression_ties_secondary_(): + """ + Test isotonic regression fit, transform and fit_transform + against the "secondary" ties method and "pituitary" data from R + "isotone" package, as detailed in: J. d. Leeuw, K. Hornik, P. Mair, + Isotone Optimization in R: Pool-Adjacent-Violators Algorithm + (PAVA) and Active Set Methods + + Set values based on pituitary example and + the following R command detailed in the paper above: + > library("isotone") + > data("pituitary") + > res1 <- gpava(pituitary$age, pituitary$size, ties="secondary") + > res1$x + + `isotone` version: 1.0-2, 2014-09-07 + R version: R version 3.1.1 (2014-07-10) + """ + x = [8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14] + y = [21, 23.5, 23, 24, 21, 25, 21.5, 22, 19, 23.5, 25] + y_true = [22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, + 22.22222, 22.22222, 22.22222, 24.25, 24.25] + + # Check fit, transform and fit_transform + ir = IsotonicRegression() + ir.fit(x, y) + assert_array_almost_equal(ir.transform(x), y_true, 4) + assert_array_almost_equal(ir.fit_transform(x, y), y_true, 4) + + +def test_isotonic_regression_reversed(): + y = np.array([10, 9, 10, 7, 6, 6.1, 5]) + y_ = IsotonicRegression(increasing=False).fit_transform( + np.arange(len(y)), y) + assert_array_equal(np.ones(y_[:-1].shape), ((y_[:-1] - y_[1:]) >= 0)) + + +def test_isotonic_regression_auto_decreasing(): + # Set y and x for decreasing + y = np.array([10, 9, 10, 7, 6, 6.1, 5]) + x = np.arange(len(y)) + + # Create model and fit_transform + ir = IsotonicRegression(increasing='auto') + y_ = assert_no_warnings(ir.fit_transform, x, y) + + # Check that relationship decreases + is_increasing = y_[0] < y_[-1] + assert_false(is_increasing) + + +def test_isotonic_regression_auto_increasing(): + # Set y and x for decreasing + y = np.array([5, 6.1, 6, 7, 10, 9, 10]) + x = np.arange(len(y)) + + # Create model and fit_transform + ir = IsotonicRegression(increasing='auto') + y_ = assert_no_warnings(ir.fit_transform, x, y) + + # Check that relationship increases + is_increasing = y_[0] < y_[-1] + assert_true(is_increasing) + + +def test_assert_raises_exceptions(): + ir = IsotonicRegression() + rng = np.random.RandomState(42) + assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) + assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) + assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) + assert_raises(ValueError, ir.transform, rng.randn(3, 10)) + + +def test_isotonic_sample_weight_parameter_default_value(): + # check if default value of sample_weight parameter is one + ir = IsotonicRegression() + # random test data + rng = np.random.RandomState(42) + n = 100 + x = np.arange(n) + y = rng.randint(-50, 50, size=(n,)) + 50. * np.log(1 + np.arange(n)) + # check if value is correctly used + weights = np.ones(n) + y_set_value = ir.fit_transform(x, y, sample_weight=weights) + y_default_value = ir.fit_transform(x, y) + + assert_array_equal(y_set_value, y_default_value) + + +def test_isotonic_min_max_boundaries(): + # check if min value is used correctly + ir = IsotonicRegression(y_min=2, y_max=4) + n = 6 + x = np.arange(n) + y = np.arange(n) + y_test = [2, 2, 2, 3, 4, 4] + y_result = np.round(ir.fit_transform(x, y)) + assert_array_equal(y_result, y_test) + + +def test_isotonic_sample_weight(): + ir = IsotonicRegression() + x = [1, 2, 3, 4, 5, 6, 7] + y = [1, 41, 51, 1, 2, 5, 24] + sample_weight = [1, 2, 3, 4, 5, 6, 7] + expected_y = [1, 13.95, 13.95, 13.95, 13.95, 13.95, 24] + received_y = ir.fit_transform(x, y, sample_weight=sample_weight) + + assert_array_equal(expected_y, received_y) + + +def test_isotonic_regression_oob_raise(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") + ir.fit(x, y) + + # Check that an exception is thrown + assert_raises(ValueError, ir.predict, [min(x) - 10, max(x) + 10]) + + +def test_isotonic_regression_oob_clip(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") + ir.fit(x, y) + + # Predict from training and test x and check that min/max match. + y1 = ir.predict([min(x) - 10, max(x) + 10]) + y2 = ir.predict(x) + assert_equal(max(y1), max(y2)) + assert_equal(min(y1), min(y2)) + + +def test_isotonic_regression_oob_nan(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="nan") + ir.fit(x, y) + + # Predict from training and test x and check that we have two NaNs. + y1 = ir.predict([min(x) - 10, max(x) + 10]) + assert_equal(sum(np.isnan(y1)), 2) + + +def test_isotonic_regression_oob_bad(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="xyz") + + # Make sure that we throw an error for bad out_of_bounds value + assert_raises(ValueError, ir.fit, x, y) + + +def test_isotonic_regression_oob_bad_after(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") + + # Make sure that we throw an error for bad out_of_bounds value in transform + ir.fit(x, y) + ir.out_of_bounds = "xyz" + assert_raises(ValueError, ir.transform, x) + + +def test_isotonic_regression_pickle(): + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") + ir.fit(x, y) + + ir_ser = pickle.dumps(ir, pickle.HIGHEST_PROTOCOL) + ir2 = pickle.loads(ir_ser) + np.testing.assert_array_equal(ir.predict(x), ir2.predict(x)) + + +def test_isotonic_duplicate_min_entry(): + x = [0, 0, 1] + y = [0, 0, 1] + + ir = IsotonicRegression(increasing=True, out_of_bounds="clip") + ir.fit(x, y) + all_predictions_finite = np.all(np.isfinite(ir.predict(x))) + assert_true(all_predictions_finite) + + +def test_isotonic_zero_weight_loop(): + # Test from @ogrisel's issue: + # https://github.com/scikit-learn/scikit-learn/issues/4297 + + # Get deterministic RNG with seed + rng = np.random.RandomState(42) + + # Create regression and samples + regression = IsotonicRegression() + n_samples = 50 + x = np.linspace(-3, 3, n_samples) + y = x + rng.uniform(size=n_samples) + + # Get some random weights and zero out + w = rng.uniform(size=n_samples) + w[5:8] = 0 + regression.fit(x, y, sample_weight=w) + + # This will hang in failure case. + regression.fit(x, y, sample_weight=w) + +""" Python Character Mapping Codec cp1257 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1257.TXT' with gencodec.py. + +"""#" + +import codecs + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self,input,errors='strict'): + return codecs.charmap_encode(input,errors,encoding_table) + + def decode(self,input,errors='strict'): + return codecs.charmap_decode(input,errors,decoding_table) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input,self.errors,encoding_table)[0] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input,self.errors,decoding_table)[0] + +class StreamWriter(Codec,codecs.StreamWriter): + pass + +class StreamReader(Codec,codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='cp1257', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) + + +### Decoding Table + +decoding_table = ( + u'\x00' # 0x00 -> NULL + u'\x01' # 0x01 -> START OF HEADING + u'\x02' # 0x02 -> START OF TEXT + u'\x03' # 0x03 -> END OF TEXT + u'\x04' # 0x04 -> END OF TRANSMISSION + u'\x05' # 0x05 -> ENQUIRY + u'\x06' # 0x06 -> ACKNOWLEDGE + u'\x07' # 0x07 -> BELL + u'\x08' # 0x08 -> BACKSPACE + u'\t' # 0x09 -> HORIZONTAL TABULATION + u'\n' # 0x0A -> LINE FEED + u'\x0b' # 0x0B -> VERTICAL TABULATION + u'\x0c' # 0x0C -> FORM FEED + u'\r' # 0x0D -> CARRIAGE RETURN + u'\x0e' # 0x0E -> SHIFT OUT + u'\x0f' # 0x0F -> SHIFT IN + u'\x10' # 0x10 -> DATA LINK ESCAPE + u'\x11' # 0x11 -> DEVICE CONTROL ONE + u'\x12' # 0x12 -> DEVICE CONTROL TWO + u'\x13' # 0x13 -> DEVICE CONTROL THREE + u'\x14' # 0x14 -> DEVICE CONTROL FOUR + u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE + u'\x16' # 0x16 -> SYNCHRONOUS IDLE + u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK + u'\x18' # 0x18 -> CANCEL + u'\x19' # 0x19 -> END OF MEDIUM + u'\x1a' # 0x1A -> SUBSTITUTE + u'\x1b' # 0x1B -> ESCAPE + u'\x1c' # 0x1C -> FILE SEPARATOR + u'\x1d' # 0x1D -> GROUP SEPARATOR + u'\x1e' # 0x1E -> RECORD SEPARATOR + u'\x1f' # 0x1F -> UNIT SEPARATOR + u' ' # 0x20 -> SPACE + u'!' # 0x21 -> EXCLAMATION MARK + u'"' # 0x22 -> QUOTATION MARK + u'#' # 0x23 -> NUMBER SIGN + u'$' # 0x24 -> DOLLAR SIGN + u'%' # 0x25 -> PERCENT SIGN + u'&' # 0x26 -> AMPERSAND + u"'" # 0x27 -> APOSTROPHE + u'(' # 0x28 -> LEFT PARENTHESIS + u')' # 0x29 -> RIGHT PARENTHESIS + u'*' # 0x2A -> ASTERISK + u'+' # 0x2B -> PLUS SIGN + u',' # 0x2C -> COMMA + u'-' # 0x2D -> HYPHEN-MINUS + u'.' # 0x2E -> FULL STOP + u'/' # 0x2F -> SOLIDUS + u'0' # 0x30 -> DIGIT ZERO + u'1' # 0x31 -> DIGIT ONE + u'2' # 0x32 -> DIGIT TWO + u'3' # 0x33 -> DIGIT THREE + u'4' # 0x34 -> DIGIT FOUR + u'5' # 0x35 -> DIGIT FIVE + u'6' # 0x36 -> DIGIT SIX + u'7' # 0x37 -> DIGIT SEVEN + u'8' # 0x38 -> DIGIT EIGHT + u'9' # 0x39 -> DIGIT NINE + u':' # 0x3A -> COLON + u';' # 0x3B -> SEMICOLON + u'<' # 0x3C -> LESS-THAN SIGN + u'=' # 0x3D -> EQUALS SIGN + u'>' # 0x3E -> GREATER-THAN SIGN + u'?' # 0x3F -> QUESTION MARK + u'@' # 0x40 -> COMMERCIAL AT + u'A' # 0x41 -> LATIN CAPITAL LETTER A + u'B' # 0x42 -> LATIN CAPITAL LETTER B + u'C' # 0x43 -> LATIN CAPITAL LETTER C + u'D' # 0x44 -> LATIN CAPITAL LETTER D + u'E' # 0x45 -> LATIN CAPITAL LETTER E + u'F' # 0x46 -> LATIN CAPITAL LETTER F + u'G' # 0x47 -> LATIN CAPITAL LETTER G + u'H' # 0x48 -> LATIN CAPITAL LETTER H + u'I' # 0x49 -> LATIN CAPITAL LETTER I + u'J' # 0x4A -> LATIN CAPITAL LETTER J + u'K' # 0x4B -> LATIN CAPITAL LETTER K + u'L' # 0x4C -> LATIN CAPITAL LETTER L + u'M' # 0x4D -> LATIN CAPITAL LETTER M + u'N' # 0x4E -> LATIN CAPITAL LETTER N + u'O' # 0x4F -> LATIN CAPITAL LETTER O + u'P' # 0x50 -> LATIN CAPITAL LETTER P + u'Q' # 0x51 -> LATIN CAPITAL LETTER Q + u'R' # 0x52 -> LATIN CAPITAL LETTER R + u'S' # 0x53 -> LATIN CAPITAL LETTER S + u'T' # 0x54 -> LATIN CAPITAL LETTER T + u'U' # 0x55 -> LATIN CAPITAL LETTER U + u'V' # 0x56 -> LATIN CAPITAL LETTER V + u'W' # 0x57 -> LATIN CAPITAL LETTER W + u'X' # 0x58 -> LATIN CAPITAL LETTER X + u'Y' # 0x59 -> LATIN CAPITAL LETTER Y + u'Z' # 0x5A -> LATIN CAPITAL LETTER Z + u'[' # 0x5B -> LEFT SQUARE BRACKET + u'\\' # 0x5C -> REVERSE SOLIDUS + u']' # 0x5D -> RIGHT SQUARE BRACKET + u'^' # 0x5E -> CIRCUMFLEX ACCENT + u'_' # 0x5F -> LOW LINE + u'`' # 0x60 -> GRAVE ACCENT + u'a' # 0x61 -> LATIN SMALL LETTER A + u'b' # 0x62 -> LATIN SMALL LETTER B + u'c' # 0x63 -> LATIN SMALL LETTER C + u'd' # 0x64 -> LATIN SMALL LETTER D + u'e' # 0x65 -> LATIN SMALL LETTER E + u'f' # 0x66 -> LATIN SMALL LETTER F + u'g' # 0x67 -> LATIN SMALL LETTER G + u'h' # 0x68 -> LATIN SMALL LETTER H + u'i' # 0x69 -> LATIN SMALL LETTER I + u'j' # 0x6A -> LATIN SMALL LETTER J + u'k' # 0x6B -> LATIN SMALL LETTER K + u'l' # 0x6C -> LATIN SMALL LETTER L + u'm' # 0x6D -> LATIN SMALL LETTER M + u'n' # 0x6E -> LATIN SMALL LETTER N + u'o' # 0x6F -> LATIN SMALL LETTER O + u'p' # 0x70 -> LATIN SMALL LETTER P + u'q' # 0x71 -> LATIN SMALL LETTER Q + u'r' # 0x72 -> LATIN SMALL LETTER R + u's' # 0x73 -> LATIN SMALL LETTER S + u't' # 0x74 -> LATIN SMALL LETTER T + u'u' # 0x75 -> LATIN SMALL LETTER U + u'v' # 0x76 -> LATIN SMALL LETTER V + u'w' # 0x77 -> LATIN SMALL LETTER W + u'x' # 0x78 -> LATIN SMALL LETTER X + u'y' # 0x79 -> LATIN SMALL LETTER Y + u'z' # 0x7A -> LATIN SMALL LETTER Z + u'{' # 0x7B -> LEFT CURLY BRACKET + u'|' # 0x7C -> VERTICAL LINE + u'}' # 0x7D -> RIGHT CURLY BRACKET + u'~' # 0x7E -> TILDE + u'\x7f' # 0x7F -> DELETE + u'\u20ac' # 0x80 -> EURO SIGN + u'\ufffe' # 0x81 -> UNDEFINED + u'\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK + u'\ufffe' # 0x83 -> UNDEFINED + u'\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK + u'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS + u'\u2020' # 0x86 -> DAGGER + u'\u2021' # 0x87 -> DOUBLE DAGGER + u'\ufffe' # 0x88 -> UNDEFINED + u'\u2030' # 0x89 -> PER MILLE SIGN + u'\ufffe' # 0x8A -> UNDEFINED + u'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK + u'\ufffe' # 0x8C -> UNDEFINED + u'\xa8' # 0x8D -> DIAERESIS + u'\u02c7' # 0x8E -> CARON + u'\xb8' # 0x8F -> CEDILLA + u'\ufffe' # 0x90 -> UNDEFINED + u'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK + u'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK + u'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK + u'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK + u'\u2022' # 0x95 -> BULLET + u'\u2013' # 0x96 -> EN DASH + u'\u2014' # 0x97 -> EM DASH + u'\ufffe' # 0x98 -> UNDEFINED + u'\u2122' # 0x99 -> TRADE MARK SIGN + u'\ufffe' # 0x9A -> UNDEFINED + u'\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + u'\ufffe' # 0x9C -> UNDEFINED + u'\xaf' # 0x9D -> MACRON + u'\u02db' # 0x9E -> OGONEK + u'\ufffe' # 0x9F -> UNDEFINED + u'\xa0' # 0xA0 -> NO-BREAK SPACE + u'\ufffe' # 0xA1 -> UNDEFINED + u'\xa2' # 0xA2 -> CENT SIGN + u'\xa3' # 0xA3 -> POUND SIGN + u'\xa4' # 0xA4 -> CURRENCY SIGN + u'\ufffe' # 0xA5 -> UNDEFINED + u'\xa6' # 0xA6 -> BROKEN BAR + u'\xa7' # 0xA7 -> SECTION SIGN + u'\xd8' # 0xA8 -> LATIN CAPITAL LETTER O WITH STROKE + u'\xa9' # 0xA9 -> COPYRIGHT SIGN + u'\u0156' # 0xAA -> LATIN CAPITAL LETTER R WITH CEDILLA + u'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + u'\xac' # 0xAC -> NOT SIGN + u'\xad' # 0xAD -> SOFT HYPHEN + u'\xae' # 0xAE -> REGISTERED SIGN + u'\xc6' # 0xAF -> LATIN CAPITAL LETTER AE + u'\xb0' # 0xB0 -> DEGREE SIGN + u'\xb1' # 0xB1 -> PLUS-MINUS SIGN + u'\xb2' # 0xB2 -> SUPERSCRIPT TWO + u'\xb3' # 0xB3 -> SUPERSCRIPT THREE + u'\xb4' # 0xB4 -> ACUTE ACCENT + u'\xb5' # 0xB5 -> MICRO SIGN + u'\xb6' # 0xB6 -> PILCROW SIGN + u'\xb7' # 0xB7 -> MIDDLE DOT + u'\xf8' # 0xB8 -> LATIN SMALL LETTER O WITH STROKE + u'\xb9' # 0xB9 -> SUPERSCRIPT ONE + u'\u0157' # 0xBA -> LATIN SMALL LETTER R WITH CEDILLA + u'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + u'\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER + u'\xbd' # 0xBD -> VULGAR FRACTION ONE HALF + u'\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS + u'\xe6' # 0xBF -> LATIN SMALL LETTER AE + u'\u0104' # 0xC0 -> LATIN CAPITAL LETTER A WITH OGONEK + u'\u012e' # 0xC1 -> LATIN CAPITAL LETTER I WITH OGONEK + u'\u0100' # 0xC2 -> LATIN CAPITAL LETTER A WITH MACRON + u'\u0106' # 0xC3 -> LATIN CAPITAL LETTER C WITH ACUTE + u'\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS + u'\xc5' # 0xC5 -> LATIN CAPITAL LETTER A WITH RING ABOVE + u'\u0118' # 0xC6 -> LATIN CAPITAL LETTER E WITH OGONEK + u'\u0112' # 0xC7 -> LATIN CAPITAL LETTER E WITH MACRON + u'\u010c' # 0xC8 -> LATIN CAPITAL LETTER C WITH CARON + u'\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE + u'\u0179' # 0xCA -> LATIN CAPITAL LETTER Z WITH ACUTE + u'\u0116' # 0xCB -> LATIN CAPITAL LETTER E WITH DOT ABOVE + u'\u0122' # 0xCC -> LATIN CAPITAL LETTER G WITH CEDILLA + u'\u0136' # 0xCD -> LATIN CAPITAL LETTER K WITH CEDILLA + u'\u012a' # 0xCE -> LATIN CAPITAL LETTER I WITH MACRON + u'\u013b' # 0xCF -> LATIN CAPITAL LETTER L WITH CEDILLA + u'\u0160' # 0xD0 -> LATIN CAPITAL LETTER S WITH CARON + u'\u0143' # 0xD1 -> LATIN CAPITAL LETTER N WITH ACUTE + u'\u0145' # 0xD2 -> LATIN CAPITAL LETTER N WITH CEDILLA + u'\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE + u'\u014c' # 0xD4 -> LATIN CAPITAL LETTER O WITH MACRON + u'\xd5' # 0xD5 -> LATIN CAPITAL LETTER O WITH TILDE + u'\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS + u'\xd7' # 0xD7 -> MULTIPLICATION SIGN + u'\u0172' # 0xD8 -> LATIN CAPITAL LETTER U WITH OGONEK + u'\u0141' # 0xD9 -> LATIN CAPITAL LETTER L WITH STROKE + u'\u015a' # 0xDA -> LATIN CAPITAL LETTER S WITH ACUTE + u'\u016a' # 0xDB -> LATIN CAPITAL LETTER U WITH MACRON + u'\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS + u'\u017b' # 0xDD -> LATIN CAPITAL LETTER Z WITH DOT ABOVE + u'\u017d' # 0xDE -> LATIN CAPITAL LETTER Z WITH CARON + u'\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S + u'\u0105' # 0xE0 -> LATIN SMALL LETTER A WITH OGONEK + u'\u012f' # 0xE1 -> LATIN SMALL LETTER I WITH OGONEK + u'\u0101' # 0xE2 -> LATIN SMALL LETTER A WITH MACRON + u'\u0107' # 0xE3 -> LATIN SMALL LETTER C WITH ACUTE + u'\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS + u'\xe5' # 0xE5 -> LATIN SMALL LETTER A WITH RING ABOVE + u'\u0119' # 0xE6 -> LATIN SMALL LETTER E WITH OGONEK + u'\u0113' # 0xE7 -> LATIN SMALL LETTER E WITH MACRON + u'\u010d' # 0xE8 -> LATIN SMALL LETTER C WITH CARON + u'\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE + u'\u017a' # 0xEA -> LATIN SMALL LETTER Z WITH ACUTE + u'\u0117' # 0xEB -> LATIN SMALL LETTER E WITH DOT ABOVE + u'\u0123' # 0xEC -> LATIN SMALL LETTER G WITH CEDILLA + u'\u0137' # 0xED -> LATIN SMALL LETTER K WITH CEDILLA + u'\u012b' # 0xEE -> LATIN SMALL LETTER I WITH MACRON + u'\u013c' # 0xEF -> LATIN SMALL LETTER L WITH CEDILLA + u'\u0161' # 0xF0 -> LATIN SMALL LETTER S WITH CARON + u'\u0144' # 0xF1 -> LATIN SMALL LETTER N WITH ACUTE + u'\u0146' # 0xF2 -> LATIN SMALL LETTER N WITH CEDILLA + u'\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE + u'\u014d' # 0xF4 -> LATIN SMALL LETTER O WITH MACRON + u'\xf5' # 0xF5 -> LATIN SMALL LETTER O WITH TILDE + u'\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS + u'\xf7' # 0xF7 -> DIVISION SIGN + u'\u0173' # 0xF8 -> LATIN SMALL LETTER U WITH OGONEK + u'\u0142' # 0xF9 -> LATIN SMALL LETTER L WITH STROKE + u'\u015b' # 0xFA -> LATIN SMALL LETTER S WITH ACUTE + u'\u016b' # 0xFB -> LATIN SMALL LETTER U WITH MACRON + u'\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS + u'\u017c' # 0xFD -> LATIN SMALL LETTER Z WITH DOT ABOVE + u'\u017e' # 0xFE -> LATIN SMALL LETTER Z WITH CARON + u'\u02d9' # 0xFF -> DOT ABOVE +) + +### Encoding table +encoding_table=codecs.charmap_build(decoding_table) + +#!/usr/bin/env python +# Copyright (c) 2012 The LibYuv Project Authors. All rights reserved. +# +# Use of this source code is governed by a BSD-style license +# that can be found in the LICENSE file in the root of the source +# tree. An additional intellectual property rights grant can be found +# in the file PATENTS. All contributing project authors may +# be found in the AUTHORS file in the root of the source tree. + +"""Runs various libyuv tests through valgrind_test.py. + +This script inherits the chrome_tests.py in Chrome, but allows running any test +instead of only the hard-coded ones. It uses the -t cmdline flag to do this, and +only supports specifying a single test for each run. + +Suppression files: +The Chrome valgrind directory we use as a DEPS dependency contains the following +suppression files: + valgrind/memcheck/suppressions.txt + valgrind/memcheck/suppressions_mac.txt + valgrind/tsan/suppressions.txt + valgrind/tsan/suppressions_mac.txt + valgrind/tsan/suppressions_win32.txt +Since they're referenced from the chrome_tests.py script, we have similar files +below the directory of this script. When executing, this script will setup both +Chrome's suppression files and our own, so we can easily maintain libyuv +specific suppressions in our own files. +""" + +import logging +import optparse +import os +import sys + +import logging_utils +import path_utils + +import chrome_tests + + +class LibyuvTest(chrome_tests.ChromeTests): + """Class that handles setup of suppressions for libyuv. + + Everything else is inherited from chrome_tests.ChromeTests. + """ + + def _DefaultCommand(self, tool, exe=None, valgrind_test_args=None): + """Override command-building method so we can add more suppressions.""" + cmd = chrome_tests.ChromeTests._DefaultCommand(self, tool, exe, + valgrind_test_args) + # When ChromeTests._DefaultCommand has executed, it has setup suppression + # files based on what's found in the memcheck/ or tsan/ subdirectories of + # this script's location. If Mac or Windows is executing, additional + # platform specific files have also been added. + # Since only the ones located below this directory is added, we must also + # add the ones maintained by Chrome, located in ../valgrind. + + # The idea is to look for --suppression arguments in the cmd list and add a + # modified copy of each suppression file, for the corresponding file in + # ../valgrind. If we would simply replace 'valgrind-libyuv' with 'valgrind' + # we may produce invalid paths if other parts of the path contain that + # string. That's why the code below only replaces the end of the path. + script_dir = path_utils.ScriptDir() + old_base, _ = os.path.split(script_dir) + new_dir = os.path.join(old_base, 'valgrind') + add_suppressions = [] + for token in cmd: + if '--suppressions' in token: + add_suppressions.append(token.replace(script_dir, new_dir)) + return add_suppressions + cmd + + +def main(_): + parser = optparse.OptionParser('usage: %prog -b -t ') + parser.disable_interspersed_args() + parser.add_option('-b', '--build-dir', + help=('Location of the compiler output. Can only be used ' + 'when the test argument does not contain this path.')) + parser.add_option("--target", help="Debug or Release") + parser.add_option('-t', '--test', help='Test to run.') + parser.add_option('', '--baseline', action='store_true', default=False, + help='Generate baseline data instead of validating') + parser.add_option('', '--gtest_filter', + help='Additional arguments to --gtest_filter') + parser.add_option('', '--gtest_repeat', + help='Argument for --gtest_repeat') + parser.add_option("--gtest_shuffle", action="store_true", default=False, + help="Randomize tests' orders on every iteration.") + parser.add_option("--gtest_break_on_failure", action="store_true", + default=False, + help="Drop in to debugger on assertion failure. Also " + "useful for forcing tests to exit with a stack dump " + "on the first assertion failure when running with " + "--gtest_repeat=-1") + parser.add_option('-v', '--verbose', action='store_true', default=False, + help='Verbose output - enable debug log messages') + parser.add_option('', '--tool', dest='valgrind_tool', default='memcheck', + help='Specify a valgrind tool to run the tests under') + parser.add_option('', '--tool_flags', dest='valgrind_tool_flags', default='', + help='Specify custom flags for the selected valgrind tool') + parser.add_option('', '--keep_logs', action='store_true', default=False, + help=('Store memory tool logs in the .logs directory ' + 'instead of /tmp.\nThis can be useful for tool ' + 'developers/maintainers.\nPlease note that the ' + '.logs directory will be clobbered on tool startup.')) + parser.add_option("--test-launcher-bot-mode", action="store_true", + help="run the tests with --test-launcher-bot-mode") + parser.add_option("--test-launcher-total-shards", type=int, + help="run the tests with --test-launcher-total-shards") + parser.add_option("--test-launcher-shard-index", type=int, + help="run the tests with --test-launcher-shard-index") + options, args = parser.parse_args() + + if options.verbose: + logging_utils.config_root(logging.DEBUG) + else: + logging_utils.config_root() + + if not options.test: + parser.error('--test not specified') + + # Support build dir both with and without the target. + if (options.target and options.build_dir and + not options.build_dir.endswith(options.target)): + options.build_dir = os.path.join(options.build_dir, options.target) + + # If --build_dir is provided, prepend it to the test executable if needed. + test_executable = options.test + if options.build_dir and not test_executable.startswith(options.build_dir): + test_executable = os.path.join(options.build_dir, test_executable) + args = [test_executable] + args + + test = LibyuvTest(options, args, 'cmdline') + return test.Run() + +if __name__ == '__main__': + return_code = main(sys.argv) + sys.exit(return_code) + +import sys +import exceptions + +import numpy as np +from numpy.ctypeslib import ndpointer, load_library +from numpy.testing import * + +try: + cdll = load_library('multiarray', np.core.multiarray.__file__) + _HAS_CTYPE = True +except ImportError: + _HAS_CTYPE = False +except exceptions.OSError, e: + _HAS_CTYPE = False + +class TestLoadLibrary(TestCase): + @dec.skipif(not _HAS_CTYPE, "ctypes not available on this python installation") + @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin") + def test_basic(self): + try: + cdll = load_library('multiarray', + np.core.multiarray.__file__) + except ImportError, e: + msg = "ctypes is not available on this python: skipping the test" \ + " (import error was: %s)" % str(e) + print msg + + @dec.skipif(not _HAS_CTYPE, "ctypes not available on this python installation") + @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin") + def test_basic2(self): + """Regression for #801: load_library with a full library name + (including extension) does not work.""" + try: + try: + from distutils import sysconfig + so = sysconfig.get_config_var('SO') + cdll = load_library('multiarray%s' % so, + np.core.multiarray.__file__) + except ImportError: + print "No distutils available, skipping test." + except ImportError, e: + msg = "ctypes is not available on this python: skipping the test" \ + " (import error was: %s)" % str(e) + print msg + +class TestNdpointer(TestCase): + def test_dtype(self): + dt = np.intc + p = ndpointer(dtype=dt) + self.assert_(p.from_param(np.array([1], dt))) + dt = 'i4') + p = ndpointer(dtype=dt) + p.from_param(np.array([1], dt)) + self.assertRaises(TypeError, p.from_param, + np.array([1], dt.newbyteorder('swap'))) + dtnames = ['x', 'y'] + dtformats = [np.intc, np.float64] + dtdescr = {'names' : dtnames, 'formats' : dtformats} + dt = np.dtype(dtdescr) + p = ndpointer(dtype=dt) + self.assert_(p.from_param(np.zeros((10,), dt))) + samedt = np.dtype(dtdescr) + p = ndpointer(dtype=samedt) + self.assert_(p.from_param(np.zeros((10,), dt))) + dt2 = np.dtype(dtdescr, align=True) + if dt.itemsize != dt2.itemsize: + self.assertRaises(TypeError, p.from_param, np.zeros((10,), dt2)) + else: + self.assert_(p.from_param(np.zeros((10,), dt2))) + + def test_ndim(self): + p = ndpointer(ndim=0) + self.assert_(p.from_param(np.array(1))) + self.assertRaises(TypeError, p.from_param, np.array([1])) + p = ndpointer(ndim=1) + self.assertRaises(TypeError, p.from_param, np.array(1)) + self.assert_(p.from_param(np.array([1]))) + p = ndpointer(ndim=2) + self.assert_(p.from_param(np.array([[1]]))) + + def test_shape(self): + p = ndpointer(shape=(1,2)) + self.assert_(p.from_param(np.array([[1,2]]))) + self.assertRaises(TypeError, p.from_param, np.array([[1],[2]])) + p = ndpointer(shape=()) + self.assert_(p.from_param(np.array(1))) + + def test_flags(self): + x = np.array([[1,2,3]], order='F') + p = ndpointer(flags='FORTRAN') + self.assert_(p.from_param(x)) + p = ndpointer(flags='CONTIGUOUS') + self.assertRaises(TypeError, p.from_param, x) + p = ndpointer(flags=x.flags.num) + self.assert_(p.from_param(x)) + self.assertRaises(TypeError, p.from_param, np.array([[1,2,3]])) + + +if hasattr(sys, 'gettotalrefcount'): + # skip this test class when Python was compiled using + # the --with-pydebug option. This is necessary because, i.e. + # type("foo", (object,), {}) + # leaks references + del TestNdpointer + +if __name__ == "__main__": + run_module_suite() + +from __future__ import division, print_function, absolute_import + +import os +import sys +if sys.version_info[0] >= 3: + from io import StringIO +else: + from StringIO import StringIO +import tempfile + +import numpy as np + +from numpy.testing import TestCase, assert_equal, \ + assert_array_almost_equal_nulp + +from scipy.sparse import coo_matrix, csc_matrix, rand + +from scipy.io import hb_read, hb_write +from scipy.io.harwell_boeing import HBFile, HBInfo + + +SIMPLE = """\ +No Title |No Key + 9 4 1 4 +RUA 100 100 10 0 +(26I3) (26I3) (3E23.15) +1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9 +9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11 +37 71 89 18 30 45 70 19 25 52 +2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01 +6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01 +4.196478590163001e-01 5.649603072111251e-01 9.934423887087086e-01 +6.912334991524289e-01 +""" + +SIMPLE_MATRIX = coo_matrix( + ( + (0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799, + 0.0661749042483, 0.887037034319, 0.419647859016, + 0.564960307211, 0.993442388709, 0.691233499152,), + (np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51], + [0, 4, 58, 61, 61, 72, 72, 73, 99, 99]])))) + + +def assert_csc_almost_equal(r, l): + r = csc_matrix(r) + l = csc_matrix(l) + assert_equal(r.indptr, l.indptr) + assert_equal(r.indices, l.indices) + assert_array_almost_equal_nulp(r.data, l.data, 10000) + + +class TestHBReader(TestCase): + def test_simple(self): + m = hb_read(StringIO(SIMPLE)) + assert_csc_almost_equal(m, SIMPLE_MATRIX) + + +class TestRBRoundtrip(TestCase): + def test_simple(self): + rm = rand(100, 1000, 0.05).tocsc() + fd, filename = tempfile.mkstemp(suffix="rb") + try: + hb_write(filename, rm, HBInfo.from_data(rm)) + m = hb_read(filename) + finally: + os.close(fd) + os.remove(filename) + + assert_csc_almost_equal(m, rm) + +""" +====================================== +Decision Tree Regression with AdaBoost +====================================== + +A decision tree is boosted using the AdaBoost.R2 [1] algorithm on a 1D +sinusoidal dataset with a small amount of Gaussian noise. +299 boosts (300 decision trees) is compared with a single decision tree +regressor. As the number of boosts is increased the regressor can fit more +detail. + +.. [1] H. Drucker, "Improving Regressors using Boosting Techniques", 1997. + +""" +print(__doc__) + +# Author: Noel Dawe +# +# License: BSD 3 clause + +# importing necessary libraries +import numpy as np +import matplotlib.pyplot as plt +from sklearn.tree import DecisionTreeRegressor +from sklearn.ensemble import AdaBoostRegressor + +# Create the dataset +rng = np.random.RandomState(1) +X = np.linspace(0, 6, 100)[:, np.newaxis] +y = np.sin(X).ravel() + np.sin(6 * X).ravel() + rng.normal(0, 0.1, X.shape[0]) + +# Fit regression model +regr_1 = DecisionTreeRegressor(max_depth=4) + +regr_2 = AdaBoostRegressor(DecisionTreeRegressor(max_depth=4), + n_estimators=300, random_state=rng) + +regr_1.fit(X, y) +regr_2.fit(X, y) + +# Predict +y_1 = regr_1.predict(X) +y_2 = regr_2.predict(X) + +# Plot the results +plt.figure() +plt.scatter(X, y, c="k", label="training samples") +plt.plot(X, y_1, c="g", label="n_estimators=1", linewidth=2) +plt.plot(X, y_2, c="r", label="n_estimators=300", linewidth=2) +plt.xlabel("data") +plt.ylabel("target") +plt.title("Boosted Decision Tree Regression") +plt.legend() +plt.show() + +#! test QC_JSON Schema with ghost atoms + +import numpy as np +import psi4 +import json + +# Generate JSON data +json_data = { + "schema_name": "qc_schema_input", + "schema_version": 1, + "molecule": { + "geometry": [ + 0.0, + 0.0, + -5.0, + 0.0, + 0.0, + 5.0, + ], + "symbols": ["He", "He"], + "real": [True, False] + }, + "driver": "energy", + "model": { + "method": "SCF", + "basis": "cc-pVDZ" + }, + "keywords": { + "scf_type": "df" + }, + "memory": 1024 * 1024 * 1024, + "nthreads": 1, +} + +# Write expected output +expected_return_result = -2.85518836280515 +expected_properties = { + 'calcinfo_nbasis': 10, + 'calcinfo_nmo': 10, + 'calcinfo_nalpha': 1, + 'calcinfo_nbeta': 1, + 'calcinfo_natom': 2, + 'scf_one_electron_energy': -3.8820496359492576, + 'scf_two_electron_energy': 1.0268612731441076, + 'nuclear_repulsion_energy': 0.0, + 'scf_total_energy': -2.85518836280515, + 'return_energy': -2.85518836280515 +} + +json_ret = psi4.json_wrapper.run_json(json_data) + +with open("output.json", "w") as ofile: #TEST + json.dump(json_ret, ofile, indent=2) #TEST + +psi4.compare_integers(True, json_ret["success"], "JSON Success") #TEST +psi4.compare_values(expected_return_result, json_ret["return_result"], 5, "Return Value") #TEST + +for k in expected_properties.keys(): #TEST + psi4.compare_values(expected_properties[k], json_ret["properties"][k], 5, k.upper()) #TEST + + +""" +Testing for the base module (sklearn.ensemble.base). +""" + +# Authors: Gilles Louppe +# License: BSD 3 clause + +from numpy.testing import assert_equal +from nose.tools import assert_true + +from sklearn.utils.testing import assert_raise_message +from sklearn.datasets import load_iris +from sklearn.ensemble import BaggingClassifier +from sklearn.linear_model import Perceptron + + +def test_base(): + # Check BaseEnsemble methods. + ensemble = BaggingClassifier(base_estimator=Perceptron(), n_estimators=3) + + iris = load_iris() + ensemble.fit(iris.data, iris.target) + ensemble.estimators_ = [] # empty the list and create estimators manually + + ensemble._make_estimator() + ensemble._make_estimator() + ensemble._make_estimator() + ensemble._make_estimator(append=False) + + assert_equal(3, len(ensemble)) + assert_equal(3, len(ensemble.estimators_)) + + assert_true(isinstance(ensemble[0], Perceptron)) + + +def test_base_zero_n_estimators(): + # Check that instantiating a BaseEnsemble with n_estimators<=0 raises + # a ValueError. + ensemble = BaggingClassifier(base_estimator=Perceptron(), n_estimators=0) + iris = load_iris() + assert_raise_message(ValueError, + "n_estimators must be greater than zero, got 0.", + ensemble.fit, iris.data, iris.target) + +from django.conf import settings +from django.contrib.sites.models import Site +from django.http import HttpResponseRedirect, Http404 +from django.views.decorators.cache import cache_page + +import waffle + +from kitsune.inproduct.models import Redirect +from kitsune.sumo.helpers import urlparams + + +@cache_page(24 * 60 * 60) # 24 hours. +def redirect(request, product, version, platform, locale, topic=None): + """Redirect in-product URLs to the right place.""" + redirects = Redirect.objects.all() + + # In order from least to most important. + parts = ('locale', 'product', 'version', 'platform', 'topic') + + # First we remove any redirects that explicitly don't match. Do this in + # Python to avoid an explosion of cache use. + t = topic if topic else '' + + def f(redirect): + matches = ( + redirect.product.lower() in (product.lower(), ''), + redirect.version.lower() in (version.lower(), ''), + redirect.platform.lower() in (platform.lower(), ''), + redirect.locale.lower() in (locale.lower(), ''), + redirect.topic.lower() == t.lower(), + ) + return all(matches) + + redirects = filter(f, redirects) + + # Assign a ordinal (score) to each redirect based on how specific it is, + # then order by score descending. + # + # Scores are weighted by powers of 2 so that specifying the most important + # field (i.e. topic) outweighs specifying all 4 other fields. This means + # we should find the correct match faster in most common cases. + # For example, if you have two redirects that have topic='foo', and one + # of them also has platform='mac', and one with platform='win', they'll + # sort like: + # 24, Redirect(topic='foo', platform='mac') + # 16, Redirect(topic='foo') + # 8, Redirect(platform='win') + # Macs going to 'foo' will will hit the first redirect. Everyone else + # going to 'foo' will hit the second. (Windows users going to 'foo' would + # never match Redirect(platform='win') but if it sorted higher, it would + # take longer to get there.) + def ordinal(redirect): + score = 0 + for i, part in enumerate(parts): + if getattr(redirect, part) != '': + score += 1 << i + return score, redirect + + ordered = map(ordinal, redirects) + ordered.sort(key=lambda x: x[0], reverse=True) + + # A redirect matches if all its fields match. A field matches if it is + # blank or matches the input. + def matches(redirect, **kw): + for part in parts: + attr = getattr(redirect, part) + if attr != '': + v = kw[part] if kw[part] else '' + if attr.lower() != v.lower(): + return False + return True + + # As soon as we've found a match, that's the best one. + destination = None + for score, redirect in ordered: + if matches(redirect, product=product, version=version, + platform=platform, locale=locale, topic=topic): + destination = redirect + break + + # Oh noes! We didn't find a target. + if not destination: + raise Http404 + + # If the target starts with HTTP, we don't add a locale or query string + # params. + if destination.target.startswith('http'): + target = destination.target + else: + params = { + 'as': 'u', + 'utm_source': 'inproduct'} + if hasattr(request, 'eu_build'): + params['eu'] = 1 + target = u'/%s/%s' % (locale, destination.target.lstrip('/')) + target = urlparams(target, **params) + + # Switch over to HTTPS if we DEBUG=False and sample is active. + if not settings.DEBUG and waffle.sample_is_active('inproduct-https'): + domain = Site.objects.get_current().domain + target = 'https://%s%s' % (domain, target) + + # 302 because these can change over time. + return HttpResponseRedirect(target) + +# coding: utf-8 +# Copyright (c) Pymatgen Development Team. +# Distributed under the terms of the MIT License. + +from __future__ import division, unicode_literals + +__author__ = "Bharat Medasani" +__copyright__ = "Copyright 2013, The Materials Project" +__version__ = "0.1" +__maintainer__ = "Shyue Ping Ong" +__email__ = "bkmedasani@lbl.gov" +__date__ = "Aug 2, 2013" + +import unittest +import os +import re + +from pymatgen.core.periodic_table import Specie +from pymatgen.core.structure import Structure, Molecule +from pymatgen.io.cif import CifParser +from pymatgen.io.zeopp import ZeoCssr, ZeoVoronoiXYZ, get_voronoi_nodes, \ + get_high_accuracy_voronoi_nodes, get_void_volume_surfarea, \ + get_free_sphere_params +from pymatgen.io.vasp.inputs import Poscar +from pymatgen.analysis.bond_valence import BVAnalyzer + +try: + import zeo +except ImportError: + zeo = None + +test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", + 'test_files') + + +@unittest.skipIf(not zeo, "zeo not present.") +class ZeoCssrTest(unittest.TestCase): + def setUp(self): + filepath = os.path.join(test_dir, 'POSCAR') + p = Poscar.from_file(filepath) + self.zeocssr = ZeoCssr(p.structure) + + def test_str(self): + expected_string = """4.7595 10.4118 6.0672 +90.00 90.00 90.00 SPGR = 1 P 1 OPT = 1 +24 0 +0 Fe4 P4 O16 +1 Fe 0.4749 0.2187 0.7500 0 0 0 0 0 0 0 0 0.0000 +2 Fe 0.9749 0.2813 0.2500 0 0 0 0 0 0 0 0 0.0000 +3 Fe 0.0251 0.7187 0.7500 0 0 0 0 0 0 0 0 0.0000 +4 Fe 0.5251 0.7813 0.2500 0 0 0 0 0 0 0 0 0.0000 +5 P 0.4182 0.0946 0.2500 0 0 0 0 0 0 0 0 0.0000 +6 P 0.9182 0.4054 0.7500 0 0 0 0 0 0 0 0 0.0000 +7 P 0.0818 0.5946 0.2500 0 0 0 0 0 0 0 0 0.0000 +8 P 0.5818 0.9054 0.7500 0 0 0 0 0 0 0 0 0.0000 +9 O 0.7071 0.0434 0.7500 0 0 0 0 0 0 0 0 0.0000 +10 O 0.7413 0.0966 0.2500 0 0 0 0 0 0 0 0 0.0000 +11 O 0.2854 0.1657 0.0461 0 0 0 0 0 0 0 0 0.0000 +12 O 0.2854 0.1657 0.4539 0 0 0 0 0 0 0 0 0.0000 +13 O 0.7854 0.3343 0.5461 0 0 0 0 0 0 0 0 0.0000 +14 O 0.7854 0.3343 0.9539 0 0 0 0 0 0 0 0 0.0000 +15 O 0.2413 0.4034 0.7500 0 0 0 0 0 0 0 0 0.0000 +16 O 0.2071 0.4566 0.2500 0 0 0 0 0 0 0 0 0.0000 +17 O 0.7929 0.5434 0.7500 0 0 0 0 0 0 0 0 0.0000 +18 O 0.7587 0.5966 0.2500 0 0 0 0 0 0 0 0 0.0000 +19 O 0.2146 0.6657 0.0461 0 0 0 0 0 0 0 0 0.0000 +20 O 0.2146 0.6657 0.4539 0 0 0 0 0 0 0 0 0.0000 +21 O 0.7146 0.8343 0.5461 0 0 0 0 0 0 0 0 0.0000 +22 O 0.7146 0.8343 0.9539 0 0 0 0 0 0 0 0 0.0000 +23 O 0.2587 0.9034 0.7500 0 0 0 0 0 0 0 0 0.0000 +24 O 0.2929 0.9566 0.2500 0 0 0 0 0 0 0 0 0.0000""" + self.assertEqual(str(self.zeocssr), expected_string) + + def test_from_file(self): + filename = os.path.join(test_dir, "EDI.cssr") + zeocssr = ZeoCssr.from_file(filename) + self.assertIsInstance(zeocssr.structure, Structure) + + +#@unittest.skipIf(not zeo, "zeo not present.") +class ZeoCssrOxiTest(unittest.TestCase): + def setUp(self): + filepath = os.path.join(test_dir, 'POSCAR') + p = Poscar.from_file(filepath) + structure = BVAnalyzer().get_oxi_state_decorated_structure(p.structure) + self.zeocssr = ZeoCssr(structure) + + def test_str(self): + expected_string = """4.7595 10.4118 6.0672 +90.00 90.00 90.00 SPGR = 1 P 1 OPT = 1 +24 0 +0 Fe4 P4 O16 +1 Fe3+ 0.4749 0.2187 0.7500 0 0 0 0 0 0 0 0 0.0000 +2 Fe3+ 0.9749 0.2813 0.2500 0 0 0 0 0 0 0 0 0.0000 +3 Fe3+ 0.0251 0.7187 0.7500 0 0 0 0 0 0 0 0 0.0000 +4 Fe3+ 0.5251 0.7813 0.2500 0 0 0 0 0 0 0 0 0.0000 +5 P5+ 0.4182 0.0946 0.2500 0 0 0 0 0 0 0 0 0.0000 +6 P5+ 0.9182 0.4054 0.7500 0 0 0 0 0 0 0 0 0.0000 +7 P5+ 0.0818 0.5946 0.2500 0 0 0 0 0 0 0 0 0.0000 +8 P5+ 0.5818 0.9054 0.7500 0 0 0 0 0 0 0 0 0.0000 +9 O2- 0.7071 0.0434 0.7500 0 0 0 0 0 0 0 0 0.0000 +10 O2- 0.7413 0.0966 0.2500 0 0 0 0 0 0 0 0 0.0000 +11 O2- 0.2854 0.1657 0.0461 0 0 0 0 0 0 0 0 0.0000 +12 O2- 0.2854 0.1657 0.4539 0 0 0 0 0 0 0 0 0.0000 +13 O2- 0.7854 0.3343 0.5461 0 0 0 0 0 0 0 0 0.0000 +14 O2- 0.7854 0.3343 0.9539 0 0 0 0 0 0 0 0 0.0000 +15 O2- 0.2413 0.4034 0.7500 0 0 0 0 0 0 0 0 0.0000 +16 O2- 0.2071 0.4566 0.2500 0 0 0 0 0 0 0 0 0.0000 +17 O2- 0.7929 0.5434 0.7500 0 0 0 0 0 0 0 0 0.0000 +18 O2- 0.7587 0.5966 0.2500 0 0 0 0 0 0 0 0 0.0000 +19 O2- 0.2146 0.6657 0.0461 0 0 0 0 0 0 0 0 0.0000 +20 O2- 0.2146 0.6657 0.4539 0 0 0 0 0 0 0 0 0.0000 +21 O2- 0.7146 0.8343 0.5461 0 0 0 0 0 0 0 0 0.0000 +22 O2- 0.7146 0.8343 0.9539 0 0 0 0 0 0 0 0 0.0000 +23 O2- 0.2587 0.9034 0.7500 0 0 0 0 0 0 0 0 0.0000 +24 O2- 0.2929 0.9566 0.2500 0 0 0 0 0 0 0 0 0.0000""" + self.assertEqual(str(self.zeocssr), expected_string) + + def test_from_file(self): + filename = os.path.join(test_dir, "EDI_oxistate_decorated.cssr") + zeocssr = ZeoCssr.from_file(filename) + self.assertIsInstance(zeocssr.structure, Structure) + + +@unittest.skipIf(not zeo, "zeo not present.") +class ZeoVoronoiXYZTest(unittest.TestCase): + def setUp(self): + coords = [ + [0.000000, 0.000000, 0.000000], + [0.000000, 0.000000, 1.089000], + [1.026719, 0.000000, -0.363000], + [-0.513360, -0.889165, -0.363000], + [-0.513360, 0.889165, -0.363000]] + prop = [0.4, 0.2, 0.2, 0.2, 0.2] + self.mol = Molecule( + ["C", "H", "H", "H", "H"], coords, + site_properties={"voronoi_radius": prop}) + self.xyz = ZeoVoronoiXYZ(self.mol) + + def test_str(self): + ans = """5 +H4 C1 +C 0.000000 0.000000 0.000000 0.400000 +H 1.089000 0.000000 0.000000 0.200000 +H -0.363000 1.026719 0.000000 0.200000 +H -0.363000 -0.513360 -0.889165 0.200000 +H -0.363000 -0.513360 0.889165 0.200000""" + self.assertEqual(str(self.xyz), ans) + self.assertEqual(str(self.xyz), ans) + + def test_from_file(self): + filename = os.path.join(test_dir, "EDI_voro.xyz") + vor = ZeoVoronoiXYZ.from_file(filename) + self.assertIsInstance(vor.molecule, Molecule) + + +@unittest.skipIf(not zeo, "zeo not present.") +class GetVoronoiNodesTest(unittest.TestCase): + def setUp(self): + filepath = os.path.join(test_dir, 'POSCAR') + p = Poscar.from_file(filepath) + self.structure = p.structure + bv = BVAnalyzer() + valences = bv.get_valences(self.structure) + el = [site.species_string for site in self.structure.sites] + valence_dict = dict(zip(el, valences)) + self.rad_dict = {} + for k, v in valence_dict.items(): + self.rad_dict[k] = float(Specie(k, v).ionic_radius) + + assert len(self.rad_dict) == len(self.structure.composition) + + def test_get_voronoi_nodes(self): + vor_node_struct, vor_edge_center_struct, vor_face_center_struct = \ + get_voronoi_nodes(self.structure, self.rad_dict) + self.assertIsInstance(vor_node_struct, Structure) + self.assertIsInstance(vor_edge_center_struct, Structure) + self.assertIsInstance(vor_face_center_struct, Structure) + print (len(vor_node_struct.sites)) + print (len(vor_face_center_struct.sites)) + + +@unittest.skipIf(not zeo, "zeo not present.") +class GetFreeSphereParamsTest(unittest.TestCase): + def setUp(self): + filepath = os.path.join(test_dir, 'free_sph.cif') + self.structure = Structure.from_file(filepath) + self.rad_dict = {'Ge':0.67,'P':0.52,'S':1.7, + 'La':1.17,'Zr':0.86,'O':1.26} + + def test_get_free_sphere_params(self): + free_sph_params = get_free_sphere_params(self.structure, + rad_dict=self.rad_dict) + # Zeo results can change in future. Hence loose comparison + self.assertAlmostEqual( + free_sph_params['inc_sph_max_dia'], 2.58251, places=1) + self.assertAlmostEqual( + free_sph_params['free_sph_max_dia'], 1.29452, places=1) + self.assertAlmostEqual( + free_sph_params['inc_sph_along_free_sph_path_max_dia'], + 2.58251, places=1) + + +@unittest.skipIf(not zeo, "zeo not present.") +class GetHighAccuracyVoronoiNodesTest(unittest.TestCase): + def setUp(self): + filepath = os.path.join(test_dir, 'POSCAR') + p = Poscar.from_file(filepath) + self.structure = p.structure + bv = BVAnalyzer() + valences = bv.get_valences(self.structure) + el = [site.species_string for site in self.structure.sites] + valence_dict = dict(zip(el, valences)) + self.rad_dict = {} + for k, v in valence_dict.items(): + self.rad_dict[k] = float(Specie(k, v).ionic_radius) + + assert len(self.rad_dict) == len(self.structure.composition) + + def test_get_voronoi_nodes(self): + #vor_node_struct, vor_ec_struct, vor_fc_struct = \ + # get_high_accuracy_voronoi_nodes(self.structure, self.rad_dict) + vor_node_struct = \ + get_high_accuracy_voronoi_nodes(self.structure, self.rad_dict) + self.assertIsInstance(vor_node_struct, Structure) + #self.assertIsInstance(vor_ec_struct, Structure) + #self.assertIsInstance(vor_fc_struct, Structure) + print(len(vor_node_struct.sites)) + #print(len(vor_fc_struct.sites)) + + +@unittest.skipIf(not zeo, "zeo not present.") +class GetVoronoiNodesMultiOxiTest(unittest.TestCase): + def setUp(self): + filepath = os.path.join(test_dir, 'POSCAR') + p = Poscar.from_file(filepath) + self.structure = p.structure + bv = BVAnalyzer() + self.structure = bv.get_oxi_state_decorated_structure(self.structure) + valences = bv.get_valences(self.structure) + radii = [] + for i in range(len(valences)): + el = self.structure.sites[i].specie.symbol + radius = Specie(el, valences[i]).ionic_radius + radii.append(radius) + el = [site.species_string for site in self.structure.sites] + self.rad_dict = dict(zip(el, radii)) + for el in self.rad_dict.keys(): + print((el, self.rad_dict[el].real)) + + def test_get_voronoi_nodes(self): + vor_node_struct, vor_edge_center_struct, vor_face_center_struct =\ + get_voronoi_nodes(self.structure, self.rad_dict) + self.assertIsInstance(vor_node_struct, Structure) + self.assertIsInstance(vor_edge_center_struct, Structure) + self.assertIsInstance(vor_face_center_struct, Structure) + + +@unittest.skip("The function is deprecated") +class GetVoidVolumeSurfaceTest(unittest.TestCase): + def setUp(self): + filepath1 = os.path.join(test_dir, 'Li2O.cif') + p = CifParser(filepath1).get_structures(False)[0] + bv = BVAnalyzer() + valences = bv.get_valences(p) + el = [site.species_string for site in p.sites] + val_dict = dict(zip(el, valences)) + self._radii = {} + for k, v in val_dict.items(): + k1 = re.sub(r'[1-9,+,\-]', '', k) + self._radii[k1] = float(Specie(k1, v).ionic_radius) + p.remove(0) + self._vac_struct = p + + def test_void_volume_surface_area(self): + pass + vol, sa = get_void_volume_surfarea(self._vac_struct, self._radii) + #print "vol: ", vol, "sa: ", sa + self.assertIsInstance(vol, float) + self.assertIsInstance(sa, float) + +if __name__ == "__main__": + unittest.main() + +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# MySQL Connector/Python - MySQL driver written in Python. +# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. + +# MySQL Connector/Python is licensed under the terms of the GPLv2 +# , like most +# MySQL Connectors. There are special exceptions to the terms and +# conditions of the GPLv2 as it is applied to this software, see the +# FOSS License Exception +# . +# +# 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. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +from __future__ import print_function + +import sys, os + +import mysql.connector + +""" + +Example using MySQL Connector/Python showing: +* sending multiple statements and iterating over the results + +""" + +def main(config): + output = [] + db = mysql.connector.Connect(**config) + cursor = db.cursor() + + # Drop table if exists, and create it new + stmt_drop = "DROP TABLE IF EXISTS names" + cursor.execute(stmt_drop) + + stmt_create = """ + CREATE TABLE names ( + id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(30) DEFAULT '' NOT NULL, + info TEXT DEFAULT '', + age TINYINT UNSIGNED DEFAULT '30', + PRIMARY KEY (id) + )""" + cursor.execute(stmt_create) + + info = "abc"*10000 + + stmts = [ + "INSERT INTO names (name) VALUES ('Geert')", + "SELECT COUNT(*) AS cnt FROM names", + "INSERT INTO names (name) VALUES ('Jan'),('Michel')", + "SELECT name FROM names", + ] + + # Note 'multi=True' when calling cursor.execute() + for result in cursor.execute(' ; '.join(stmts), multi=True): + if result.with_rows: + if result.statement == stmts[3]: + output.append("Names in table: " + + ' '.join([ name[0] for name in result])) + else: + output.append("Number of rows: %d" % result.fetchone()[0]) + else: + if result.rowcount > 1: + tmp = 's' + else: + tmp = '' + output.append("Inserted %d row%s" % (result.rowcount, tmp)) + + cursor.execute(stmt_drop) + + cursor.close() + db.close() + return output + +if __name__ == '__main__': + # + # Configure MySQL login and database to use in config.py + # + from config import Config + config = Config.dbinfo().copy() + out = main(config) + print('\n'.join(out)) + +""" +This module parse an UPnP device's XML definition in an Object. + +@author: Raphael Slinckx +@copyright: Copyright 2005 +@license: LGPL +@contact: U{raphael@slinckx.net} +@version: 0.1.0 +""" + +__revision__ = "$id" + +from xml.dom import minidom +import logging + +# Allowed UPnP services to use when mapping ports/external addresses +WANSERVICES = ['urn:schemas-upnp-org:service:WANIPConnection:1', + 'urn:schemas-upnp-org:service:WANPPPConnection:1'] + +class UPnPXml: + """ + This objects parses the XML definition, and stores the useful + results in attributes. + + The device infos dictionnary may contain the following keys: + - friendlyname: A friendly name to call the device. + - manufacturer: A manufacturer name for the device. + + Here are the different attributes: + - deviceinfos: A dictionnary of device infos as defined above. + - controlurl: The control url, this is the url to use when sending SOAP + requests to the device, relative to the base url. + - wanservice: The WAN service to be used, one of the L{WANSERVICES} + - urlbase: The base url to use when talking in SOAP to the device. + + The full url to use is obtained by urljoin(urlbase, controlurl) + """ + + def __init__(self, xml): + """ + Parse the given XML string for UPnP infos. This creates the attributes + when they are found, or None if no value was found. + + @param xml: a xml string to parse + """ + logging.debug("Got UPNP Xml description:\n%s", xml) + doc = minidom.parseString(xml) + + # Fetch various device info + self.deviceinfos = {} + try: + attributes = { + 'friendlyname':'friendlyName', + 'manufacturer' : 'manufacturer' + } + device = doc.getElementsByTagName('device')[0] + for name, tag in attributes.iteritems(): + try: + self.deviceinfos[name] = device.getElementsByTagName( + tag)[0].firstChild.datas.encode('utf-8') + except: + pass + except: + pass + + # Fetch device control url + self.controlurl = None + self.wanservice = None + + for service in doc.getElementsByTagName('service'): + try: + stype = service.getElementsByTagName( + 'serviceType')[0].firstChild.data.encode('utf-8') + if stype in WANSERVICES: + self.controlurl = service.getElementsByTagName( + 'controlURL')[0].firstChild.data.encode('utf-8') + self.wanservice = stype + break + except: + pass + + # Find base url + self.urlbase = None + try: + self.urlbase = doc.getElementsByTagName( + 'URLBase')[0].firstChild.data.encode('utf-8') + except: + pass + + +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.aodv', cpp_namespace='::ns3') + return root_module + +def register_types(module): + root_module = module.get_root() + + ## wifi-mac-header.h (module 'wifi'): ns3::WifiMacType [enumeration] + module.add_enum('WifiMacType', ['WIFI_MAC_CTL_RTS', 'WIFI_MAC_CTL_CTS', 'WIFI_MAC_CTL_ACK', 'WIFI_MAC_CTL_BACKREQ', 'WIFI_MAC_CTL_BACKRESP', 'WIFI_MAC_MGT_BEACON', 'WIFI_MAC_MGT_ASSOCIATION_REQUEST', 'WIFI_MAC_MGT_ASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_DISASSOCIATION', 'WIFI_MAC_MGT_REASSOCIATION_REQUEST', 'WIFI_MAC_MGT_REASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_PROBE_REQUEST', 'WIFI_MAC_MGT_PROBE_RESPONSE', 'WIFI_MAC_MGT_AUTHENTICATION', 'WIFI_MAC_MGT_DEAUTHENTICATION', 'WIFI_MAC_MGT_ACTION', 'WIFI_MAC_MGT_ACTION_NO_ACK', 'WIFI_MAC_MGT_MULTIHOP_ACTION', 'WIFI_MAC_DATA', 'WIFI_MAC_DATA_CFACK', 'WIFI_MAC_DATA_CFPOLL', 'WIFI_MAC_DATA_CFACK_CFPOLL', 'WIFI_MAC_DATA_NULL', 'WIFI_MAC_DATA_NULL_CFACK', 'WIFI_MAC_DATA_NULL_CFPOLL', 'WIFI_MAC_DATA_NULL_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA', 'WIFI_MAC_QOSDATA_CFACK', 'WIFI_MAC_QOSDATA_CFPOLL', 'WIFI_MAC_QOSDATA_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA_NULL', 'WIFI_MAC_QOSDATA_NULL_CFPOLL', 'WIFI_MAC_QOSDATA_NULL_CFACK_CFPOLL'], import_from_module='ns.wifi') + ## address.h (module 'network'): ns3::Address [class] + module.add_class('Address', import_from_module='ns.network') + ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] + module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') + ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] + module.add_class('AttributeConstructionList', import_from_module='ns.core') + ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] + module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) + ## buffer.h (module 'network'): ns3::Buffer [class] + module.add_class('Buffer', import_from_module='ns.network') + ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] + module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) + ## packet.h (module 'network'): ns3::ByteTagIterator [class] + module.add_class('ByteTagIterator', import_from_module='ns.network') + ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] + module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] + module.add_class('ByteTagList', import_from_module='ns.network') + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] + module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] + module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) + ## callback.h (module 'core'): ns3::CallbackBase [class] + module.add_class('CallbackBase', import_from_module='ns.core') + ## event-id.h (module 'core'): ns3::EventId [class] + module.add_class('EventId', import_from_module='ns.core') + ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] + module.add_class('Inet6SocketAddress', import_from_module='ns.network') + ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] + root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) + ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] + module.add_class('InetSocketAddress', import_from_module='ns.network') + ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] + root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) + ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] + module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) + ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] + module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') + ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] + module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) + ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] + module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') + ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] + module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) + ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] + module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') + ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] + module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) + ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] + module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') + ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] + module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) + ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] + module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') + ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] + module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) + ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] + module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') + ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] + module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) + ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] + module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') + ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] + module.add_class('Ipv4Address', import_from_module='ns.network') + ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] + root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) + ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] + module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') + ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] + module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') + ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] + module.add_class('Ipv4Mask', import_from_module='ns.network') + ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class] + module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet') + ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] + module.add_class('Ipv6Address', import_from_module='ns.network') + ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] + root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress [class] + module.add_class('Ipv6InterfaceAddress', import_from_module='ns.internet') + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e [enumeration] + module.add_enum('State_e', ['TENTATIVE', 'DEPRECATED', 'PREFERRED', 'PERMANENT', 'HOMEADDRESS', 'TENTATIVE_OPTIMISTIC', 'INVALID'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e [enumeration] + module.add_enum('Scope_e', ['HOST', 'LINKLOCAL', 'GLOBAL'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') + ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] + module.add_class('Ipv6Prefix', import_from_module='ns.network') + ## mac48-address.h (module 'network'): ns3::Mac48Address [class] + module.add_class('Mac48Address', import_from_module='ns.network') + ## mac48-address.h (module 'network'): ns3::Mac48Address [class] + root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) + ## node-container.h (module 'network'): ns3::NodeContainer [class] + module.add_class('NodeContainer', import_from_module='ns.network') + ## object-base.h (module 'core'): ns3::ObjectBase [class] + module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') + ## object.h (module 'core'): ns3::ObjectDeleter [struct] + module.add_class('ObjectDeleter', import_from_module='ns.core') + ## object-factory.h (module 'core'): ns3::ObjectFactory [class] + module.add_class('ObjectFactory', import_from_module='ns.core') + ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] + module.add_class('PacketMetadata', import_from_module='ns.network') + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] + module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] + module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] + module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) + ## packet.h (module 'network'): ns3::PacketTagIterator [class] + module.add_class('PacketTagIterator', import_from_module='ns.network') + ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] + module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) + ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] + module.add_class('PacketTagList', import_from_module='ns.network') + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] + module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) + ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) + ## simulator.h (module 'core'): ns3::Simulator [class] + module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') + ## tag.h (module 'network'): ns3::Tag [class] + module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) + ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] + module.add_class('TagBuffer', import_from_module='ns.network') + ## timer.h (module 'core'): ns3::Timer [class] + module.add_class('Timer', import_from_module='ns.core') + ## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration] + module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') + ## timer.h (module 'core'): ns3::Timer::State [enumeration] + module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') + ## timer-impl.h (module 'core'): ns3::TimerImpl [class] + module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core') + ## type-id.h (module 'core'): ns3::TypeId [class] + module.add_class('TypeId', import_from_module='ns.core') + ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] + module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') + ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] + module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) + ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] + module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) + ## empty.h (module 'core'): ns3::empty [class] + module.add_class('empty', import_from_module='ns.core') + ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] + module.add_class('int64x64_t', import_from_module='ns.core') + ## aodv-helper.h (module 'aodv'): ns3::AodvHelper [class] + module.add_class('AodvHelper', parent=root_module['ns3::Ipv4RoutingHelper']) + ## chunk.h (module 'network'): ns3::Chunk [class] + module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) + ## header.h (module 'network'): ns3::Header [class] + module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) + ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] + module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) + ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] + module.add_enum('DscpType', ['DscpDefault', 'CS1', 'AF11', 'AF12', 'AF13', 'CS2', 'AF21', 'AF22', 'AF23', 'CS3', 'AF31', 'AF32', 'AF33', 'CS4', 'AF41', 'AF42', 'AF43', 'CS5', 'EF', 'CS6', 'CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') + ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] + module.add_enum('EcnType', ['NotECT', 'ECT1', 'ECT0', 'CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') + ## ipv6-header.h (module 'internet'): ns3::Ipv6Header [class] + module.add_class('Ipv6Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) + ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::NextHeader_e [enumeration] + module.add_enum('NextHeader_e', ['IPV6_EXT_HOP_BY_HOP', 'IPV6_IPV4', 'IPV6_TCP', 'IPV6_UDP', 'IPV6_IPV6', 'IPV6_EXT_ROUTING', 'IPV6_EXT_FRAGMENTATION', 'IPV6_EXT_CONFIDENTIALITY', 'IPV6_EXT_AUTHENTIFICATION', 'IPV6_ICMPV6', 'IPV6_EXT_END', 'IPV6_EXT_DESTINATION', 'IPV6_SCTP', 'IPV6_EXT_MOBILITY', 'IPV6_UDP_LITE'], outer_class=root_module['ns3::Ipv6Header'], import_from_module='ns.internet') + ## object.h (module 'core'): ns3::Object [class] + module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) + ## object.h (module 'core'): ns3::Object::AggregateIterator [class] + module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) + ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] + module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) + ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] + module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter'], 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 > [class] + module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) + ## socket.h (module 'network'): ns3::Socket [class] + module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) + ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] + module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') + ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] + module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') + ## socket.h (module 'network'): ns3::SocketAddressTag [class] + module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) + ## socket.h (module 'network'): ns3::SocketIpTosTag [class] + module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) + ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] + module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) + ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] + module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) + ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] + module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) + ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] + module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) + ## nstime.h (module 'core'): ns3::Time [class] + module.add_class('Time', import_from_module='ns.core') + ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] + module.add_enum('Unit', ['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 >']) + ## trailer.h (module 'network'): ns3::Trailer [class] + module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) + ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] + module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] + module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] + module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader [class] + module.add_class('WifiMacHeader', import_from_module='ns.wifi', parent=root_module['ns3::Header']) + ## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::QosAckPolicy [enumeration] + module.add_enum('QosAckPolicy', ['NORMAL_ACK', 'NO_ACK', 'NO_EXPLICIT_ACK', 'BLOCK_ACK'], outer_class=root_module['ns3::WifiMacHeader'], import_from_module='ns.wifi') + ## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::AddressType [enumeration] + module.add_enum('AddressType', ['ADDR1', 'ADDR2', 'ADDR3', 'ADDR4'], outer_class=root_module['ns3::WifiMacHeader'], import_from_module='ns.wifi') + ## 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']) + ## arp-cache.h (module 'internet'): ns3::ArpCache [class] + module.add_class('ArpCache', import_from_module='ns.internet', parent=root_module['ns3::Object']) + ## arp-cache.h (module 'internet'): ns3::ArpCache::Entry [class] + module.add_class('Entry', import_from_module='ns.internet', outer_class=root_module['ns3::ArpCache']) + ## 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 >']) + ## 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 >']) + ## 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 >']) + ## 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 >']) + ## callback.h (module 'core'): ns3::CallbackValue [class] + module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) + ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] + module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] + module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class] + module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] + module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) + ## 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']) + ## 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 >']) + ## 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']) + ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol [class] + module.add_class('IpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) + ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus [enumeration] + module.add_enum('RxStatus', ['RX_OK', 'RX_CSUM_FAILED', 'RX_ENDPOINT_CLOSED', 'RX_ENDPOINT_UNREACH'], outer_class=root_module['ns3::IpL4Protocol'], import_from_module='ns.internet') + ## ipv4.h (module 'internet'): ns3::Ipv4 [class] + module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) + ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] + module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) + ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] + module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) + ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface [class] + module.add_class('Ipv4Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) + ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] + module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) + ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] + module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') + ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] + module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) + ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] + module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) + ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] + module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter >']) + ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] + module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter >']) + ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] + module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) + ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] + module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) + ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] + module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) + ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface [class] + module.add_class('Ipv6Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) + ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] + module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) + ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] + module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) + ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] + module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] + module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) + ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] + module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) + ## net-device.h (module 'network'): ns3::NetDevice [class] + module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) + ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] + module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') + ## nix-vector.h (module 'network'): ns3::NixVector [class] + module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter >']) + ## node.h (module 'network'): ns3::Node [class] + module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) + ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class] + module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] + module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) + ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] + module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) + ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] + module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter >']) + ## packet.h (module 'network'): ns3::Packet [class] + module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter >']) + ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] + module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) + ## nstime.h (module 'core'): ns3::TimeChecker [class] + module.add_class('TimeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) + ## nstime.h (module 'core'): ns3::TimeValue [class] + module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) + ## type-id.h (module 'core'): ns3::TypeIdChecker [class] + module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) + ## type-id.h (module 'core'): ns3::TypeIdValue [class] + module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) + ## address.h (module 'network'): ns3::AddressChecker [class] + module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) + ## address.h (module 'network'): ns3::AddressValue [class] + module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) + module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type='list') + module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map') + + ## Register a nested module for the namespace FatalImpl + + nested_module = module.add_cpp_namespace('FatalImpl') + register_types_ns3_FatalImpl(nested_module) + + + ## Register a nested module for the namespace aodv + + nested_module = module.add_cpp_namespace('aodv') + register_types_ns3_aodv(nested_module) + + +def register_types_ns3_FatalImpl(module): + root_module = module.get_root() + + +def register_types_ns3_aodv(module): + root_module = module.get_root() + + ## aodv-packet.h (module 'aodv'): ns3::aodv::MessageType [enumeration] + module.add_enum('MessageType', ['AODVTYPE_RREQ', 'AODVTYPE_RREP', 'AODVTYPE_RERR', 'AODVTYPE_RREP_ACK']) + ## aodv-rtable.h (module 'aodv'): ns3::aodv::RouteFlags [enumeration] + module.add_enum('RouteFlags', ['VALID', 'INVALID', 'IN_SEARCH']) + ## aodv-dpd.h (module 'aodv'): ns3::aodv::DuplicatePacketDetection [class] + module.add_class('DuplicatePacketDetection') + ## aodv-id-cache.h (module 'aodv'): ns3::aodv::IdCache [class] + module.add_class('IdCache') + ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors [class] + module.add_class('Neighbors') + ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor [struct] + module.add_class('Neighbor', outer_class=root_module['ns3::aodv::Neighbors']) + ## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry [class] + module.add_class('QueueEntry') + ## aodv-rqueue.h (module 'aodv'): ns3::aodv::RequestQueue [class] + module.add_class('RequestQueue') + ## aodv-packet.h (module 'aodv'): ns3::aodv::RerrHeader [class] + module.add_class('RerrHeader', parent=root_module['ns3::Header']) + ## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol [class] + module.add_class('RoutingProtocol', parent=root_module['ns3::Ipv4RoutingProtocol']) + ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTable [class] + module.add_class('RoutingTable') + ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry [class] + module.add_class('RoutingTableEntry') + ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepAckHeader [class] + module.add_class('RrepAckHeader', parent=root_module['ns3::Header']) + ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepHeader [class] + module.add_class('RrepHeader', parent=root_module['ns3::Header']) + ## aodv-packet.h (module 'aodv'): ns3::aodv::RreqHeader [class] + module.add_class('RreqHeader', parent=root_module['ns3::Header']) + ## aodv-packet.h (module 'aodv'): ns3::aodv::TypeHeader [class] + module.add_class('TypeHeader', parent=root_module['ns3::Header']) + module.add_container('std::map< ns3::Ipv4Address, unsigned int >', ('ns3::Ipv4Address', 'unsigned int'), container_type='map') + module.add_container('std::vector< ns3::Ipv4Address >', 'ns3::Ipv4Address', container_type='vector') + +def register_methods(root_module): + register_Ns3Address_methods(root_module, root_module['ns3::Address']) + register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) + register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) + register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) + register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) + register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) + register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) + register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) + register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) + register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) + register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) + register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) + register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) + register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) + register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) + register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) + register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) + register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) + register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) + register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) + register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) + register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) + register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) + register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) + register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper']) + register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) + register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress']) + register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) + register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) + register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) + register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) + register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) + register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) + register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) + register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) + register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) + register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) + register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) + register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) + register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) + register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) + register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) + register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) + register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) + register_Ns3Timer_methods(root_module, root_module['ns3::Timer']) + register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl']) + register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) + register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) + register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) + register_Ns3Empty_methods(root_module, root_module['ns3::empty']) + register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) + register_Ns3AodvHelper_methods(root_module, root_module['ns3::AodvHelper']) + register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) + register_Ns3Header_methods(root_module, root_module['ns3::Header']) + register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) + register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header']) + register_Ns3Object_methods(root_module, root_module['ns3::Object']) + register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) + register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) + register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) + register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter >']) + register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) + register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag']) + register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) + register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) + register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) + register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) + register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) + register_Ns3Time_methods(root_module, root_module['ns3::Time']) + register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) + register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) + register_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_Ns3WifiMacHeader_methods(root_module, root_module['ns3::WifiMacHeader']) + register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) + register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) + register_Ns3ArpCache_methods(root_module, root_module['ns3::ArpCache']) + register_Ns3ArpCacheEntry_methods(root_module, root_module['ns3::ArpCache::Entry']) + register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) + register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) + register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) + register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) + register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) + register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) + register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) + register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) + register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) + register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) + register_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_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_Ns3IpL4Protocol_methods(root_module, root_module['ns3::IpL4Protocol']) + register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) + register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) + register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) + register_Ns3Ipv4Interface_methods(root_module, root_module['ns3::Ipv4Interface']) + register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) + register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) + register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) + register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) + register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) + register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) + register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) + register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) + register_Ns3Ipv6Interface_methods(root_module, root_module['ns3::Ipv6Interface']) + register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) + register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) + register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) + register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) + register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) + register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) + register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) + register_Ns3Node_methods(root_module, root_module['ns3::Node']) + register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) + register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) + register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) + register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) + register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) + register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) + register_Ns3TimeChecker_methods(root_module, root_module['ns3::TimeChecker']) + register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) + register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) + register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) + register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) + register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) + register_Ns3AodvDuplicatePacketDetection_methods(root_module, root_module['ns3::aodv::DuplicatePacketDetection']) + register_Ns3AodvIdCache_methods(root_module, root_module['ns3::aodv::IdCache']) + register_Ns3AodvNeighbors_methods(root_module, root_module['ns3::aodv::Neighbors']) + register_Ns3AodvNeighborsNeighbor_methods(root_module, root_module['ns3::aodv::Neighbors::Neighbor']) + register_Ns3AodvQueueEntry_methods(root_module, root_module['ns3::aodv::QueueEntry']) + register_Ns3AodvRequestQueue_methods(root_module, root_module['ns3::aodv::RequestQueue']) + register_Ns3AodvRerrHeader_methods(root_module, root_module['ns3::aodv::RerrHeader']) + register_Ns3AodvRoutingProtocol_methods(root_module, root_module['ns3::aodv::RoutingProtocol']) + register_Ns3AodvRoutingTable_methods(root_module, root_module['ns3::aodv::RoutingTable']) + register_Ns3AodvRoutingTableEntry_methods(root_module, root_module['ns3::aodv::RoutingTableEntry']) + register_Ns3AodvRrepAckHeader_methods(root_module, root_module['ns3::aodv::RrepAckHeader']) + register_Ns3AodvRrepHeader_methods(root_module, root_module['ns3::aodv::RrepHeader']) + register_Ns3AodvRreqHeader_methods(root_module, root_module['ns3::aodv::RreqHeader']) + register_Ns3AodvTypeHeader_methods(root_module, root_module['ns3::aodv::TypeHeader']) + return + +def register_Ns3Address_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_binary_comparison_operator('<') + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('==') + ## address.h (module 'network'): ns3::Address::Address() [constructor] + cls.add_constructor([]) + ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] + cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) + ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] + cls.add_constructor([param('ns3::Address const &', 'address')]) + ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] + cls.add_method('CheckCompatible', + 'bool', + [param('uint8_t', 'type'), param('uint8_t', 'len')], + is_const=True) + ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] + cls.add_method('CopyAllFrom', + 'uint32_t', + [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) + ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] + cls.add_method('CopyAllTo', + 'uint32_t', + [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], + is_const=True) + ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] + cls.add_method('CopyFrom', + 'uint32_t', + [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) + ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] + cls.add_method('CopyTo', + 'uint32_t', + [param('uint8_t *', 'buffer')], + is_const=True) + ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] + cls.add_method('Deserialize', + 'void', + [param('ns3::TagBuffer', 'buffer')]) + ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] + cls.add_method('GetLength', + 'uint8_t', + [], + is_const=True) + ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True) + ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] + cls.add_method('IsInvalid', + 'bool', + [], + is_const=True) + ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] + cls.add_method('IsMatchingType', + 'bool', + [param('uint8_t', 'type')], + is_const=True) + ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] + cls.add_method('Register', + 'uint8_t', + [], + is_static=True) + ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] + cls.add_method('Serialize', + 'void', + [param('ns3::TagBuffer', 'buffer')], + is_const=True) + return + +def register_Ns3AttributeConstructionList_methods(root_module, cls): + ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] + cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) + ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] + cls.add_constructor([]) + ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr checker, ns3::Ptr 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::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::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::AttributeConstructionList::Find(ns3::Ptr checker) const [member function] + cls.add_method('Find', + 'ns3::Ptr< ns3::AttributeValue >', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True) + return + +def register_Ns3AttributeConstructionListItem_methods(root_module, cls): + ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] + cls.add_constructor([]) + ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] + cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) + ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] + cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) + ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] + cls.add_instance_attribute('name', 'std::string', is_const=False) + ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] + cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) + return + +def register_Ns3Buffer_methods(root_module, cls): + ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] + cls.add_constructor([]) + ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] + cls.add_constructor([param('uint32_t', 'dataSize')]) + ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] + cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) + ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] + cls.add_constructor([param('ns3::Buffer const &', 'o')]) + ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] + cls.add_method('AddAtEnd', + 'bool', + [param('uint32_t', 'end')]) + ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] + cls.add_method('AddAtEnd', + 'void', + [param('ns3::Buffer const &', 'o')]) + ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] + cls.add_method('AddAtStart', + 'bool', + [param('uint32_t', 'start')]) + ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] + cls.add_method('Begin', + 'ns3::Buffer::Iterator', + [], + is_const=True) + ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] + cls.add_method('CopyData', + 'void', + [param('std::ostream *', 'os'), param('uint32_t', 'size')], + is_const=True) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] + cls.add_method('CopyData', + 'uint32_t', + [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], + is_const=True) + ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] + cls.add_method('CreateFragment', + 'ns3::Buffer', + [param('uint32_t', 'start'), param('uint32_t', 'length')], + is_const=True) + ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] + cls.add_method('CreateFullCopy', + 'ns3::Buffer', + [], + is_const=True) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) + ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] + cls.add_method('End', + 'ns3::Buffer::Iterator', + [], + is_const=True) + ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] + cls.add_method('GetCurrentEndOffset', + 'int32_t', + [], + is_const=True) + ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] + cls.add_method('GetCurrentStartOffset', + 'int32_t', + [], + is_const=True) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] + cls.add_method('GetSize', + 'uint32_t', + [], + is_const=True) + ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] + cls.add_method('PeekData', + 'uint8_t const *', + [], + is_const=True) + ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] + cls.add_method('RemoveAtEnd', + 'void', + [param('uint32_t', 'end')]) + ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] + cls.add_method('RemoveAtStart', + 'void', + [param('uint32_t', 'start')]) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] + cls.add_method('Serialize', + 'uint32_t', + [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], + is_const=True) + return + +def register_Ns3BufferIterator_methods(root_module, cls): + ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) + ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] + cls.add_constructor([]) + ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] + cls.add_method('CalculateIpChecksum', + 'uint16_t', + [param('uint16_t', 'size')]) + ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] + cls.add_method('CalculateIpChecksum', + 'uint16_t', + [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] + cls.add_method('GetDistanceFrom', + 'uint32_t', + [param('ns3::Buffer::Iterator const &', 'o')], + is_const=True) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] + cls.add_method('GetSize', + 'uint32_t', + [], + is_const=True) + ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] + cls.add_method('IsEnd', + 'bool', + [], + is_const=True) + ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] + cls.add_method('IsStart', + 'bool', + [], + is_const=True) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] + cls.add_method('Next', + 'void', + []) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] + cls.add_method('Next', + 'void', + [param('uint32_t', 'delta')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] + cls.add_method('Prev', + 'void', + []) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] + cls.add_method('Prev', + 'void', + [param('uint32_t', 'delta')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] + cls.add_method('Read', + 'void', + [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) + ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] + cls.add_method('ReadLsbtohU16', + 'uint16_t', + []) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] + cls.add_method('ReadLsbtohU32', + 'uint32_t', + []) + ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] + cls.add_method('ReadLsbtohU64', + 'uint64_t', + []) + ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] + cls.add_method('ReadNtohU16', + 'uint16_t', + []) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] + cls.add_method('ReadNtohU32', + 'uint32_t', + []) + ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] + cls.add_method('ReadNtohU64', + 'uint64_t', + []) + ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] + cls.add_method('ReadU16', + 'uint16_t', + []) + ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] + cls.add_method('ReadU32', + 'uint32_t', + []) + ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] + cls.add_method('ReadU64', + 'uint64_t', + []) + ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] + cls.add_method('ReadU8', + 'uint8_t', + []) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] + cls.add_method('Write', + 'void', + [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] + cls.add_method('Write', + 'void', + [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] + cls.add_method('WriteHtolsbU16', + 'void', + [param('uint16_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] + cls.add_method('WriteHtolsbU32', + 'void', + [param('uint32_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] + cls.add_method('WriteHtolsbU64', + 'void', + [param('uint64_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] + cls.add_method('WriteHtonU16', + 'void', + [param('uint16_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] + cls.add_method('WriteHtonU32', + 'void', + [param('uint32_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] + cls.add_method('WriteHtonU64', + 'void', + [param('uint64_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] + cls.add_method('WriteU16', + 'void', + [param('uint16_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] + cls.add_method('WriteU32', + 'void', + [param('uint32_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] + cls.add_method('WriteU64', + 'void', + [param('uint64_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] + cls.add_method('WriteU8', + 'void', + [param('uint8_t', 'data')]) + ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] + cls.add_method('WriteU8', + 'void', + [param('uint8_t', 'data'), param('uint32_t', 'len')]) + return + +def register_Ns3ByteTagIterator_methods(root_module, cls): + ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] + cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) + ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] + cls.add_method('HasNext', + 'bool', + [], + is_const=True) + ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] + cls.add_method('Next', + 'ns3::ByteTagIterator::Item', + []) + return + +def register_Ns3ByteTagIteratorItem_methods(root_module, cls): + ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] + cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) + ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] + cls.add_method('GetEnd', + 'uint32_t', + [], + is_const=True) + ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] + cls.add_method('GetStart', + 'uint32_t', + [], + is_const=True) + ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] + cls.add_method('GetTag', + 'void', + [param('ns3::Tag &', 'tag')], + is_const=True) + ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_const=True) + return + +def register_Ns3ByteTagList_methods(root_module, cls): + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] + cls.add_constructor([]) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] + cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) + ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] + cls.add_method('Add', + 'ns3::TagBuffer', + [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) + ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] + cls.add_method('Add', + 'void', + [param('ns3::ByteTagList const &', 'o')]) + ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] + cls.add_method('AddAtEnd', + 'void', + [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) + ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] + cls.add_method('AddAtStart', + 'void', + [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] + cls.add_method('Begin', + 'ns3::ByteTagList::Iterator', + [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], + is_const=True) + ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] + cls.add_method('RemoveAll', + 'void', + []) + return + +def register_Ns3ByteTagListIterator_methods(root_module, cls): + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] + cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) + ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] + cls.add_method('GetOffsetStart', + 'uint32_t', + [], + is_const=True) + ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] + cls.add_method('HasNext', + 'bool', + [], + is_const=True) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] + cls.add_method('Next', + 'ns3::ByteTagList::Iterator::Item', + []) + return + +def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] + cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] + cls.add_constructor([param('ns3::TagBuffer', 'buf')]) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] + cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] + cls.add_instance_attribute('end', 'int32_t', is_const=False) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] + cls.add_instance_attribute('size', 'uint32_t', is_const=False) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] + cls.add_instance_attribute('start', 'int32_t', is_const=False) + ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] + cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) + return + +def register_Ns3CallbackBase_methods(root_module, cls): + ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] + cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) + ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] + cls.add_constructor([]) + ## callback.h (module 'core'): ns3::Ptr ns3::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 impl) [constructor] + cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], + visibility='protected') + ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] + cls.add_method('Demangle', + 'std::string', + [param('std::string const &', 'mangled')], + is_static=True, visibility='protected') + return + +def register_Ns3EventId_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_binary_comparison_operator('==') + ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] + cls.add_constructor([param('ns3::EventId const &', 'arg0')]) + ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] + cls.add_constructor([]) + ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr 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_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_Ns3IntToType__0_methods(root_module, cls): + ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor] + cls.add_constructor([]) + ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor] + cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')]) + return + +def register_Ns3IntToType__1_methods(root_module, cls): + ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor] + cls.add_constructor([]) + ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor] + cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')]) + return + +def register_Ns3IntToType__2_methods(root_module, cls): + ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor] + cls.add_constructor([]) + ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor] + cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')]) + return + +def register_Ns3IntToType__3_methods(root_module, cls): + ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor] + cls.add_constructor([]) + ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor] + cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')]) + return + +def register_Ns3IntToType__4_methods(root_module, cls): + ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor] + cls.add_constructor([]) + ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor] + cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')]) + return + +def register_Ns3IntToType__5_methods(root_module, cls): + ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor] + cls.add_constructor([]) + ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor] + cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')]) + return + +def register_Ns3IntToType__6_methods(root_module, cls): + ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor] + cls.add_constructor([]) + ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor] + cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')]) + return + +def register_Ns3Ipv4Address_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_binary_comparison_operator('<') + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('==') + ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) + ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] + cls.add_constructor([]) + ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] + cls.add_constructor([param('uint32_t', 'address')]) + ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] + cls.add_constructor([param('char const *', 'address')]) + ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] + cls.add_method('CombineMask', + 'ns3::Ipv4Address', + [param('ns3::Ipv4Mask const &', 'mask')], + is_const=True) + ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] + cls.add_method('ConvertFrom', + 'ns3::Ipv4Address', + [param('ns3::Address const &', 'address')], + is_static=True) + ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] + cls.add_method('Deserialize', + 'ns3::Ipv4Address', + [param('uint8_t const *', 'buf')], + is_static=True) + ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] + cls.add_method('Get', + 'uint32_t', + [], + is_const=True) + ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] + cls.add_method('GetAny', + 'ns3::Ipv4Address', + [], + is_static=True) + ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] + cls.add_method('GetBroadcast', + 'ns3::Ipv4Address', + [], + is_static=True) + ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] + cls.add_method('GetLoopback', + 'ns3::Ipv4Address', + [], + is_static=True) + ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] + cls.add_method('GetSubnetDirectedBroadcast', + 'ns3::Ipv4Address', + [param('ns3::Ipv4Mask const &', 'mask')], + is_const=True) + ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] + cls.add_method('GetZero', + 'ns3::Ipv4Address', + [], + is_static=True) + ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] + cls.add_method('IsBroadcast', + 'bool', + [], + is_const=True) + ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] + cls.add_method('IsEqual', + 'bool', + [param('ns3::Ipv4Address const &', 'other')], + is_const=True) + ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] + cls.add_method('IsLocalMulticast', + 'bool', + [], + is_const=True) + ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] + cls.add_method('IsMatchingType', + 'bool', + [param('ns3::Address const &', 'address')], + is_static=True) + ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] + cls.add_method('IsMulticast', + 'bool', + [], + is_const=True) + ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] + cls.add_method('IsSubnetDirectedBroadcast', + 'bool', + [param('ns3::Ipv4Mask const &', 'mask')], + is_const=True) + ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True) + ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] + cls.add_method('Serialize', + 'void', + [param('uint8_t *', 'buf')], + is_const=True) + ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] + cls.add_method('Set', + 'void', + [param('uint32_t', 'address')]) + ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] + cls.add_method('Set', + 'void', + [param('char const *', 'address')]) + return + +def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('==') + ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] + cls.add_constructor([]) + ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] + cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) + ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] + cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) + ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] + cls.add_method('GetBroadcast', + 'ns3::Ipv4Address', + [], + is_const=True) + ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] + cls.add_method('GetLocal', + 'ns3::Ipv4Address', + [], + is_const=True) + ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] + cls.add_method('GetMask', + 'ns3::Ipv4Mask', + [], + is_const=True) + ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] + cls.add_method('GetScope', + 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', + [], + is_const=True) + ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] + cls.add_method('IsSecondary', + 'bool', + [], + is_const=True) + ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] + cls.add_method('SetBroadcast', + 'void', + [param('ns3::Ipv4Address', 'broadcast')]) + ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] + cls.add_method('SetLocal', + 'void', + [param('ns3::Ipv4Address', 'local')]) + ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] + cls.add_method('SetMask', + 'void', + [param('ns3::Ipv4Mask', 'mask')]) + ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] + cls.add_method('SetPrimary', + 'void', + []) + ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] + cls.add_method('SetScope', + 'void', + [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) + ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] + cls.add_method('SetSecondary', + 'void', + []) + return + +def register_Ns3Ipv4Mask_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('==') + ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) + ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] + cls.add_constructor([]) + ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] + cls.add_constructor([param('uint32_t', 'mask')]) + ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] + cls.add_constructor([param('char const *', 'mask')]) + ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] + cls.add_method('Get', + 'uint32_t', + [], + is_const=True) + ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] + cls.add_method('GetInverse', + 'uint32_t', + [], + is_const=True) + ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] + cls.add_method('GetLoopback', + 'ns3::Ipv4Mask', + [], + is_static=True) + ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] + cls.add_method('GetOnes', + 'ns3::Ipv4Mask', + [], + is_static=True) + ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] + cls.add_method('GetPrefixLength', + 'uint16_t', + [], + is_const=True) + ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] + cls.add_method('GetZero', + 'ns3::Ipv4Mask', + [], + is_static=True) + ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] + cls.add_method('IsEqual', + 'bool', + [param('ns3::Ipv4Mask', 'other')], + is_const=True) + ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] + cls.add_method('IsMatch', + 'bool', + [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], + is_const=True) + ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True) + ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] + cls.add_method('Set', + 'void', + [param('uint32_t', 'mask')]) + return + +def register_Ns3Ipv4RoutingHelper_methods(root_module, cls): + ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper() [constructor] + cls.add_constructor([]) + ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper(ns3::Ipv4RoutingHelper const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv4RoutingHelper const &', 'arg0')]) + ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper * ns3::Ipv4RoutingHelper::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ipv4RoutingHelper *', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## ipv4-routing-helper.h (module 'internet'): ns3::Ptr ns3::Ipv4RoutingHelper::Create(ns3::Ptr node) const [member function] + cls.add_method('Create', + 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', + [param('ns3::Ptr< ns3::Node >', 'node')], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableAllAt(ns3::Time printTime, ns3::Ptr stream) const [member function] + cls.add_method('PrintRoutingTableAllAt', + 'void', + [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], + is_const=True) + ## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableAllEvery(ns3::Time printInterval, ns3::Ptr stream) const [member function] + cls.add_method('PrintRoutingTableAllEvery', + 'void', + [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], + is_const=True) + ## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableAt(ns3::Time printTime, ns3::Ptr node, ns3::Ptr stream) const [member function] + cls.add_method('PrintRoutingTableAt', + 'void', + [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], + is_const=True) + ## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableEvery(ns3::Time printInterval, ns3::Ptr node, ns3::Ptr stream) const [member function] + cls.add_method('PrintRoutingTableEvery', + 'void', + [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], + is_const=True) + return + +def register_Ns3Ipv6Address_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_binary_comparison_operator('<') + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('==') + ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] + cls.add_constructor([]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] + cls.add_constructor([param('char const *', 'address')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] + cls.add_constructor([param('uint8_t *', 'address')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] + cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] + cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] + cls.add_method('CombinePrefix', + 'ns3::Ipv6Address', + [param('ns3::Ipv6Prefix const &', 'prefix')]) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] + cls.add_method('ConvertFrom', + 'ns3::Ipv6Address', + [param('ns3::Address const &', 'address')], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] + cls.add_method('Deserialize', + 'ns3::Ipv6Address', + [param('uint8_t const *', 'buf')], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] + cls.add_method('GetAllHostsMulticast', + 'ns3::Ipv6Address', + [], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] + cls.add_method('GetAllNodesMulticast', + 'ns3::Ipv6Address', + [], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] + cls.add_method('GetAllRoutersMulticast', + 'ns3::Ipv6Address', + [], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] + cls.add_method('GetAny', + 'ns3::Ipv6Address', + [], + is_static=True) + ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] + cls.add_method('GetBytes', + 'void', + [param('uint8_t *', 'buf')], + is_const=True) + ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] + cls.add_method('GetIpv4MappedAddress', + 'ns3::Ipv4Address', + [], + is_const=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] + cls.add_method('GetLoopback', + 'ns3::Ipv6Address', + [], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] + cls.add_method('GetOnes', + 'ns3::Ipv6Address', + [], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] + cls.add_method('GetZero', + 'ns3::Ipv6Address', + [], + is_static=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] + cls.add_method('IsAllHostsMulticast', + 'bool', + [], + is_const=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] + cls.add_method('IsAllNodesMulticast', + 'bool', + [], + is_const=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] + cls.add_method('IsAllRoutersMulticast', + 'bool', + [], + is_const=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] + cls.add_method('IsAny', + 'bool', + [], + is_const=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] + cls.add_method('IsEqual', + 'bool', + [param('ns3::Ipv6Address const &', 'other')], + is_const=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function] + cls.add_method('IsIpv4MappedAddress', + 'bool', + []) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] + cls.add_method('IsLinkLocal', + 'bool', + [], + is_const=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] + cls.add_method('IsLinkLocalMulticast', + 'bool', + [], + is_const=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] + cls.add_method('IsLocalhost', + 'bool', + [], + is_const=True) + ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] + cls.add_method('IsMatchingType', + 'bool', + [param('ns3::Address const &', 'address')], + is_static=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] + cls.add_method('IsMulticast', + 'bool', + [], + is_const=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] + cls.add_method('IsSolicitedMulticast', + 'bool', + [], + is_const=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] + cls.add_method('MakeAutoconfiguredAddress', + 'ns3::Ipv6Address', + [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] + cls.add_method('MakeAutoconfiguredLinkLocalAddress', + 'ns3::Ipv6Address', + [param('ns3::Mac48Address', 'mac')], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] + cls.add_method('MakeIpv4MappedAddress', + 'ns3::Ipv6Address', + [param('ns3::Ipv4Address', 'addr')], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] + cls.add_method('MakeSolicitedAddress', + 'ns3::Ipv6Address', + [param('ns3::Ipv6Address', 'addr')], + is_static=True) + ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True) + ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] + cls.add_method('Serialize', + 'void', + [param('uint8_t *', 'buf')], + is_const=True) + ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] + cls.add_method('Set', + 'void', + [param('char const *', 'address')]) + ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] + cls.add_method('Set', + 'void', + [param('uint8_t *', 'address')]) + return + +def register_Ns3Ipv6InterfaceAddress_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('==') + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress() [constructor] + cls.add_constructor([]) + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address) [constructor] + cls.add_constructor([param('ns3::Ipv6Address', 'address')]) + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address, ns3::Ipv6Prefix prefix) [constructor] + cls.add_constructor([param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'prefix')]) + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6InterfaceAddress const & o) [copy constructor] + cls.add_constructor([param('ns3::Ipv6InterfaceAddress const &', 'o')]) + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceAddress::GetAddress() const [member function] + cls.add_method('GetAddress', + 'ns3::Ipv6Address', + [], + is_const=True) + ## ipv6-interface-address.h (module 'internet'): uint32_t ns3::Ipv6InterfaceAddress::GetNsDadUid() const [member function] + cls.add_method('GetNsDadUid', + 'uint32_t', + [], + is_const=True) + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Prefix ns3::Ipv6InterfaceAddress::GetPrefix() const [member function] + cls.add_method('GetPrefix', + 'ns3::Ipv6Prefix', + [], + is_const=True) + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e ns3::Ipv6InterfaceAddress::GetScope() const [member function] + cls.add_method('GetScope', + 'ns3::Ipv6InterfaceAddress::Scope_e', + [], + is_const=True) + ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e ns3::Ipv6InterfaceAddress::GetState() const [member function] + cls.add_method('GetState', + 'ns3::Ipv6InterfaceAddress::State_e', + [], + is_const=True) + ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetAddress(ns3::Ipv6Address address) [member function] + cls.add_method('SetAddress', + 'void', + [param('ns3::Ipv6Address', 'address')]) + ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetNsDadUid(uint32_t uid) [member function] + cls.add_method('SetNsDadUid', + 'void', + [param('uint32_t', 'uid')]) + ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetScope(ns3::Ipv6InterfaceAddress::Scope_e scope) [member function] + cls.add_method('SetScope', + 'void', + [param('ns3::Ipv6InterfaceAddress::Scope_e', 'scope')]) + ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetState(ns3::Ipv6InterfaceAddress::State_e state) [member function] + cls.add_method('SetState', + 'void', + [param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) + return + +def register_Ns3Ipv6Prefix_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('==') + ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] + cls.add_constructor([]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] + cls.add_constructor([param('uint8_t *', 'prefix')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] + cls.add_constructor([param('char const *', 'prefix')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] + cls.add_constructor([param('uint8_t', 'prefix')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] + cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] + cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) + ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] + cls.add_method('GetBytes', + 'void', + [param('uint8_t *', 'buf')], + is_const=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] + cls.add_method('GetLoopback', + 'ns3::Ipv6Prefix', + [], + is_static=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] + cls.add_method('GetOnes', + 'ns3::Ipv6Prefix', + [], + is_static=True) + ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] + cls.add_method('GetPrefixLength', + 'uint8_t', + [], + is_const=True) + ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] + cls.add_method('GetZero', + 'ns3::Ipv6Prefix', + [], + is_static=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] + cls.add_method('IsEqual', + 'bool', + [param('ns3::Ipv6Prefix const &', 'other')], + is_const=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] + cls.add_method('IsMatch', + 'bool', + [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], + is_const=True) + ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True) + return + +def register_Ns3Mac48Address_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_binary_comparison_operator('<') + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('==') + ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) + ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] + cls.add_constructor([]) + ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] + cls.add_constructor([param('char const *', 'str')]) + ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] + cls.add_method('Allocate', + 'ns3::Mac48Address', + [], + is_static=True) + ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] + cls.add_method('ConvertFrom', + 'ns3::Mac48Address', + [param('ns3::Address const &', 'address')], + is_static=True) + ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] + cls.add_method('CopyFrom', + 'void', + [param('uint8_t const *', 'buffer')]) + ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] + cls.add_method('CopyTo', + 'void', + [param('uint8_t *', 'buffer')], + is_const=True) + ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] + cls.add_method('GetBroadcast', + 'ns3::Mac48Address', + [], + is_static=True) + ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] + cls.add_method('GetMulticast', + 'ns3::Mac48Address', + [param('ns3::Ipv4Address', 'address')], + is_static=True) + ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] + cls.add_method('GetMulticast', + 'ns3::Mac48Address', + [param('ns3::Ipv6Address', 'address')], + is_static=True) + ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] + cls.add_method('GetMulticast6Prefix', + 'ns3::Mac48Address', + [], + is_static=True) + ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] + cls.add_method('GetMulticastPrefix', + 'ns3::Mac48Address', + [], + is_static=True) + ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] + cls.add_method('IsBroadcast', + 'bool', + [], + is_const=True) + ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] + cls.add_method('IsGroup', + 'bool', + [], + is_const=True) + ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] + cls.add_method('IsMatchingType', + 'bool', + [param('ns3::Address const &', 'address')], + is_static=True) + return + +def register_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 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 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*,std::vector, std::allocator > > > 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*,std::vector, std::allocator > > > 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::NodeContainer::Get(uint32_t i) const [member function] + cls.add_method('Get', + 'ns3::Ptr< ns3::Node >', + [param('uint32_t', 'i')], + is_const=True) + ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] + cls.add_method('GetGlobal', + 'ns3::NodeContainer', + [], + is_static=True) + ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] + cls.add_method('GetN', + 'uint32_t', + [], + is_const=True) + return + +def register_Ns3ObjectBase_methods(root_module, cls): + ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] + cls.add_constructor([]) + ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] + cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) + ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] + cls.add_method('GetAttribute', + 'void', + [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], + is_const=True) + ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] + cls.add_method('GetAttributeFailSafe', + 'bool', + [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], + is_const=True) + ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] + cls.add_method('GetInstanceTypeId', + 'ns3::TypeId', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] + cls.add_method('SetAttribute', + 'void', + [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) + ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] + cls.add_method('SetAttributeFailSafe', + 'bool', + [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) + ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] + cls.add_method('TraceConnect', + 'bool', + [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) + ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] + cls.add_method('TraceConnectWithoutContext', + 'bool', + [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) + ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] + cls.add_method('TraceDisconnect', + 'bool', + [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) + ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] + cls.add_method('TraceDisconnectWithoutContext', + 'bool', + [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) + ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] + cls.add_method('ConstructSelf', + 'void', + [param('ns3::AttributeConstructionList const &', 'attributes')], + visibility='protected') + ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] + cls.add_method('NotifyConstructionCompleted', + 'void', + [], + visibility='protected', is_virtual=True) + return + +def register_Ns3ObjectDeleter_methods(root_module, cls): + ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] + cls.add_constructor([]) + ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] + cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) + ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] + cls.add_method('Delete', + 'void', + [param('ns3::Object *', 'object')], + is_static=True) + return + +def register_Ns3ObjectFactory_methods(root_module, cls): + cls.add_output_stream_operator() + ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] + cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) + ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] + cls.add_constructor([]) + ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] + cls.add_constructor([param('std::string', 'typeId')]) + ## object-factory.h (module 'core'): ns3::Ptr ns3::ObjectFactory::Create() const [member function] + cls.add_method('Create', + 'ns3::Ptr< ns3::Object >', + [], + is_const=True) + ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_const=True) + ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] + cls.add_method('Set', + 'void', + [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) + ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] + cls.add_method('SetTypeId', + 'void', + [param('ns3::TypeId', 'tid')]) + ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] + cls.add_method('SetTypeId', + 'void', + [param('char const *', 'tid')]) + ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] + cls.add_method('SetTypeId', + 'void', + [param('std::string', 'tid')]) + return + +def register_Ns3PacketMetadata_methods(root_module, cls): + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] + cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] + cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) + ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] + cls.add_method('AddAtEnd', + 'void', + [param('ns3::PacketMetadata const &', 'o')]) + ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] + cls.add_method('AddHeader', + 'void', + [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) + ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] + cls.add_method('AddPaddingAtEnd', + 'void', + [param('uint32_t', 'end')]) + ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] + cls.add_method('AddTrailer', + 'void', + [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] + cls.add_method('BeginItem', + 'ns3::PacketMetadata::ItemIterator', + [param('ns3::Buffer', 'buffer')], + is_const=True) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] + cls.add_method('CreateFragment', + 'ns3::PacketMetadata', + [param('uint32_t', 'start'), param('uint32_t', 'end')], + is_const=True) + ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) + ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] + cls.add_method('Enable', + 'void', + [], + is_static=True) + ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] + cls.add_method('EnableChecking', + 'void', + [], + is_static=True) + ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True) + ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] + cls.add_method('GetUid', + 'uint64_t', + [], + is_const=True) + ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] + cls.add_method('RemoveAtEnd', + 'void', + [param('uint32_t', 'end')]) + ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] + cls.add_method('RemoveAtStart', + 'void', + [param('uint32_t', 'start')]) + ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] + cls.add_method('RemoveHeader', + 'void', + [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) + ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] + cls.add_method('RemoveTrailer', + 'void', + [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) + ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] + cls.add_method('Serialize', + 'uint32_t', + [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], + is_const=True) + return + +def register_Ns3PacketMetadataItem_methods(root_module, cls): + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] + cls.add_constructor([]) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] + cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] + cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] + cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] + cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] + cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] + cls.add_instance_attribute('isFragment', 'bool', is_const=False) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] + cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) + return + +def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] + cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] + cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) + ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] + cls.add_method('HasNext', + 'bool', + [], + is_const=True) + ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] + cls.add_method('Next', + 'ns3::PacketMetadata::Item', + []) + return + +def register_Ns3PacketTagIterator_methods(root_module, cls): + ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] + cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) + ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] + cls.add_method('HasNext', + 'bool', + [], + is_const=True) + ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] + cls.add_method('Next', + 'ns3::PacketTagIterator::Item', + []) + return + +def register_Ns3PacketTagIteratorItem_methods(root_module, cls): + ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] + cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) + ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] + cls.add_method('GetTag', + 'void', + [param('ns3::Tag &', 'tag')], + is_const=True) + ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_const=True) + return + +def register_Ns3PacketTagList_methods(root_module, cls): + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] + cls.add_constructor([]) + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] + cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) + ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] + cls.add_method('Add', + 'void', + [param('ns3::Tag const &', 'tag')], + is_const=True) + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] + cls.add_method('Head', + 'ns3::PacketTagList::TagData const *', + [], + is_const=True) + ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] + cls.add_method('Peek', + 'bool', + [param('ns3::Tag &', 'tag')], + is_const=True) + ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] + cls.add_method('Remove', + 'bool', + [param('ns3::Tag &', 'tag')]) + ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] + cls.add_method('RemoveAll', + 'void', + []) + return + +def register_Ns3PacketTagListTagData_methods(root_module, cls): + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] + cls.add_constructor([]) + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] + cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] + cls.add_instance_attribute('count', 'uint32_t', is_const=False) + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] + cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] + cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) + ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] + cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) + return + +def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): + ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount::SimpleRefCount() [constructor] + cls.add_constructor([]) + ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount::SimpleRefCount(ns3::SimpleRefCount 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::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::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 impl) [member function] + cls.add_method('SetImplementation', + 'void', + [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], + is_static=True) + ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] + cls.add_method('SetScheduler', + 'void', + [param('ns3::ObjectFactory', 'schedulerFactory')], + is_static=True) + ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] + cls.add_method('Stop', + 'void', + [], + is_static=True) + ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] + cls.add_method('Stop', + 'void', + [param('ns3::Time const &', 'time')], + is_static=True) + return + +def register_Ns3Tag_methods(root_module, cls): + ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] + cls.add_constructor([]) + ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Tag const &', 'arg0')]) + ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] + cls.add_method('Deserialize', + 'void', + [param('ns3::TagBuffer', 'i')], + is_pure_virtual=True, is_virtual=True) + ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] + cls.add_method('Serialize', + 'void', + [param('ns3::TagBuffer', 'i')], + is_pure_virtual=True, is_const=True, is_virtual=True) + return + +def register_Ns3TagBuffer_methods(root_module, cls): + ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] + cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) + ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] + cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) + ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] + cls.add_method('CopyFrom', + 'void', + [param('ns3::TagBuffer', 'o')]) + ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] + cls.add_method('Read', + 'void', + [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) + ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] + cls.add_method('ReadDouble', + 'double', + []) + ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] + cls.add_method('ReadU16', + 'uint16_t', + []) + ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] + cls.add_method('ReadU32', + 'uint32_t', + []) + ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] + cls.add_method('ReadU64', + 'uint64_t', + []) + ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] + cls.add_method('ReadU8', + 'uint8_t', + []) + ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] + cls.add_method('TrimAtEnd', + 'void', + [param('uint32_t', 'trim')]) + ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] + cls.add_method('Write', + 'void', + [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) + ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] + cls.add_method('WriteDouble', + 'void', + [param('double', 'v')]) + ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] + cls.add_method('WriteU16', + 'void', + [param('uint16_t', 'data')]) + ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] + cls.add_method('WriteU32', + 'void', + [param('uint32_t', 'data')]) + ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] + cls.add_method('WriteU64', + 'void', + [param('uint64_t', 'v')]) + ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] + cls.add_method('WriteU8', + 'void', + [param('uint8_t', 'v')]) + return + +def register_Ns3Timer_methods(root_module, cls): + ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Timer const &', 'arg0')]) + ## timer.h (module 'core'): ns3::Timer::Timer() [constructor] + cls.add_constructor([]) + ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor] + cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')]) + ## timer.h (module 'core'): void ns3::Timer::Cancel() [member function] + cls.add_method('Cancel', + 'void', + []) + ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function] + cls.add_method('GetDelay', + 'ns3::Time', + [], + is_const=True) + ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function] + cls.add_method('GetDelayLeft', + 'ns3::Time', + [], + is_const=True) + ## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function] + cls.add_method('GetState', + 'ns3::Timer::State', + [], + is_const=True) + ## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function] + cls.add_method('IsExpired', + 'bool', + [], + is_const=True) + ## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function] + cls.add_method('IsRunning', + 'bool', + [], + is_const=True) + ## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function] + cls.add_method('IsSuspended', + 'bool', + [], + is_const=True) + ## timer.h (module 'core'): void ns3::Timer::Remove() [member function] + cls.add_method('Remove', + 'void', + []) + ## timer.h (module 'core'): void ns3::Timer::Resume() [member function] + cls.add_method('Resume', + 'void', + []) + ## timer.h (module 'core'): void ns3::Timer::Schedule() [member function] + cls.add_method('Schedule', + 'void', + []) + ## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function] + cls.add_method('Schedule', + 'void', + [param('ns3::Time', 'delay')]) + ## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function] + cls.add_method('SetDelay', + 'void', + [param('ns3::Time const &', 'delay')]) + ## timer.h (module 'core'): void ns3::Timer::Suspend() [member function] + cls.add_method('Suspend', + 'void', + []) + return + +def register_Ns3TimerImpl_methods(root_module, cls): + ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor] + cls.add_constructor([]) + ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor] + cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')]) + ## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function] + cls.add_method('Invoke', + 'void', + [], + is_pure_virtual=True, is_virtual=True) + ## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function] + cls.add_method('Schedule', + 'ns3::EventId', + [param('ns3::Time const &', 'delay')], + is_pure_virtual=True, is_virtual=True) + return + +def register_Ns3TypeId_methods(root_module, cls): + cls.add_binary_comparison_operator('!=') + cls.add_binary_comparison_operator('<') + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('==') + ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] + cls.add_constructor([param('char const *', 'name')]) + ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] + cls.add_constructor([]) + ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] + cls.add_constructor([param('ns3::TypeId const &', 'o')]) + ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr accessor, ns3::Ptr 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 accessor, ns3::Ptr 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 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::TypeId::GetConstructor() const [member function] + cls.add_method('GetConstructor', + 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', + [], + is_const=True) + ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] + cls.add_method('GetGroupName', + 'std::string', + [], + is_const=True) + ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] + cls.add_method('GetName', + 'std::string', + [], + is_const=True) + ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] + cls.add_method('GetParent', + 'ns3::TypeId', + [], + is_const=True) + ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] + cls.add_method('GetRegistered', + 'ns3::TypeId', + [param('uint32_t', 'i')], + is_static=True) + ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] + cls.add_method('GetRegisteredN', + 'uint32_t', + [], + is_static=True) + ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] + cls.add_method('GetTraceSource', + 'ns3::TypeId::TraceSourceInformation', + [param('uint32_t', 'i')], + is_const=True) + ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] + cls.add_method('GetTraceSourceN', + 'uint32_t', + [], + is_const=True) + ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] + cls.add_method('GetUid', + 'uint16_t', + [], + is_const=True) + ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] + cls.add_method('HasConstructor', + 'bool', + [], + is_const=True) + ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] + cls.add_method('HasParent', + 'bool', + [], + is_const=True) + ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] + cls.add_method('HideFromDocumentation', + 'ns3::TypeId', + []) + ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] + cls.add_method('IsChildOf', + 'bool', + [param('ns3::TypeId', 'other')], + is_const=True) + ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] + cls.add_method('LookupAttributeByName', + 'bool', + [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], + is_const=True) + ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] + cls.add_method('LookupByName', + 'ns3::TypeId', + [param('std::string', 'name')], + is_static=True) + ## type-id.h (module 'core'): ns3::Ptr ns3::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 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_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) + cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) + cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) + cls.add_unary_numeric_operator('-') + cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) + cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) + cls.add_binary_comparison_operator('<') + cls.add_binary_comparison_operator('>') + cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right')) + cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right')) + cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right')) + cls.add_output_stream_operator() + cls.add_binary_comparison_operator('<=') + cls.add_binary_comparison_operator('==') + cls.add_binary_comparison_operator('>=') + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] + cls.add_constructor([]) + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] + cls.add_constructor([param('double', 'v')]) + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] + cls.add_constructor([param('int', 'v')]) + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] + cls.add_constructor([param('long int', 'v')]) + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] + cls.add_constructor([param('long long int', 'v')]) + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] + cls.add_constructor([param('unsigned int', 'v')]) + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] + cls.add_constructor([param('long unsigned int', 'v')]) + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] + cls.add_constructor([param('long long unsigned int', 'v')]) + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] + cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) + ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] + cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) + ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] + cls.add_method('GetDouble', + 'double', + [], + is_const=True) + ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] + cls.add_method('GetHigh', + 'int64_t', + [], + is_const=True) + ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] + cls.add_method('GetLow', + 'uint64_t', + [], + is_const=True) + ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] + cls.add_method('Invert', + 'ns3::int64x64_t', + [param('uint64_t', 'v')], + is_static=True) + ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] + cls.add_method('MulByInvert', + 'void', + [param('ns3::int64x64_t const &', 'o')]) + return + +def register_Ns3AodvHelper_methods(root_module, cls): + ## aodv-helper.h (module 'aodv'): ns3::AodvHelper::AodvHelper(ns3::AodvHelper const & arg0) [copy constructor] + cls.add_constructor([param('ns3::AodvHelper const &', 'arg0')]) + ## aodv-helper.h (module 'aodv'): ns3::AodvHelper::AodvHelper() [constructor] + cls.add_constructor([]) + ## aodv-helper.h (module 'aodv'): int64_t ns3::AodvHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function] + cls.add_method('AssignStreams', + 'int64_t', + [param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')]) + ## aodv-helper.h (module 'aodv'): ns3::AodvHelper * ns3::AodvHelper::Copy() const [member function] + cls.add_method('Copy', + 'ns3::AodvHelper *', + [], + is_const=True, is_virtual=True) + ## aodv-helper.h (module 'aodv'): ns3::Ptr ns3::AodvHelper::Create(ns3::Ptr node) const [member function] + cls.add_method('Create', + 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', + [param('ns3::Ptr< ns3::Node >', 'node')], + is_const=True, is_virtual=True) + ## aodv-helper.h (module 'aodv'): void ns3::AodvHelper::Set(std::string name, ns3::AttributeValue const & value) [member function] + cls.add_method('Set', + 'void', + [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) + return + +def register_Ns3Chunk_methods(root_module, cls): + ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] + cls.add_constructor([]) + ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) + ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('ns3::Buffer::Iterator', 'start')], + is_pure_virtual=True, is_virtual=True) + ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_pure_virtual=True, is_const=True, is_virtual=True) + return + +def register_Ns3Header_methods(root_module, cls): + cls.add_output_stream_operator() + ## header.h (module 'network'): ns3::Header::Header() [constructor] + cls.add_constructor([]) + ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Header const &', 'arg0')]) + ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('ns3::Buffer::Iterator', 'start')], + is_pure_virtual=True, is_virtual=True) + ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] + cls.add_method('Serialize', + 'void', + [param('ns3::Buffer::Iterator', 'start')], + is_pure_virtual=True, is_const=True, is_virtual=True) + return + +def register_Ns3Ipv4Header_methods(root_module, cls): + ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) + ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] + cls.add_constructor([]) + ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('ns3::Buffer::Iterator', 'start')], + is_virtual=True) + ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] + cls.add_method('DscpTypeToString', + 'std::string', + [param('ns3::Ipv4Header::DscpType', 'dscp')], + is_const=True) + ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] + cls.add_method('EcnTypeToString', + 'std::string', + [param('ns3::Ipv4Header::EcnType', 'ecn')], + is_const=True) + ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] + cls.add_method('EnableChecksum', + 'void', + []) + ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] + cls.add_method('GetDestination', + 'ns3::Ipv4Address', + [], + is_const=True) + ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] + cls.add_method('GetDscp', + 'ns3::Ipv4Header::DscpType', + [], + is_const=True) + ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] + cls.add_method('GetEcn', + 'ns3::Ipv4Header::EcnType', + [], + is_const=True)