repo_name
stringlengths
5
100
path
stringlengths
4
299
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1.03M
license
stringclasses
15 values
hash
int64
-9,223,351,895,964,839,000
9,223,297,778B
line_mean
float64
3.17
100
line_max
int64
7
1k
alpha_frac
float64
0.25
0.98
autogenerated
bool
1 class
dezede/dezede
libretto/api/rest/serializers.py
1
6967
from collections import OrderedDict from django.template.defaultfilters import filesizeformat from rest_framework.fields import ReadOnlyField, Field, SerializerMethodField from rest_framework.relations import ( HyperlinkedIdentityField, StringRelatedField, PrimaryKeyRelatedField ) from rest_framework.reverse import reverse from rest_framework.serializers import ( HyperlinkedModelSerializer, ModelSerializer, ) from accounts.models import HierarchicUser from ...models import * class CommonSerializer(ModelSerializer): str = ReadOnlyField(source='__str__') change_url = SerializerMethodField() delete_url = SerializerMethodField() can_add = SerializerMethodField() can_change = SerializerMethodField() can_delete = SerializerMethodField() def _get_base_admin_url(self, obj): return f'admin:{obj._meta.app_label}_{obj._meta.model_name}' def get_url(self, viewname, *args, **kwargs): return self.context['request'].build_absolute_uri(reverse( viewname, args=args, kwargs=kwargs, )) def get_change_url(self, obj): return self.get_url( f'{self._get_base_admin_url(obj)}_change', obj.pk, ) def get_delete_url(self, obj): return self.get_url( f'{self._get_base_admin_url(obj)}_delete', obj.pk, ) def has_perm(self, permission, obj): return self.context['request'].user.has_perm(permission, obj=obj) def get_can_add(self, obj): return self.has_perm( f'libretto.add_{obj._meta.model_name}', obj, ) def get_can_change(self, obj): return self.has_perm( f'libretto.change_{obj._meta.model_name}', obj, ) def get_can_delete(self, obj): return self.has_perm( f'libretto.delete_{obj._meta.model_name}', obj, ) class AncrageSpatioTemporelSerializer(Field): def to_representation(self, obj): d = OrderedDict() for fieldname in sorted(obj.fields): d[fieldname] = getattr(obj, fieldname) lieu = d.get('lieu') if lieu is not None: d['lieu'] = reverse('lieu-detail', (lieu.pk,), request=self.context.get('request')) return d class IndividuSerializer(HyperlinkedModelSerializer): str = ReadOnlyField(source='__str__') html = ReadOnlyField() naissance = AncrageSpatioTemporelSerializer() deces = AncrageSpatioTemporelSerializer() professions = PrimaryKeyRelatedField(many=True, read_only=True) front_url = HyperlinkedIdentityField(view_name='individu_detail', lookup_field='slug') class Meta(object): model = Individu fields = ( 'id', 'str', 'html', 'nom', 'prenoms', 'naissance', 'deces', 'professions', 'parents', 'front_url', 'url' ) class EnsembleSerializer(HyperlinkedModelSerializer): str = ReadOnlyField(source='__str__') html = ReadOnlyField() type = StringRelatedField() front_url = HyperlinkedIdentityField(view_name='ensemble_detail', lookup_field='slug') class Meta(object): model = Ensemble fields = ( 'id', 'str', 'html', 'type', 'front_url', 'url' ) class LieuSerializer(HyperlinkedModelSerializer): str = ReadOnlyField(source='__str__') nature = StringRelatedField() front_url = HyperlinkedIdentityField(view_name='lieu_detail', lookup_field='slug') class Meta(object): model = Lieu fields = ( 'id', 'str', 'nom', 'nature', 'parent', 'front_url', 'url' ) class OeuvreSerializer(HyperlinkedModelSerializer): str = ReadOnlyField(source='__str__') titre_significatif = ReadOnlyField(source='get_titre_significatif') titre_non_significatif = ReadOnlyField(source='get_titre_non_significatif') description = ReadOnlyField(source='get_description') genre = StringRelatedField() auteurs = PrimaryKeyRelatedField(many=True, read_only=True) creation = AncrageSpatioTemporelSerializer() front_url = HyperlinkedIdentityField(view_name='oeuvre_detail', lookup_field='slug') class Meta(object): model = Oeuvre fields = ( 'id', 'str', 'extrait_de', 'titre_significatif', 'titre_non_significatif', 'description', 'genre', 'auteurs', 'creation', 'front_url', 'url' ) class SourceSerializer(CommonSerializer): auteurs = PrimaryKeyRelatedField(many=True, read_only=True) children = SerializerMethodField() small_thumbnail = SerializerMethodField() medium_thumbnail = SerializerMethodField() front_url = HyperlinkedIdentityField(view_name='source_permanent_detail', lookup_field='pk') taille_fichier = SerializerMethodField() has_images = ReadOnlyField() class Meta: model = Source exclude = () def get_children(self, obj): return list( obj.children.order_by('position').values_list('pk', flat=True) ) def get_small_thumbnail(self, obj): return self.context['request'].build_absolute_uri(obj.small_thumbnail) def get_medium_thumbnail(self, obj): return self.context['request'].build_absolute_uri(obj.medium_thumbnail) def get_taille_fichier(self, obj): try: size = obj.fichier.size except (ValueError, FileNotFoundError): size = 0 return filesizeformat(size) class AuteurSerializer(ModelSerializer): class Meta: model = Auteur exclude = () class ProfessionSerializer(CommonSerializer): html = ReadOnlyField(source='short_html') front_url = HyperlinkedIdentityField( view_name='profession_permanent_detail', lookup_field='pk', ) class Meta: model = Profession exclude = () class EvenementSerializer(CommonSerializer): front_url = HyperlinkedIdentityField( view_name='evenement_pk', lookup_field='pk', ) class Meta: model = Evenement exclude = () class PartieSerializer(CommonSerializer): front_url = HyperlinkedIdentityField(view_name='partie_detail', lookup_field='slug') class Meta: model = Partie exclude = () class UserSerializer(CommonSerializer): front_url = HyperlinkedIdentityField(view_name='user_profile', lookup_field='username') class Meta: model = HierarchicUser exclude = ( 'password', 'email', 'last_login', 'date_joined', 'show_email', 'willing_to_be_mentor', 'is_superuser', 'is_staff', 'is_active', 'groups', 'user_permissions', )
bsd-3-clause
-6,222,309,248,963,132,000
30.668182
79
0.616334
false
adamvduke/thrift-adamd
lib/py/setup.py
6
3405
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import sys try: from setuptools import setup, Extension except: from distutils.core import setup, Extension, Command from distutils.command.build_ext import build_ext from distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatformError # Fix to build sdist under vagrant import os if 'vagrant' in str(os.environ): del os.link include_dirs = [] if sys.platform == 'win32': include_dirs.append('compat/win32') ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError, IOError) else: ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError) class BuildFailed(Exception): pass class ve_build_ext(build_ext): def run(self): try: build_ext.run(self) except DistutilsPlatformError as x: raise BuildFailed() def build_extension(self, ext): try: build_ext.build_extension(self, ext) except ext_errors as x: raise BuildFailed() def run_setup(with_binary): if with_binary: extensions = dict( ext_modules = [ Extension('thrift.protocol.fastbinary', sources = ['src/protocol/fastbinary.c'], include_dirs = include_dirs, ) ], cmdclass=dict(build_ext=ve_build_ext) ) else: extensions = dict() setup(name = 'thrift', version = '1.0.0-dev', description = 'Python bindings for the Apache Thrift RPC system', author = 'Thrift Developers', author_email = '[email protected]', url = 'http://thrift.apache.org', license = 'Apache License 2.0', packages = [ 'thrift', 'thrift.protocol', 'thrift.transport', 'thrift.server', ], package_dir = {'thrift' : 'src'}, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Networking' ], use_2to3 = True, **extensions ) try: run_setup(True) except BuildFailed: print() print('*' * 80) print("An error occured while trying to compile with the C extension enabled") print("Attempting to build without the extension now") print('*' * 80) print() run_setup(False)
apache-2.0
6,929,761,598,889,673,000
29.954545
87
0.63025
false
SevInf/IEDriver
py/selenium/webdriver/remote/errorhandler.py
19
7739
# Copyright 2010 WebDriver committers # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from selenium.common.exceptions import ElementNotSelectableException from selenium.common.exceptions import ElementNotVisibleException from selenium.common.exceptions import InvalidCookieDomainException from selenium.common.exceptions import InvalidElementStateException from selenium.common.exceptions import InvalidSelectorException from selenium.common.exceptions import ImeNotAvailableException from selenium.common.exceptions import ImeActivationFailedException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoSuchFrameException from selenium.common.exceptions import NoSuchWindowException from selenium.common.exceptions import StaleElementReferenceException from selenium.common.exceptions import UnableToSetCookieException from selenium.common.exceptions import UnexpectedAlertPresentException from selenium.common.exceptions import NoAlertPresentException from selenium.common.exceptions import ErrorInResponseException from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import WebDriverException from selenium.common.exceptions import MoveTargetOutOfBoundsException try: basestring except NameError: # Python 3.x basestring = str class ErrorCode(object): """ Error codes defined in the WebDriver wire protocol. """ # Keep in sync with org.openqa.selenium.remote.ErrorCodes and errorcodes.h SUCCESS = 0 NO_SUCH_ELEMENT = [7, 'no such element'] NO_SUCH_FRAME = [8, 'no such frame'] UNKNOWN_COMMAND = [9, 'unknown command'] STALE_ELEMENT_REFERENCE = [10, 'stale element reference'] ELEMENT_NOT_VISIBLE = [11, 'element not visible'] INVALID_ELEMENT_STATE = [12, 'invalid element state'] UNKNOWN_ERROR = [13, 'unknown error'] ELEMENT_IS_NOT_SELECTABLE = [15, 'element not selectable'] JAVASCRIPT_ERROR = [17, 'javascript error'] XPATH_LOOKUP_ERROR = [19, 'invalid selector'] TIMEOUT = [21, 'timeout'] NO_SUCH_WINDOW = [23, 'no such window'] INVALID_COOKIE_DOMAIN = [24, 'invalid cookie domain'] UNABLE_TO_SET_COOKIE = [25, 'unable to set cookie'] UNEXPECTED_ALERT_OPEN = [26, 'unexpected alert open'] NO_ALERT_OPEN = [27, 'no such alert'] SCRIPT_TIMEOUT = [28, 'script timeout'] INVALID_ELEMENT_COORDINATES = [29, 'invalid element coordinates'] IME_NOT_AVAILABLE = [30, 'ime not available'] IME_ENGINE_ACTIVATION_FAILED = [31, 'ime engine activation failed'] INVALID_SELECTOR = [32, 'invalid selector'] MOVE_TARGET_OUT_OF_BOUNDS = [34, 'move target out of bounds'] INVALID_XPATH_SELECTOR = [51, 'invalid selector'] INVALID_XPATH_SELECTOR_RETURN_TYPER = [52, 'invalid selector'] METHOD_NOT_ALLOWED = [405, 'unsupported operation'] class ErrorHandler(object): """ Handles errors returned by the WebDriver server. """ def check_response(self, response): """ Checks that a JSON response from the WebDriver does not have an error. :Args: - response - The JSON response from the WebDriver server as a dictionary object. :Raises: If the response contains an error message. """ status = response['status'] if status == ErrorCode.SUCCESS: return exception_class = ErrorInResponseException if status in ErrorCode.NO_SUCH_ELEMENT: exception_class = NoSuchElementException elif status in ErrorCode.NO_SUCH_FRAME: exception_class = NoSuchFrameException elif status in ErrorCode.NO_SUCH_WINDOW: exception_class = NoSuchWindowException elif status in ErrorCode.STALE_ELEMENT_REFERENCE: exception_class = StaleElementReferenceException elif status in ErrorCode.ELEMENT_NOT_VISIBLE: exception_class = ElementNotVisibleException elif status in ErrorCode.INVALID_ELEMENT_STATE: exception_class = InvalidElementStateException elif status in ErrorCode.INVALID_SELECTOR \ or status in ErrorCode.INVALID_XPATH_SELECTOR \ or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER: exception_class = InvalidSelectorException elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE: exception_class = ElementNotSelectableException elif status in ErrorCode.INVALID_COOKIE_DOMAIN: exception_class = WebDriverException elif status in ErrorCode.UNABLE_TO_SET_COOKIE: exception_class = WebDriverException elif status in ErrorCode.TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.SCRIPT_TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.UNKNOWN_ERROR: exception_class = WebDriverException elif status in ErrorCode.UNEXPECTED_ALERT_OPEN: exception_class = UnexpectedAlertPresentException elif status in ErrorCode.NO_ALERT_OPEN: exception_class = NoAlertPresentException elif status in ErrorCode.IME_NOT_AVAILABLE: exception_class = ImeNotAvailableException elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED: exception_class = ImeActivationFailedException elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS: exception_class = MoveTargetOutOfBoundsException else: exception_class = WebDriverException value = response['value'] if isinstance(value, basestring): if exception_class == ErrorInResponseException: raise exception_class(response, value) raise exception_class(value) message = '' if 'message' in value: message = value['message'] screen = None if 'screen' in value: screen = value['screen'] stacktrace = None if 'stackTrace' in value and value['stackTrace']: stacktrace = [] try: for frame in value['stackTrace']: line = self._value_or_default(frame, 'lineNumber', '') file = self._value_or_default(frame, 'fileName', '<anonymous>') if line: file = "%s:%s" % (file, line) meth = self._value_or_default(frame, 'methodName', '<anonymous>') if 'className' in frame: meth = "%s.%s" % (frame['className'], meth) msg = " at %s (%s)" msg = msg % (meth, file) stacktrace.append(msg) except TypeError: pass if exception_class == ErrorInResponseException: raise exception_class(response, message) elif exception_class == UnexpectedAlertPresentException and 'alert' in value: raise exception_class(message, screen, stacktrace, value['alert'].get('text')) raise exception_class(message, screen, stacktrace) def _value_or_default(self, obj, key, default): return obj[key] if key in obj else default
apache-2.0
-3,229,968,248,950,638,600
44.792899
90
0.680837
false
manahl/pytest-plugins
pytest-server-fixtures/pytest_server_fixtures/s3.py
1
3205
# coding: utf-8 """ Pytest fixtures to launch a minio S3 server and get a bucket for it. """ from __future__ import absolute_import, division, print_function, unicode_literals import uuid from collections import namedtuple import logging import os import pytest from future.utils import text_type from pytest_fixture_config import requires_config from . import CONFIG from .http import HTTPTestServer log = logging.getLogger(__name__) def _s3_server(request): server = MinioServer() server.start() request.addfinalizer(server.teardown) return server @pytest.fixture(scope="session") @requires_config(CONFIG, ['minio_executable']) def s3_server(request): """ Creates a session-scoped temporary S3 server using the 'minio' tool. The primary method on the server object is `s3_server.get_s3_client()`, which returns a boto3 `Resource` (`boto3.resource('s3', ...)`) """ return _s3_server(request) BucketInfo = namedtuple('BucketInfo', ['client', 'name']) # Minio is a little too slow to start for each function call # Start it once per session and get a new bucket for each function instead. @pytest.fixture(scope="function") def s3_bucket(s3_server): # pylint: disable=redefined-outer-name """ Creates a function-scoped s3 bucket, returning a BucketInfo namedtuple with `s3_bucket.client` and `s3_bucket.name` fields """ client = s3_server.get_s3_client() bucket_name = text_type(uuid.uuid4()) client.create_bucket(Bucket=bucket_name) return BucketInfo(client, bucket_name) class MinioServer(HTTPTestServer): random_port = True aws_access_key_id = "MINIO_TEST_ACCESS" aws_secret_access_key = "MINIO_TEST_SECRET" def __init__(self, workspace=None, delete=None, preserve_sys_path=False, **kwargs): env = kwargs.get('env', os.environ.copy()) env.update({"MINIO_ACCESS_KEY": self.aws_access_key_id, "MINIO_SECRET_KEY": self.aws_secret_access_key}) kwargs['env'] = env kwargs['hostname'] = "0.0.0.0" # minio doesn't seem to allow binding to 127.0.0.0/8 super(MinioServer, self).__init__(workspace=workspace, delete=delete, preserve_sys_path=preserve_sys_path, **kwargs) def get_s3_client(self): # Region name and signature are to satisfy minio import boto3 import botocore.client s3 = boto3.resource( 's3', endpoint_url=self.boto_endpoint_url, aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, region_name='us-east-1', config=botocore.client.Config(signature_version='s3v4'), ) return s3 @property def datadir(self): return self.workspace / 'minio-db' @property def boto_endpoint_url(self): return self.uri def pre_setup(self): self.datadir.mkdir() # pylint: disable=no-value-for-parameter @property def run_cmd(self): cmdargs = [ CONFIG.minio_executable, "server", "--address", "{}:{}".format(self.hostname, self.port), text_type(self.datadir), ] return cmdargs
mit
6,468,175,324,941,757,000
30.732673
124
0.656162
false
mixturemodel-flow/tensorflow
tensorflow/contrib/keras/python/keras/layers/lstm_test.py
11
11737
# 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 LSTM layer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.keras.python import keras from tensorflow.contrib.keras.python.keras import testing_utils from tensorflow.python.platform import test class LSTMLayerTest(test.TestCase): def test_return_sequences_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 with self.test_session(): testing_utils.layer_test( keras.layers.LSTM, kwargs={'units': units, 'return_sequences': True}, input_shape=(num_samples, timesteps, embedding_dim)) def test_dynamic_behavior_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 with self.test_session(): layer = keras.layers.LSTM(units, input_shape=(None, embedding_dim)) model = keras.models.Sequential() model.add(layer) model.compile('sgd', 'mse') x = np.random.random((num_samples, timesteps, embedding_dim)) y = np.random.random((num_samples, units)) model.train_on_batch(x, y) def test_dropout_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 with self.test_session(): testing_utils.layer_test( keras.layers.LSTM, kwargs={'units': units, 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) def test_implementation_mode_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 with self.test_session(): for mode in [0, 1, 2]: testing_utils.layer_test( keras.layers.LSTM, kwargs={'units': units, 'implementation': mode}, input_shape=(num_samples, timesteps, embedding_dim)) def test_statefulness_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 layer_class = keras.layers.LSTM with self.test_session(): model = keras.models.Sequential() model.add( keras.layers.Embedding( 4, embedding_dim, mask_zero=True, input_length=timesteps, batch_input_shape=(num_samples, timesteps))) layer = layer_class( units, return_sequences=False, stateful=True, weights=None) model.add(layer) model.compile(optimizer='sgd', loss='mse') out1 = model.predict(np.ones((num_samples, timesteps))) self.assertEqual(out1.shape, (num_samples, units)) # train once so that the states change model.train_on_batch( np.ones((num_samples, timesteps)), np.ones((num_samples, units))) out2 = model.predict(np.ones((num_samples, timesteps))) # if the state is not reset, output should be different self.assertNotEqual(out1.max(), out2.max()) # check that output changes after states are reset # (even though the model itself didn't change) layer.reset_states() out3 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out2.max(), out3.max()) # check that container-level reset_states() works model.reset_states() out4 = model.predict(np.ones((num_samples, timesteps))) self.assertAllClose(out3, out4, atol=1e-5) # check that the call to `predict` updated the states out5 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out4.max(), out5.max()) # Check masking layer.reset_states() left_padded_input = np.ones((num_samples, timesteps)) left_padded_input[0, :1] = 0 left_padded_input[1, :2] = 0 out6 = model.predict(left_padded_input) layer.reset_states() right_padded_input = np.ones((num_samples, timesteps)) right_padded_input[0, -1:] = 0 right_padded_input[1, -2:] = 0 out7 = model.predict(right_padded_input) self.assertAllClose(out7, out6, atol=1e-5) def test_regularization_LSTM(self): embedding_dim = 4 layer_class = keras.layers.LSTM with self.test_session(): layer = layer_class( 5, return_sequences=False, weights=None, input_shape=(None, embedding_dim), kernel_regularizer=keras.regularizers.l1(0.01), recurrent_regularizer=keras.regularizers.l1(0.01), bias_regularizer='l2', activity_regularizer='l1') layer.build((None, None, 2)) self.assertEqual(len(layer.losses), 3) layer(keras.backend.variable(np.ones((2, 3, 2)))) self.assertEqual(len(layer.losses), 4) layer = layer_class( 5, return_sequences=False, weights=None, input_shape=(None, embedding_dim), kernel_constraint=keras.constraints.max_norm(0.01), recurrent_constraint=keras.constraints.max_norm(0.01), bias_constraint='max_norm') layer.build((None, None, embedding_dim)) self.assertEqual(len(layer.constraints), 3) def test_with_masking_layer_LSTM(self): layer_class = keras.layers.LSTM with self.test_session(): inputs = np.random.random((2, 3, 4)) targets = np.abs(np.random.random((2, 3, 5))) targets /= targets.sum(axis=-1, keepdims=True) model = keras.models.Sequential() model.add(keras.layers.Masking(input_shape=(3, 4))) model.add(layer_class(units=5, return_sequences=True, unroll=False)) model.compile(loss='categorical_crossentropy', optimizer='adam') model.fit(inputs, targets, epochs=1, batch_size=2, verbose=1) def test_from_config_LSTM(self): layer_class = keras.layers.LSTM for stateful in (False, True): l1 = layer_class(units=1, stateful=stateful) l2 = layer_class.from_config(l1.get_config()) assert l1.get_config() == l2.get_config() def test_specify_initial_state_keras_tensor(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 with self.test_session(): # Test with Keras tensor inputs = keras.Input((timesteps, embedding_dim)) initial_state = [keras.Input((units,)) for _ in range(num_states)] layer = keras.layers.LSTM(units) if len(initial_state) == 1: output = layer(inputs, initial_state=initial_state[0]) else: output = layer(inputs, initial_state=initial_state) assert initial_state[0] in layer.inbound_nodes[0].input_tensors model = keras.models.Model([inputs] + initial_state, output) model.compile(loss='categorical_crossentropy', optimizer='adam') inputs = np.random.random((num_samples, timesteps, embedding_dim)) initial_state = [np.random.random((num_samples, units)) for _ in range(num_states)] targets = np.random.random((num_samples, units)) model.train_on_batch([inputs] + initial_state, targets) def test_specify_initial_state_non_keras_tensor(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 with self.test_session(): # Test with non-Keras tensor inputs = keras.Input((timesteps, embedding_dim)) initial_state = [keras.backend.random_normal_variable( (num_samples, units), 0, 1) for _ in range(num_states)] layer = keras.layers.LSTM(units) output = layer(inputs, initial_state=initial_state) model = keras.models.Model(inputs, output) model.compile(loss='categorical_crossentropy', optimizer='adam') inputs = np.random.random((num_samples, timesteps, embedding_dim)) targets = np.random.random((num_samples, units)) model.train_on_batch(inputs, targets) def test_reset_states_with_values(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 with self.test_session(): layer = keras.layers.LSTM(units, stateful=True) layer.build((num_samples, timesteps, embedding_dim)) layer.reset_states() assert len(layer.states) == num_states assert layer.states[0] is not None self.assertAllClose( keras.backend.eval(layer.states[0]), np.zeros(keras.backend.int_shape(layer.states[0])), atol=1e-4) state_shapes = [keras.backend.int_shape(state) for state in layer.states] values = [np.ones(shape) for shape in state_shapes] if len(values) == 1: values = values[0] layer.reset_states(values) self.assertAllClose( keras.backend.eval(layer.states[0]), np.ones(keras.backend.int_shape(layer.states[0])), atol=1e-4) # Test with invalid data with self.assertRaises(ValueError): layer.reset_states([1] * (len(layer.states) + 1)) def test_specify_state_with_masking(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 with self.test_session(): inputs = keras.Input((timesteps, embedding_dim)) _ = keras.layers.Masking()(inputs) initial_state = [keras.Input((units,)) for _ in range(num_states)] output = keras.layers.LSTM(units)(inputs, initial_state=initial_state) model = keras.models.Model([inputs] + initial_state, output) model.compile(loss='categorical_crossentropy', optimizer='adam') inputs = np.random.random((num_samples, timesteps, embedding_dim)) initial_state = [np.random.random((num_samples, units)) for _ in range(num_states)] targets = np.random.random((num_samples, units)) model.train_on_batch([inputs] + initial_state, targets) def test_return_state(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 with self.test_session(): inputs = keras.Input(batch_shape=(num_samples, timesteps, embedding_dim)) layer = keras.layers.LSTM(units, return_state=True, stateful=True) outputs = layer(inputs) state = outputs[1:] assert len(state) == num_states model = keras.models.Model(inputs, state[0]) inputs = np.random.random((num_samples, timesteps, embedding_dim)) state = model.predict(inputs) self.assertAllClose(keras.backend.eval(layer.states[0]), state, atol=1e-4) def test_state_reuse(self): timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 with self.test_session(): inputs = keras.Input(batch_shape=(num_samples, timesteps, embedding_dim)) layer = keras.layers.LSTM(units, return_state=True, return_sequences=True) outputs = layer(inputs) output, state = outputs[0], outputs[1:] output = keras.layers.LSTM(units)(output, initial_state=state) model = keras.models.Model(inputs, output) inputs = np.random.random((num_samples, timesteps, embedding_dim)) outputs = model.predict(inputs) if __name__ == '__main__': test.main()
apache-2.0
6,139,353,636,591,519,000
34.246246
80
0.63253
false
scieloorg/elixir
setup.py
1
1133
#!/usr/bin/env python import sys import re from setuptools import setup, Extension from elixir import elixir version = elixir.__version__ install_requires = [ 'requests', 'xylose', 'lxml' ] tests_require = install_requires[:] setup( name="elixir", version=version, description="Library to bring alive the legacy documents from the SciELO Methodology", author="Fabio Batalha", author_email="[email protected]", license="BSD 2-Clause", url="http://github.com/scieloorg/elixir/", py_modules=["elixir"], classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Topic :: Software Development :: Utilities", "Topic :: Software Development :: Libraries :: Python Modules", ], dependency_links=['http://github.com/scieloorg/xylose/tarball/master#egg=xylose'], setup_requires=["nose>=1.0", "coverage"], install_requires=install_requires, tests_require=tests_require, test_suite="nose.collector", )
bsd-2-clause
-692,444,426,146,494,200
28.051282
90
0.658429
false
ANGGAIBNUSAPUTRA/git-repo
manifest_xml.py
13
32194
# # Copyright (C) 2008 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import itertools import os import re import sys import xml.dom.minidom from pyversion import is_python3 if is_python3(): import urllib.parse else: import imp import urlparse urllib = imp.new_module('urllib') urllib.parse = urlparse import gitc_utils from git_config import GitConfig from git_refs import R_HEADS, HEAD from project import RemoteSpec, Project, MetaProject from error import ManifestParseError, ManifestInvalidRevisionError MANIFEST_FILE_NAME = 'manifest.xml' LOCAL_MANIFEST_NAME = 'local_manifest.xml' LOCAL_MANIFESTS_DIR_NAME = 'local_manifests' # urljoin gets confused if the scheme is not known. urllib.parse.uses_relative.extend(['ssh', 'git', 'persistent-https', 'rpc']) urllib.parse.uses_netloc.extend(['ssh', 'git', 'persistent-https', 'rpc']) class _Default(object): """Project defaults within the manifest.""" revisionExpr = None destBranchExpr = None remote = None sync_j = 1 sync_c = False sync_s = False def __eq__(self, other): return self.__dict__ == other.__dict__ def __ne__(self, other): return self.__dict__ != other.__dict__ class _XmlRemote(object): def __init__(self, name, alias=None, fetch=None, manifestUrl=None, review=None, revision=None): self.name = name self.fetchUrl = fetch self.manifestUrl = manifestUrl self.remoteAlias = alias self.reviewUrl = review self.revision = revision self.resolvedFetchUrl = self._resolveFetchUrl() def __eq__(self, other): return self.__dict__ == other.__dict__ def __ne__(self, other): return self.__dict__ != other.__dict__ def _resolveFetchUrl(self): url = self.fetchUrl.rstrip('/') manifestUrl = self.manifestUrl.rstrip('/') # urljoin will gets confused over quite a few things. The ones we care # about here are: # * no scheme in the base url, like <hostname:port> # We handle no scheme by replacing it with an obscure protocol, gopher # and then replacing it with the original when we are done. if manifestUrl.find(':') != manifestUrl.find('/') - 1: url = urllib.parse.urljoin('gopher://' + manifestUrl, url) url = re.sub(r'^gopher://', '', url) else: url = urllib.parse.urljoin(manifestUrl, url) return url def ToRemoteSpec(self, projectName): url = self.resolvedFetchUrl.rstrip('/') + '/' + projectName remoteName = self.name if self.remoteAlias: remoteName = self.remoteAlias return RemoteSpec(remoteName, url, self.reviewUrl) class XmlManifest(object): """manages the repo configuration file""" def __init__(self, repodir): self.repodir = os.path.abspath(repodir) self.topdir = os.path.dirname(self.repodir) self.manifestFile = os.path.join(self.repodir, MANIFEST_FILE_NAME) self.globalConfig = GitConfig.ForUser() self.localManifestWarning = False self.isGitcClient = False self.repoProject = MetaProject(self, 'repo', gitdir = os.path.join(repodir, 'repo/.git'), worktree = os.path.join(repodir, 'repo')) self.manifestProject = MetaProject(self, 'manifests', gitdir = os.path.join(repodir, 'manifests.git'), worktree = os.path.join(repodir, 'manifests')) self._Unload() def Override(self, name): """Use a different manifest, just for the current instantiation. """ path = os.path.join(self.manifestProject.worktree, name) if not os.path.isfile(path): raise ManifestParseError('manifest %s not found' % name) old = self.manifestFile try: self.manifestFile = path self._Unload() self._Load() finally: self.manifestFile = old def Link(self, name): """Update the repo metadata to use a different manifest. """ self.Override(name) try: if os.path.lexists(self.manifestFile): os.remove(self.manifestFile) os.symlink('manifests/%s' % name, self.manifestFile) except OSError as e: raise ManifestParseError('cannot link manifest %s: %s' % (name, str(e))) def _RemoteToXml(self, r, doc, root): e = doc.createElement('remote') root.appendChild(e) e.setAttribute('name', r.name) e.setAttribute('fetch', r.fetchUrl) if r.remoteAlias is not None: e.setAttribute('alias', r.remoteAlias) if r.reviewUrl is not None: e.setAttribute('review', r.reviewUrl) if r.revision is not None: e.setAttribute('revision', r.revision) def _ParseGroups(self, groups): return [x for x in re.split(r'[,\s]+', groups) if x] def Save(self, fd, peg_rev=False, peg_rev_upstream=True, groups=None): """Write the current manifest out to the given file descriptor. """ mp = self.manifestProject if groups is None: groups = mp.config.GetString('manifest.groups') if groups: groups = self._ParseGroups(groups) doc = xml.dom.minidom.Document() root = doc.createElement('manifest') doc.appendChild(root) # Save out the notice. There's a little bit of work here to give it the # right whitespace, which assumes that the notice is automatically indented # by 4 by minidom. if self.notice: notice_element = root.appendChild(doc.createElement('notice')) notice_lines = self.notice.splitlines() indented_notice = ('\n'.join(" "*4 + line for line in notice_lines))[4:] notice_element.appendChild(doc.createTextNode(indented_notice)) d = self.default for r in sorted(self.remotes): self._RemoteToXml(self.remotes[r], doc, root) if self.remotes: root.appendChild(doc.createTextNode('')) have_default = False e = doc.createElement('default') if d.remote: have_default = True e.setAttribute('remote', d.remote.name) if d.revisionExpr: have_default = True e.setAttribute('revision', d.revisionExpr) if d.destBranchExpr: have_default = True e.setAttribute('dest-branch', d.destBranchExpr) if d.sync_j > 1: have_default = True e.setAttribute('sync-j', '%d' % d.sync_j) if d.sync_c: have_default = True e.setAttribute('sync-c', 'true') if d.sync_s: have_default = True e.setAttribute('sync-s', 'true') if have_default: root.appendChild(e) root.appendChild(doc.createTextNode('')) if self._manifest_server: e = doc.createElement('manifest-server') e.setAttribute('url', self._manifest_server) root.appendChild(e) root.appendChild(doc.createTextNode('')) def output_projects(parent, parent_node, projects): for project_name in projects: for project in self._projects[project_name]: output_project(parent, parent_node, project) def output_project(parent, parent_node, p): if not p.MatchesGroups(groups): return name = p.name relpath = p.relpath if parent: name = self._UnjoinName(parent.name, name) relpath = self._UnjoinRelpath(parent.relpath, relpath) e = doc.createElement('project') parent_node.appendChild(e) e.setAttribute('name', name) if relpath != name: e.setAttribute('path', relpath) remoteName = None if d.remote: remoteName = d.remote.remoteAlias or d.remote.name if not d.remote or p.remote.name != remoteName: remoteName = p.remote.name e.setAttribute('remote', remoteName) if peg_rev: if self.IsMirror: value = p.bare_git.rev_parse(p.revisionExpr + '^0') else: value = p.work_git.rev_parse(HEAD + '^0') e.setAttribute('revision', value) if peg_rev_upstream: if p.upstream: e.setAttribute('upstream', p.upstream) elif value != p.revisionExpr: # Only save the origin if the origin is not a sha1, and the default # isn't our value e.setAttribute('upstream', p.revisionExpr) else: revision = self.remotes[remoteName].revision or d.revisionExpr if not revision or revision != p.revisionExpr: e.setAttribute('revision', p.revisionExpr) if p.upstream and p.upstream != p.revisionExpr: e.setAttribute('upstream', p.upstream) if p.dest_branch and p.dest_branch != d.destBranchExpr: e.setAttribute('dest-branch', p.dest_branch) for c in p.copyfiles: ce = doc.createElement('copyfile') ce.setAttribute('src', c.src) ce.setAttribute('dest', c.dest) e.appendChild(ce) for l in p.linkfiles: le = doc.createElement('linkfile') le.setAttribute('src', l.src) le.setAttribute('dest', l.dest) e.appendChild(le) default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath] egroups = [g for g in p.groups if g not in default_groups] if egroups: e.setAttribute('groups', ','.join(egroups)) for a in p.annotations: if a.keep == "true": ae = doc.createElement('annotation') ae.setAttribute('name', a.name) ae.setAttribute('value', a.value) e.appendChild(ae) if p.sync_c: e.setAttribute('sync-c', 'true') if p.sync_s: e.setAttribute('sync-s', 'true') if p.clone_depth: e.setAttribute('clone-depth', str(p.clone_depth)) self._output_manifest_project_extras(p, e) if p.subprojects: subprojects = set(subp.name for subp in p.subprojects) output_projects(p, e, list(sorted(subprojects))) projects = set(p.name for p in self._paths.values() if not p.parent) output_projects(None, root, list(sorted(projects))) if self._repo_hooks_project: root.appendChild(doc.createTextNode('')) e = doc.createElement('repo-hooks') e.setAttribute('in-project', self._repo_hooks_project.name) e.setAttribute('enabled-list', ' '.join(self._repo_hooks_project.enabled_repo_hooks)) root.appendChild(e) doc.writexml(fd, '', ' ', '\n', 'UTF-8') def _output_manifest_project_extras(self, p, e): """Manifests can modify e if they support extra project attributes.""" pass @property def paths(self): self._Load() return self._paths @property def projects(self): self._Load() return list(self._paths.values()) @property def remotes(self): self._Load() return self._remotes @property def default(self): self._Load() return self._default @property def repo_hooks_project(self): self._Load() return self._repo_hooks_project @property def notice(self): self._Load() return self._notice @property def manifest_server(self): self._Load() return self._manifest_server @property def IsMirror(self): return self.manifestProject.config.GetBoolean('repo.mirror') @property def IsArchive(self): return self.manifestProject.config.GetBoolean('repo.archive') def _Unload(self): self._loaded = False self._projects = {} self._paths = {} self._remotes = {} self._default = None self._repo_hooks_project = None self._notice = None self.branch = None self._manifest_server = None def _Load(self): if not self._loaded: m = self.manifestProject b = m.GetBranch(m.CurrentBranch).merge if b is not None and b.startswith(R_HEADS): b = b[len(R_HEADS):] self.branch = b nodes = [] nodes.append(self._ParseManifestXml(self.manifestFile, self.manifestProject.worktree)) local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME) if os.path.exists(local): if not self.localManifestWarning: self.localManifestWarning = True print('warning: %s is deprecated; put local manifests in `%s` instead' % (LOCAL_MANIFEST_NAME, os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)), file=sys.stderr) nodes.append(self._ParseManifestXml(local, self.repodir)) local_dir = os.path.abspath(os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)) try: for local_file in sorted(os.listdir(local_dir)): if local_file.endswith('.xml'): local = os.path.join(local_dir, local_file) nodes.append(self._ParseManifestXml(local, self.repodir)) except OSError: pass try: self._ParseManifest(nodes) except ManifestParseError as e: # There was a problem parsing, unload ourselves in case they catch # this error and try again later, we will show the correct error self._Unload() raise e if self.IsMirror: self._AddMetaProjectMirror(self.repoProject) self._AddMetaProjectMirror(self.manifestProject) self._loaded = True def _ParseManifestXml(self, path, include_root): try: root = xml.dom.minidom.parse(path) except (OSError, xml.parsers.expat.ExpatError) as e: raise ManifestParseError("error parsing manifest %s: %s" % (path, e)) if not root or not root.childNodes: raise ManifestParseError("no root node in %s" % (path,)) for manifest in root.childNodes: if manifest.nodeName == 'manifest': break else: raise ManifestParseError("no <manifest> in %s" % (path,)) nodes = [] for node in manifest.childNodes: # pylint:disable=W0631 # We only get here if manifest is initialised if node.nodeName == 'include': name = self._reqatt(node, 'name') fp = os.path.join(include_root, name) if not os.path.isfile(fp): raise ManifestParseError("include %s doesn't exist or isn't a file" % (name,)) try: nodes.extend(self._ParseManifestXml(fp, include_root)) # should isolate this to the exact exception, but that's # tricky. actual parsing implementation may vary. except (KeyboardInterrupt, RuntimeError, SystemExit): raise except Exception as e: raise ManifestParseError( "failed parsing included manifest %s: %s", (name, e)) else: nodes.append(node) return nodes def _ParseManifest(self, node_list): for node in itertools.chain(*node_list): if node.nodeName == 'remote': remote = self._ParseRemote(node) if remote: if remote.name in self._remotes: if remote != self._remotes[remote.name]: raise ManifestParseError( 'remote %s already exists with different attributes' % (remote.name)) else: self._remotes[remote.name] = remote for node in itertools.chain(*node_list): if node.nodeName == 'default': new_default = self._ParseDefault(node) if self._default is None: self._default = new_default elif new_default != self._default: raise ManifestParseError('duplicate default in %s' % (self.manifestFile)) if self._default is None: self._default = _Default() for node in itertools.chain(*node_list): if node.nodeName == 'notice': if self._notice is not None: raise ManifestParseError( 'duplicate notice in %s' % (self.manifestFile)) self._notice = self._ParseNotice(node) for node in itertools.chain(*node_list): if node.nodeName == 'manifest-server': url = self._reqatt(node, 'url') if self._manifest_server is not None: raise ManifestParseError( 'duplicate manifest-server in %s' % (self.manifestFile)) self._manifest_server = url def recursively_add_projects(project): projects = self._projects.setdefault(project.name, []) if project.relpath is None: raise ManifestParseError( 'missing path for %s in %s' % (project.name, self.manifestFile)) if project.relpath in self._paths: raise ManifestParseError( 'duplicate path %s in %s' % (project.relpath, self.manifestFile)) self._paths[project.relpath] = project projects.append(project) for subproject in project.subprojects: recursively_add_projects(subproject) for node in itertools.chain(*node_list): if node.nodeName == 'project': project = self._ParseProject(node) recursively_add_projects(project) if node.nodeName == 'extend-project': name = self._reqatt(node, 'name') if name not in self._projects: raise ManifestParseError('extend-project element specifies non-existent ' 'project: %s' % name) path = node.getAttribute('path') groups = node.getAttribute('groups') if groups: groups = self._ParseGroups(groups) for p in self._projects[name]: if path and p.relpath != path: continue if groups: p.groups.extend(groups) if node.nodeName == 'repo-hooks': # Get the name of the project and the (space-separated) list of enabled. repo_hooks_project = self._reqatt(node, 'in-project') enabled_repo_hooks = self._reqatt(node, 'enabled-list').split() # Only one project can be the hooks project if self._repo_hooks_project is not None: raise ManifestParseError( 'duplicate repo-hooks in %s' % (self.manifestFile)) # Store a reference to the Project. try: repo_hooks_projects = self._projects[repo_hooks_project] except KeyError: raise ManifestParseError( 'project %s not found for repo-hooks' % (repo_hooks_project)) if len(repo_hooks_projects) != 1: raise ManifestParseError( 'internal error parsing repo-hooks in %s' % (self.manifestFile)) self._repo_hooks_project = repo_hooks_projects[0] # Store the enabled hooks in the Project object. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks if node.nodeName == 'remove-project': name = self._reqatt(node, 'name') if name not in self._projects: raise ManifestParseError('remove-project element specifies non-existent ' 'project: %s' % name) for p in self._projects[name]: del self._paths[p.relpath] del self._projects[name] # If the manifest removes the hooks project, treat it as if it deleted # the repo-hooks element too. if self._repo_hooks_project and (self._repo_hooks_project.name == name): self._repo_hooks_project = None def _AddMetaProjectMirror(self, m): name = None m_url = m.GetRemote(m.remote.name).url if m_url.endswith('/.git'): raise ManifestParseError('refusing to mirror %s' % m_url) if self._default and self._default.remote: url = self._default.remote.resolvedFetchUrl if not url.endswith('/'): url += '/' if m_url.startswith(url): remote = self._default.remote name = m_url[len(url):] if name is None: s = m_url.rindex('/') + 1 manifestUrl = self.manifestProject.config.GetString('remote.origin.url') remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl) name = m_url[s:] if name.endswith('.git'): name = name[:-4] if name not in self._projects: m.PreSync() gitdir = os.path.join(self.topdir, '%s.git' % name) project = Project(manifest = self, name = name, remote = remote.ToRemoteSpec(name), gitdir = gitdir, objdir = gitdir, worktree = None, relpath = name or None, revisionExpr = m.revisionExpr, revisionId = None) self._projects[project.name] = [project] self._paths[project.relpath] = project def _ParseRemote(self, node): """ reads a <remote> element from the manifest file """ name = self._reqatt(node, 'name') alias = node.getAttribute('alias') if alias == '': alias = None fetch = self._reqatt(node, 'fetch') review = node.getAttribute('review') if review == '': review = None revision = node.getAttribute('revision') if revision == '': revision = None manifestUrl = self.manifestProject.config.GetString('remote.origin.url') return _XmlRemote(name, alias, fetch, manifestUrl, review, revision) def _ParseDefault(self, node): """ reads a <default> element from the manifest file """ d = _Default() d.remote = self._get_remote(node) d.revisionExpr = node.getAttribute('revision') if d.revisionExpr == '': d.revisionExpr = None d.destBranchExpr = node.getAttribute('dest-branch') or None sync_j = node.getAttribute('sync-j') if sync_j == '' or sync_j is None: d.sync_j = 1 else: d.sync_j = int(sync_j) sync_c = node.getAttribute('sync-c') if not sync_c: d.sync_c = False else: d.sync_c = sync_c.lower() in ("yes", "true", "1") sync_s = node.getAttribute('sync-s') if not sync_s: d.sync_s = False else: d.sync_s = sync_s.lower() in ("yes", "true", "1") return d def _ParseNotice(self, node): """ reads a <notice> element from the manifest file The <notice> element is distinct from other tags in the XML in that the data is conveyed between the start and end tag (it's not an empty-element tag). The white space (carriage returns, indentation) for the notice element is relevant and is parsed in a way that is based on how python docstrings work. In fact, the code is remarkably similar to here: http://www.python.org/dev/peps/pep-0257/ """ # Get the data out of the node... notice = node.childNodes[0].data # Figure out minimum indentation, skipping the first line (the same line # as the <notice> tag)... minIndent = sys.maxsize lines = notice.splitlines() for line in lines[1:]: lstrippedLine = line.lstrip() if lstrippedLine: indent = len(line) - len(lstrippedLine) minIndent = min(indent, minIndent) # Strip leading / trailing blank lines and also indentation. cleanLines = [lines[0].strip()] for line in lines[1:]: cleanLines.append(line[minIndent:].rstrip()) # Clear completely blank lines from front and back... while cleanLines and not cleanLines[0]: del cleanLines[0] while cleanLines and not cleanLines[-1]: del cleanLines[-1] return '\n'.join(cleanLines) def _JoinName(self, parent_name, name): return os.path.join(parent_name, name) def _UnjoinName(self, parent_name, name): return os.path.relpath(name, parent_name) def _ParseProject(self, node, parent = None, **extra_proj_attrs): """ reads a <project> element from the manifest file """ name = self._reqatt(node, 'name') if parent: name = self._JoinName(parent.name, name) remote = self._get_remote(node) if remote is None: remote = self._default.remote if remote is None: raise ManifestParseError("no remote for project %s within %s" % (name, self.manifestFile)) revisionExpr = node.getAttribute('revision') or remote.revision if not revisionExpr: revisionExpr = self._default.revisionExpr if not revisionExpr: raise ManifestParseError("no revision for project %s within %s" % (name, self.manifestFile)) path = node.getAttribute('path') if not path: path = name if path.startswith('/'): raise ManifestParseError("project %s path cannot be absolute in %s" % (name, self.manifestFile)) rebase = node.getAttribute('rebase') if not rebase: rebase = True else: rebase = rebase.lower() in ("yes", "true", "1") sync_c = node.getAttribute('sync-c') if not sync_c: sync_c = False else: sync_c = sync_c.lower() in ("yes", "true", "1") sync_s = node.getAttribute('sync-s') if not sync_s: sync_s = self._default.sync_s else: sync_s = sync_s.lower() in ("yes", "true", "1") clone_depth = node.getAttribute('clone-depth') if clone_depth: try: clone_depth = int(clone_depth) if clone_depth <= 0: raise ValueError() except ValueError: raise ManifestParseError('invalid clone-depth %s in %s' % (clone_depth, self.manifestFile)) dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr upstream = node.getAttribute('upstream') groups = '' if node.hasAttribute('groups'): groups = node.getAttribute('groups') groups = self._ParseGroups(groups) if parent is None: relpath, worktree, gitdir, objdir = self.GetProjectPaths(name, path) else: relpath, worktree, gitdir, objdir = \ self.GetSubprojectPaths(parent, name, path) default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath] groups.extend(set(default_groups).difference(groups)) if self.IsMirror and node.hasAttribute('force-path'): if node.getAttribute('force-path').lower() in ("yes", "true", "1"): gitdir = os.path.join(self.topdir, '%s.git' % path) project = Project(manifest = self, name = name, remote = remote.ToRemoteSpec(name), gitdir = gitdir, objdir = objdir, worktree = worktree, relpath = relpath, revisionExpr = revisionExpr, revisionId = None, rebase = rebase, groups = groups, sync_c = sync_c, sync_s = sync_s, clone_depth = clone_depth, upstream = upstream, parent = parent, dest_branch = dest_branch, **extra_proj_attrs) for n in node.childNodes: if n.nodeName == 'copyfile': self._ParseCopyFile(project, n) if n.nodeName == 'linkfile': self._ParseLinkFile(project, n) if n.nodeName == 'annotation': self._ParseAnnotation(project, n) if n.nodeName == 'project': project.subprojects.append(self._ParseProject(n, parent = project)) return project def GetProjectPaths(self, name, path): relpath = path if self.IsMirror: worktree = None gitdir = os.path.join(self.topdir, '%s.git' % name) objdir = gitdir else: worktree = os.path.join(self.topdir, path).replace('\\', '/') gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path) objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name) return relpath, worktree, gitdir, objdir def GetProjectsWithName(self, name): return self._projects.get(name, []) def GetSubprojectName(self, parent, submodule_path): return os.path.join(parent.name, submodule_path) def _JoinRelpath(self, parent_relpath, relpath): return os.path.join(parent_relpath, relpath) def _UnjoinRelpath(self, parent_relpath, relpath): return os.path.relpath(relpath, parent_relpath) def GetSubprojectPaths(self, parent, name, path): relpath = self._JoinRelpath(parent.relpath, path) gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path) objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name) if self.IsMirror: worktree = None else: worktree = os.path.join(parent.worktree, path).replace('\\', '/') return relpath, worktree, gitdir, objdir def _ParseCopyFile(self, project, node): src = self._reqatt(node, 'src') dest = self._reqatt(node, 'dest') if not self.IsMirror: # src is project relative; # dest is relative to the top of the tree project.AddCopyFile(src, dest, os.path.join(self.topdir, dest)) def _ParseLinkFile(self, project, node): src = self._reqatt(node, 'src') dest = self._reqatt(node, 'dest') if not self.IsMirror: # src is project relative; # dest is relative to the top of the tree project.AddLinkFile(src, dest, os.path.join(self.topdir, dest)) def _ParseAnnotation(self, project, node): name = self._reqatt(node, 'name') value = self._reqatt(node, 'value') try: keep = self._reqatt(node, 'keep').lower() except ManifestParseError: keep = "true" if keep != "true" and keep != "false": raise ManifestParseError('optional "keep" attribute must be ' '"true" or "false"') project.AddAnnotation(name, value, keep) def _get_remote(self, node): name = node.getAttribute('remote') if not name: return None v = self._remotes.get(name) if not v: raise ManifestParseError("remote %s not defined in %s" % (name, self.manifestFile)) return v def _reqatt(self, node, attname): """ reads a required attribute from the node. """ v = node.getAttribute(attname) if not v: raise ManifestParseError("no %s in <%s> within %s" % (attname, node.nodeName, self.manifestFile)) return v def projectsDiff(self, manifest): """return the projects differences between two manifests. The diff will be from self to given manifest. """ fromProjects = self.paths toProjects = manifest.paths fromKeys = sorted(fromProjects.keys()) toKeys = sorted(toProjects.keys()) diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []} for proj in fromKeys: if not proj in toKeys: diff['removed'].append(fromProjects[proj]) else: fromProj = fromProjects[proj] toProj = toProjects[proj] try: fromRevId = fromProj.GetCommitRevisionId() toRevId = toProj.GetCommitRevisionId() except ManifestInvalidRevisionError: diff['unreachable'].append((fromProj, toProj)) else: if fromRevId != toRevId: diff['changed'].append((fromProj, toProj)) toKeys.remove(proj) for proj in toKeys: diff['added'].append(toProjects[proj]) return diff class GitcManifest(XmlManifest): def __init__(self, repodir, gitc_client_name): """Initialize the GitcManifest object.""" super(GitcManifest, self).__init__(repodir) self.isGitcClient = True self.gitc_client_name = gitc_client_name self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(), gitc_client_name) self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest') def _ParseProject(self, node, parent = None): """Override _ParseProject and add support for GITC specific attributes.""" return super(GitcManifest, self)._ParseProject( node, parent=parent, old_revision=node.getAttribute('old-revision')) def _output_manifest_project_extras(self, p, e): """Output GITC Specific Project attributes""" if p.old_revision: e.setAttribute('old-revision', str(p.old_revision))
apache-2.0
7,072,113,741,945,294,000
32.087359
94
0.616668
false
vene/AD3
examples/python/example_binary_multinomial.py
2
3386
import numpy as np from ad3 import simple_grid, general_graph def example_binary(plot=True): # generate trivial data x = np.ones((10, 10)) x[:, 5:] = -1 x_noisy = x + np.random.normal(0, 0.8, size=x.shape) x_thresh = x_noisy > .0 # create unaries unaries = x_noisy # as we convert to int, we need to multipy to get sensible values unaries = np.dstack([-unaries, unaries]) # create potts pairwise pairwise = np.eye(2) # do simple cut result = np.argmax(simple_grid(unaries, pairwise)[0], axis=-1) # use the general graph algorithm # first, we construct the grid graph inds = np.arange(x.size).reshape(x.shape) horz = np.c_[inds[:, :-1].ravel(), inds[:, 1:].ravel()] vert = np.c_[inds[:-1, :].ravel(), inds[1:, :].ravel()] edges = np.vstack([horz, vert]) # we flatten the unaries pairwise_per_edge = np.repeat(pairwise[np.newaxis, :, :], edges.shape[0], axis=0) result_graph = np.argmax(general_graph(unaries.reshape(-1, 2), edges, pairwise_per_edge)[0], axis=-1) # plot results if plot: import matplotlib.pyplot as plt plt.figure(figsize=(9, 8)) plt.suptitle("Binary distribution", size=20) plt.subplot(231, title="original") plt.imshow(x, interpolation='nearest') plt.subplot(232, title="noisy version") plt.imshow(x_noisy, interpolation='nearest') plt.subplot(234, title="thresholding result") plt.imshow(x_thresh, interpolation='nearest') plt.subplot(235, title="cut_simple") plt.imshow(result, interpolation='nearest') plt.subplot(236, title="cut_from_graph") plt.imshow(result_graph.reshape(x.shape), interpolation='nearest') plt.tight_layout() plt.show() else: print(result_graph) def example_multinomial(plot=True): # generate dataset with three stripes np.random.seed(4) x = np.zeros((10, 12, 3)) x[:, :4, 0] = 1 x[:, 4:8, 1] = 1 x[:, 8:, 2] = 1 unaries = x + 1.5 * np.random.normal(size=x.shape) x = np.argmax(x, axis=2) unaries = unaries x_thresh = np.argmax(unaries, axis=2) # potts potential pairwise_potts = 2 * np.eye(3) result = np.argmax(simple_grid(unaries, pairwise_potts)[0], axis=-1) # potential that penalizes 0-1 and 1-2 less than 0-2 pairwise_1d = 2 * np.eye(3) + 2 pairwise_1d[-1, 0] = 0 pairwise_1d[0, -1] = 0 result_1d = np.argmax(simple_grid(unaries, pairwise_1d)[0], axis=-1) if plot: import matplotlib.pyplot as plt plt.figure(figsize=(9, 3)) plt.suptitle("Multinomial distribution", size=20) plt.subplot(141, title="original") plt.imshow(x, interpolation="nearest") plt.subplot(142, title="thresholded unaries") plt.imshow(x_thresh, interpolation="nearest") plt.subplot(143, title="potts potentials") plt.imshow(result, interpolation="nearest") plt.subplot(144, title="1d topology potentials") plt.imshow(result_1d, interpolation="nearest") plt.tight_layout() plt.show() else: print(result_1d) if __name__ == '__main__': import os plot = False if os.environ.get('NOPLOT') else True example_binary(plot) example_multinomial(plot)
lgpl-3.0
271,750,891,009,953,440
32.524752
77
0.600118
false
asttra/pysces
pysces/lib/pyparsing.py
6
155429
# module pyparsing.py # # Copyright (c) 2003-2011 Paul T. McGuire # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # #from __future__ import generators __doc__ = \ """ pyparsing module - Classes and methods to define and execute parsing grammars The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you don't need to learn a new syntax for defining grammars or matching expressions - the parsing module provides a library of classes that you use to construct the grammar directly in Python. Here is a program to parse "Hello, World!" (or any greeting of the form C{"<salutation>, <addressee>!"}):: from pyparsing import Word, alphas # define grammar of a greeting greet = Word( alphas ) + "," + Word( alphas ) + "!" hello = "Hello, World!" print hello, "->", greet.parseString( hello ) The program outputs the following:: Hello, World! -> ['Hello', ',', 'World', '!'] The Python representation of the grammar is quite readable, owing to the self-explanatory class names, and the use of '+', '|' and '^' operators. The parsed results returned from C{parseString()} can be accessed as a nested list, a dictionary, or an object with named attributes. The pyparsing module handles some of the problems that are typically vexing when writing text parsers: - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.) - quoted strings - embedded comments """ __version__ = "1.5.6" __versionTime__ = "26 June 2011 10:53" __author__ = "Paul McGuire <[email protected]>" import string from weakref import ref as wkref import copy import sys import warnings import re import sre_constants #~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) ) __all__ = [ 'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty', 'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal', 'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or', 'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException', 'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException', 'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter', 'Upcase', 'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore', 'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col', 'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString', 'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'getTokensEndLoc', 'hexnums', 'htmlComment', 'javaStyleComment', 'keepOriginalText', 'line', 'lineEnd', 'lineStart', 'lineno', 'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral', 'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables', 'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity', 'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd', 'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute', 'indentedBlock', 'originalTextFor', ] """ Detect if we are running version 3.X and make appropriate changes Robert A. Clark """ _PY3K = sys.version_info[0] > 2 if _PY3K: _MAX_INT = sys.maxsize basestring = str unichr = chr _ustr = str alphas = string.ascii_lowercase + string.ascii_uppercase else: _MAX_INT = sys.maxint range = xrange set = lambda s : dict( [(c,0) for c in s] ) alphas = string.lowercase + string.uppercase def _ustr(obj): """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It then < returns the unicode object | encodes it with the default encoding | ... >. """ if isinstance(obj,unicode): return obj try: # If this works, then _ustr(obj) has the same behaviour as str(obj), so # it won't break any existing code. return str(obj) except UnicodeEncodeError: # The Python docs (http://docs.python.org/ref/customization.html#l2h-182) # state that "The return value must be a string object". However, does a # unicode object (being a subclass of basestring) count as a "string # object"? # If so, then return a unicode object: return unicode(obj) # Else encode it... but how? There are many choices... :) # Replace unprintables with escape codes? #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors') # Replace unprintables with question marks? #return unicode(obj).encode(sys.getdefaultencoding(), 'replace') # ... alphas = string.lowercase + string.uppercase # build list of single arg builtins, tolerant of Python version, that can be used as parse actions singleArgBuiltins = [] import __builtin__ for fname in "sum len enumerate sorted reversed list tuple set any all".split(): try: singleArgBuiltins.append(getattr(__builtin__,fname)) except AttributeError: continue def _xml_escape(data): """Escape &, <, >, ", ', etc. in a string of data.""" # ampersand must be replaced first from_symbols = '&><"\'' to_symbols = ['&'+s+';' for s in "amp gt lt quot apos".split()] for from_,to_ in zip(from_symbols, to_symbols): data = data.replace(from_, to_) return data class _Constants(object): pass nums = string.digits hexnums = nums + "ABCDEFabcdef" alphanums = alphas + nums _bslash = chr(92) printables = "".join( [ c for c in string.printable if c not in string.whitespace ] ) class ParseBaseException(Exception): """base exception class for all parsing runtime exceptions""" # Performance tuning: we construct a *lot* of these, so keep this # constructor as small and fast as possible def __init__( self, pstr, loc=0, msg=None, elem=None ): self.loc = loc if msg is None: self.msg = pstr self.pstr = "" else: self.msg = msg self.pstr = pstr self.parserElement = elem def __getattr__( self, aname ): """supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text """ if( aname == "lineno" ): return lineno( self.loc, self.pstr ) elif( aname in ("col", "column") ): return col( self.loc, self.pstr ) elif( aname == "line" ): return line( self.loc, self.pstr ) else: raise AttributeError(aname) def __str__( self ): return "%s (at char %d), (line:%d, col:%d)" % \ ( self.msg, self.loc, self.lineno, self.column ) def __repr__( self ): return _ustr(self) def markInputline( self, markerString = ">!<" ): """Extracts the exception line from the input string, and marks the location of the exception with a special symbol. """ line_str = self.line line_column = self.column - 1 if markerString: line_str = "".join( [line_str[:line_column], markerString, line_str[line_column:]]) return line_str.strip() def __dir__(self): return "loc msg pstr parserElement lineno col line " \ "markInputLine __str__ __repr__".split() class ParseException(ParseBaseException): """exception thrown when parse expressions don't match class; supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text """ pass class ParseFatalException(ParseBaseException): """user-throwable exception thrown when inconsistent parse content is found; stops all parsing immediately""" pass class ParseSyntaxException(ParseFatalException): """just like C{ParseFatalException}, but thrown internally when an C{ErrorStop} ('-' operator) indicates that parsing is to stop immediately because an unbacktrackable syntax error has been found""" def __init__(self, pe): super(ParseSyntaxException, self).__init__( pe.pstr, pe.loc, pe.msg, pe.parserElement) #~ class ReparseException(ParseBaseException): #~ """Experimental class - parse actions can raise this exception to cause #~ pyparsing to reparse the input string: #~ - with a modified input string, and/or #~ - with a modified start location #~ Set the values of the ReparseException in the constructor, and raise the #~ exception in a parse action to cause pyparsing to use the new string/location. #~ Setting the values as None causes no change to be made. #~ """ #~ def __init_( self, newstring, restartLoc ): #~ self.newParseText = newstring #~ self.reparseLoc = restartLoc class RecursiveGrammarException(Exception): """exception thrown by C{validate()} if the grammar could be improperly recursive""" def __init__( self, parseElementList ): self.parseElementTrace = parseElementList def __str__( self ): return "RecursiveGrammarException: %s" % self.parseElementTrace class _ParseResultsWithOffset(object): def __init__(self,p1,p2): self.tup = (p1,p2) def __getitem__(self,i): return self.tup[i] def __repr__(self): return repr(self.tup) def setOffset(self,i): self.tup = (self.tup[0],i) class ParseResults(object): """Structured parse results, to provide multiple means of access to the parsed data: - as a list (C{len(results)}) - by list index (C{results[0], results[1]}, etc.) - by attribute (C{results.<resultsName>}) """ #~ __slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__accumNames", "__weakref__" ) def __new__(cls, toklist, name=None, asList=True, modal=True ): if isinstance(toklist, cls): return toklist retobj = object.__new__(cls) retobj.__doinit = True return retobj # Performance tuning: we construct a *lot* of these, so keep this # constructor as small and fast as possible def __init__( self, toklist, name=None, asList=True, modal=True, isinstance=isinstance ): if self.__doinit: self.__doinit = False self.__name = None self.__parent = None self.__accumNames = {} if isinstance(toklist, list): self.__toklist = toklist[:] else: self.__toklist = [toklist] self.__tokdict = dict() if name is not None and name: if not modal: self.__accumNames[name] = 0 if isinstance(name,int): name = _ustr(name) # will always return a str, but use _ustr for consistency self.__name = name if not toklist in (None,'',[]): if isinstance(toklist,basestring): toklist = [ toklist ] if asList: if isinstance(toklist,ParseResults): self[name] = _ParseResultsWithOffset(toklist.copy(),0) else: self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),0) self[name].__name = name else: try: self[name] = toklist[0] except (KeyError,TypeError,IndexError): self[name] = toklist def __getitem__( self, i ): if isinstance( i, (int,slice) ): return self.__toklist[i] else: if i not in self.__accumNames: return self.__tokdict[i][-1][0] else: return ParseResults([ v[0] for v in self.__tokdict[i] ]) def __setitem__( self, k, v, isinstance=isinstance ): if isinstance(v,_ParseResultsWithOffset): self.__tokdict[k] = self.__tokdict.get(k,list()) + [v] sub = v[0] elif isinstance(k,int): self.__toklist[k] = v sub = v else: self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)] sub = v if isinstance(sub,ParseResults): sub.__parent = wkref(self) def __delitem__( self, i ): if isinstance(i,(int,slice)): mylen = len( self.__toklist ) del self.__toklist[i] # convert int to slice if isinstance(i, int): if i < 0: i += mylen i = slice(i, i+1) # get removed indices removed = list(range(*i.indices(mylen))) removed.reverse() # fixup indices in token dictionary for name in self.__tokdict: occurrences = self.__tokdict[name] for j in removed: for k, (value, position) in enumerate(occurrences): occurrences[k] = _ParseResultsWithOffset(value, position - (position > j)) else: del self.__tokdict[i] def __contains__( self, k ): return k in self.__tokdict def __len__( self ): return len( self.__toklist ) def __bool__(self): return len( self.__toklist ) > 0 __nonzero__ = __bool__ def __iter__( self ): return iter( self.__toklist ) def __reversed__( self ): return iter( self.__toklist[::-1] ) def keys( self ): """Returns all named result keys.""" return self.__tokdict.keys() def pop( self, index=-1 ): """Removes and returns item at specified index (default=last). Will work with either numeric indices or dict-key indicies.""" ret = self[index] del self[index] return ret def get(self, key, defaultValue=None): """Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified.""" if key in self: return self[key] else: return defaultValue def insert( self, index, insStr ): """Inserts new element at location index in the list of parsed tokens.""" self.__toklist.insert(index, insStr) # fixup indices in token dictionary for name in self.__tokdict: occurrences = self.__tokdict[name] for k, (value, position) in enumerate(occurrences): occurrences[k] = _ParseResultsWithOffset(value, position + (position > index)) def items( self ): """Returns all named result keys and values as a list of tuples.""" return [(k,self[k]) for k in self.__tokdict] def values( self ): """Returns all named result values.""" return [ v[-1][0] for v in self.__tokdict.values() ] def __getattr__( self, name ): if True: #name not in self.__slots__: if name in self.__tokdict: if name not in self.__accumNames: return self.__tokdict[name][-1][0] else: return ParseResults([ v[0] for v in self.__tokdict[name] ]) else: return "" return None def __add__( self, other ): ret = self.copy() ret += other return ret def __iadd__( self, other ): if other.__tokdict: offset = len(self.__toklist) addoffset = ( lambda a: (a<0 and offset) or (a+offset) ) otheritems = other.__tokdict.items() otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) ) for (k,vlist) in otheritems for v in vlist] for k,v in otherdictitems: self[k] = v if isinstance(v[0],ParseResults): v[0].__parent = wkref(self) self.__toklist += other.__toklist self.__accumNames.update( other.__accumNames ) return self def __radd__(self, other): if isinstance(other,int) and other == 0: return self.copy() def __repr__( self ): return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) ) def __str__( self ): out = "[" sep = "" for i in self.__toklist: if isinstance(i, ParseResults): out += sep + _ustr(i) else: out += sep + repr(i) sep = ", " out += "]" return out def _asStringList( self, sep='' ): out = [] for item in self.__toklist: if out and sep: out.append(sep) if isinstance( item, ParseResults ): out += item._asStringList() else: out.append( _ustr(item) ) return out def asList( self ): """Returns the parse results as a nested list of matching tokens, all converted to strings.""" out = [] for res in self.__toklist: if isinstance(res,ParseResults): out.append( res.asList() ) else: out.append( res ) return out def asDict( self ): """Returns the named parse results as dictionary.""" return dict( self.items() ) def copy( self ): """Returns a new copy of a C{ParseResults} object.""" ret = ParseResults( self.__toklist ) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update( self.__accumNames ) ret.__name = self.__name return ret def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ): """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.""" nl = "\n" out = [] namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items() for v in vlist ] ) nextLevelIndent = indent + " " # collapse out indents if formatting is not desired if not formatted: indent = "" nextLevelIndent = "" nl = "" selfTag = None if doctag is not None: selfTag = doctag else: if self.__name: selfTag = self.__name if not selfTag: if namedItemsOnly: return "" else: selfTag = "ITEM" out += [ nl, indent, "<", selfTag, ">" ] worklist = self.__toklist for i,res in enumerate(worklist): if isinstance(res,ParseResults): if i in namedItems: out += [ res.asXML(namedItems[i], namedItemsOnly and doctag is None, nextLevelIndent, formatted)] else: out += [ res.asXML(None, namedItemsOnly and doctag is None, nextLevelIndent, formatted)] else: # individual token, see if there is a name for it resTag = None if i in namedItems: resTag = namedItems[i] if not resTag: if namedItemsOnly: continue else: resTag = "ITEM" xmlBodyText = _xml_escape(_ustr(res)) out += [ nl, nextLevelIndent, "<", resTag, ">", xmlBodyText, "</", resTag, ">" ] out += [ nl, indent, "</", selfTag, ">" ] return "".join(out) def __lookup(self,sub): for k,vlist in self.__tokdict.items(): for v,loc in vlist: if sub is v: return k return None def getName(self): """Returns the results name for this token expression.""" if self.__name: return self.__name elif self.__parent: par = self.__parent() if par: return par.__lookup(self) else: return None elif (len(self) == 1 and len(self.__tokdict) == 1 and self.__tokdict.values()[0][0][1] in (0,-1)): return self.__tokdict.keys()[0] else: return None def dump(self,indent='',depth=0): """Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data.""" out = [] out.append( indent+_ustr(self.asList()) ) keys = self.items() keys.sort() for k,v in keys: if out: out.append('\n') out.append( "%s%s- %s: " % (indent,(' '*depth), k) ) if isinstance(v,ParseResults): if v.keys(): out.append( v.dump(indent,depth+1) ) else: out.append(_ustr(v)) else: out.append(_ustr(v)) return "".join(out) # add support for pickle protocol def __getstate__(self): return ( self.__toklist, ( self.__tokdict.copy(), self.__parent is not None and self.__parent() or None, self.__accumNames, self.__name ) ) def __setstate__(self,state): self.__toklist = state[0] (self.__tokdict, par, inAccumNames, self.__name) = state[1] self.__accumNames = {} self.__accumNames.update(inAccumNames) if par is not None: self.__parent = wkref(par) else: self.__parent = None def __dir__(self): return dir(super(ParseResults,self)) + self.keys() def col (loc,strg): """Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing <TAB>s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. """ return (loc<len(strg) and strg[loc] == '\n') and 1 or loc - strg.rfind("\n", 0, loc) def lineno(loc,strg): """Returns current line number within a string, counting newlines as line separators. The first line is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing <TAB>s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. """ return strg.count("\n",0,loc) + 1 def line( loc, strg ): """Returns the line of text containing loc within a string, counting newlines as line separators. """ lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR+1:nextCR] else: return strg[lastCR+1:] def _defaultStartDebugAction( instring, loc, expr ): print ("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )) def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ): print ("Matched " + _ustr(expr) + " -> " + str(toks.asList())) def _defaultExceptionDebugAction( instring, loc, expr, exc ): print ("Exception raised:" + _ustr(exc)) def nullDebugAction(*args): """'Do-nothing' debug action, to suppress debugging output during parsing.""" pass 'decorator to trim function calls to match the arity of the target' if not _PY3K: def _trim_arity(func, maxargs=2): limit = [0] def wrapper(*args): while 1: try: return func(*args[limit[0]:]) except TypeError: if limit[0] <= maxargs: limit[0] += 1 continue raise return wrapper else: def _trim_arity(func, maxargs=2): limit = maxargs def wrapper(*args): #~ nonlocal limit while 1: try: return func(*args[limit:]) except TypeError: if limit: limit -= 1 continue raise return wrapper class ParserElement(object): """Abstract base level parser element class.""" DEFAULT_WHITE_CHARS = " \n\t\r" verbose_stacktrace = False def setDefaultWhitespaceChars( chars ): """Overrides the default whitespace chars """ ParserElement.DEFAULT_WHITE_CHARS = chars setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars) def __init__( self, savelist=False ): self.parseAction = list() self.failAction = None #~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall self.strRepr = None self.resultsName = None self.saveAsList = savelist self.skipWhitespace = True self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS self.copyDefaultWhiteChars = True self.mayReturnEmpty = False # used when checking for left-recursion self.keepTabs = False self.ignoreExprs = list() self.debug = False self.streamlined = False self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index self.errmsg = "" self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all) self.debugActions = ( None, None, None ) #custom debug actions self.re = None self.callPreparse = True # used to avoid redundant calls to preParse self.callDuringTry = False def copy( self ): """Make a copy of this C{ParserElement}. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element.""" cpy = copy.copy( self ) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] if self.copyDefaultWhiteChars: cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS return cpy def setName( self, name ): """Define name for this expression, for use in debugging.""" self.name = name self.errmsg = "Expected " + self.name if hasattr(self,"exception"): self.exception.msg = self.errmsg return self def setResultsName( self, name, listAllMatches=False ): """Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. """ newself = self.copy() if name.endswith("*"): name = name[:-1] listAllMatches=True newself.resultsName = name newself.modalResults = not listAllMatches return newself def setBreak(self,breakFlag = True): """Method to invoke the Python pdb debugger when this element is about to be parsed. Set C{breakFlag} to True to enable, False to disable. """ if breakFlag: _parseMethod = self._parse def breaker(instring, loc, doActions=True, callPreParse=True): import pdb pdb.set_trace() return _parseMethod( instring, loc, doActions, callPreParse ) breaker._originalParseMethod = _parseMethod self._parse = breaker else: if hasattr(self._parse,"_originalParseMethod"): self._parse = self._parse._originalParseMethod return self def setParseAction( self, *fns, **kwargs ): """Define action to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a ParseResults object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing <TAB>s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. """ self.parseAction = list(map(_trim_arity, list(fns))) self.callDuringTry = ("callDuringTry" in kwargs and kwargs["callDuringTry"]) return self def addParseAction( self, *fns, **kwargs ): """Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.""" self.parseAction += list(map(_trim_arity, list(fns))) self.callDuringTry = self.callDuringTry or ("callDuringTry" in kwargs and kwargs["callDuringTry"]) return self def setFailAction( self, fn ): """Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments C{fn(s,loc,expr,err)} where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw C{ParseFatalException} if it is desired to stop parsing immediately.""" self.failAction = fn return self def _skipIgnorables( self, instring, loc ): exprsFound = True while exprsFound: exprsFound = False for e in self.ignoreExprs: try: while 1: loc,dummy = e._parse( instring, loc ) exprsFound = True except ParseException: pass return loc def preParse( self, instring, loc ): if self.ignoreExprs: loc = self._skipIgnorables( instring, loc ) if self.skipWhitespace: wt = self.whiteChars instrlen = len(instring) while loc < instrlen and instring[loc] in wt: loc += 1 return loc def parseImpl( self, instring, loc, doActions=True ): return loc, [] def postParse( self, instring, loc, tokenlist ): return tokenlist #~ @profile def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ): debugging = ( self.debug ) #and doActions ) if debugging or self.failAction: #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )) if (self.debugActions[0] ): self.debugActions[0]( instring, loc, self ) if callPreParse and self.callPreparse: preloc = self.preParse( instring, loc ) else: preloc = loc tokensStart = preloc try: try: loc,tokens = self.parseImpl( instring, preloc, doActions ) except IndexError: raise ParseException( instring, len(instring), self.errmsg, self ) except ParseBaseException: #~ print ("Exception raised:", err) err = None if self.debugActions[2]: err = sys.exc_info()[1] self.debugActions[2]( instring, tokensStart, self, err ) if self.failAction: if err is None: err = sys.exc_info()[1] self.failAction( instring, tokensStart, self, err ) raise else: if callPreParse and self.callPreparse: preloc = self.preParse( instring, loc ) else: preloc = loc tokensStart = preloc if self.mayIndexError or loc >= len(instring): try: loc,tokens = self.parseImpl( instring, preloc, doActions ) except IndexError: raise ParseException( instring, len(instring), self.errmsg, self ) else: loc,tokens = self.parseImpl( instring, preloc, doActions ) tokens = self.postParse( instring, loc, tokens ) retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults ) if self.parseAction and (doActions or self.callDuringTry): if debugging: try: for fn in self.parseAction: tokens = fn( instring, tokensStart, retTokens ) if tokens is not None: retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), modal=self.modalResults ) except ParseBaseException: #~ print "Exception raised in user parse action:", err if (self.debugActions[2] ): err = sys.exc_info()[1] self.debugActions[2]( instring, tokensStart, self, err ) raise else: for fn in self.parseAction: tokens = fn( instring, tokensStart, retTokens ) if tokens is not None: retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), modal=self.modalResults ) if debugging: #~ print ("Matched",self,"->",retTokens.asList()) if (self.debugActions[1] ): self.debugActions[1]( instring, tokensStart, loc, self, retTokens ) return loc, retTokens def tryParse( self, instring, loc ): try: return self._parse( instring, loc, doActions=False )[0] except ParseFatalException: raise ParseException( instring, loc, self.errmsg, self) # this method gets repeatedly called during backtracking with the same arguments - # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression def _parseCache( self, instring, loc, doActions=True, callPreParse=True ): lookup = (self,instring,loc,callPreParse,doActions) if lookup in ParserElement._exprArgCache: value = ParserElement._exprArgCache[ lookup ] if isinstance(value, Exception): raise value return (value[0],value[1].copy()) else: try: value = self._parseNoCache( instring, loc, doActions, callPreParse ) ParserElement._exprArgCache[ lookup ] = (value[0],value[1].copy()) return value except ParseBaseException: pe = sys.exc_info()[1] ParserElement._exprArgCache[ lookup ] = pe raise _parse = _parseNoCache # argument cache for optimizing repeated calls when backtracking through recursive expressions _exprArgCache = {} def resetCache(): ParserElement._exprArgCache.clear() resetCache = staticmethod(resetCache) _packratEnabled = False def enablePackrat(): """Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method C{ParserElement.enablePackrat()}. If your program uses C{psyco} to "compile as you go", you must call C{enablePackrat} before calling C{psyco.full()}. If you do not do this, Python will crash. For best results, call C{enablePackrat()} immediately after importing pyparsing. """ if not ParserElement._packratEnabled: ParserElement._packratEnabled = True ParserElement._parse = ParserElement._parseCache enablePackrat = staticmethod(enablePackrat) def parseString( self, instring, parseAll=False ): """Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. If you want the grammar to require that the entire input string be successfully parsed, then set C{parseAll} to True (equivalent to ending the grammar with C{StringEnd()}). Note: C{parseString} implicitly calls C{expandtabs()} on the input string, in order to report proper column numbers in parse actions. If the input string contains tabs and the grammar uses parse actions that use the C{loc} argument to index into the string being parsed, you can ensure you have a consistent view of the input string by: - calling C{parseWithTabs} on your grammar before calling C{parseString} (see L{I{parseWithTabs}<parseWithTabs>}) - define your parse action using the full C{(s,loc,toks)} signature, and reference the input string using the parse action's C{s} argument - explictly expand the tabs in your input string before calling C{parseString} """ ParserElement.resetCache() if not self.streamlined: self.streamline() #~ self.saveAsList = True for e in self.ignoreExprs: e.streamline() if not self.keepTabs: instring = instring.expandtabs() try: loc, tokens = self._parse( instring, 0 ) if parseAll: loc = self.preParse( instring, loc ) se = Empty() + StringEnd() se._parse( instring, loc ) except ParseBaseException: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace exc = sys.exc_info()[1] raise exc else: return tokens def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ): """Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional C{maxMatches} argument, to clip scanning after 'n' matches are found. If C{overlap} is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See L{I{parseString}<parseString>} for more information on parsing strings with embedded tabs.""" if not self.streamlined: self.streamline() for e in self.ignoreExprs: e.streamline() if not self.keepTabs: instring = _ustr(instring).expandtabs() instrlen = len(instring) loc = 0 preparseFn = self.preParse parseFn = self._parse ParserElement.resetCache() matches = 0 try: while loc <= instrlen and matches < maxMatches: try: preloc = preparseFn( instring, loc ) nextLoc,tokens = parseFn( instring, preloc, callPreParse=False ) except ParseException: loc = preloc+1 else: if nextLoc > loc: matches += 1 yield tokens, preloc, nextLoc if overlap: nextloc = preparseFn( instring, loc ) if nextloc > loc: loc = nextLoc else: loc += 1 else: loc = nextLoc else: loc = preloc+1 except ParseBaseException: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace exc = sys.exc_info()[1] raise exc def transformString( self, instring ): """Extension to C{scanString}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string.""" out = [] lastE = 0 # force preservation of <TAB>s, to minimize unwanted transformation of string, and to # keep string locs straight between transformString and scanString self.keepTabs = True try: for t,s,e in self.scanString( instring ): out.append( instring[lastE:s] ) if t: if isinstance(t,ParseResults): out += t.asList() elif isinstance(t,list): out += t else: out.append(t) lastE = e out.append(instring[lastE:]) out = [o for o in out if o] return "".join(map(_ustr,_flatten(out))) except ParseBaseException: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace exc = sys.exc_info()[1] raise exc def searchString( self, instring, maxMatches=_MAX_INT ): """Another extension to C{scanString}, simplifying the access to the tokens found to match the given parse expression. May be called with optional C{maxMatches} argument, to clip searching after 'n' matches are found. """ try: return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ]) except ParseBaseException: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace exc = sys.exc_info()[1] raise exc def __add__(self, other ): """Implementation of + operator - returns And""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return And( [ self, other ] ) def __radd__(self, other ): """Implementation of + operator when left operand is not a C{ParserElement}""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other + self def __sub__(self, other): """Implementation of - operator, returns C{And} with error stop""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return And( [ self, And._ErrorStop(), other ] ) def __rsub__(self, other ): """Implementation of - operator when left operand is not a C{ParserElement}""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other - self def __mul__(self,other): """Implementation of * operator, allows use of C{expr * 3} in place of C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples may also include C{None} as in: - C{expr*(n,None)} or C{expr*(n,)} is equivalent to C{expr*n + ZeroOrMore(expr)} (read as "at least n instances of C{expr}") - C{expr*(None,n)} is equivalent to C{expr*(0,n)} (read as "0 to n instances of C{expr}") - C{expr*(None,None)} is equivalent to C{ZeroOrMore(expr)} - C{expr*(1,None)} is equivalent to C{OneOrMore(expr)} Note that C{expr*(None,n)} does not raise an exception if more than n exprs exist in the input stream; that is, C{expr*(None,n)} does not enforce a maximum number of expr occurrences. If this behavior is desired, then write C{expr*(None,n) + ~expr} """ if isinstance(other,int): minElements, optElements = other,0 elif isinstance(other,tuple): other = (other + (None, None))[:2] if other[0] is None: other = (0, other[1]) if isinstance(other[0],int) and other[1] is None: if other[0] == 0: return ZeroOrMore(self) if other[0] == 1: return OneOrMore(self) else: return self*other[0] + ZeroOrMore(self) elif isinstance(other[0],int) and isinstance(other[1],int): minElements, optElements = other optElements -= minElements else: raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1])) else: raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other)) if minElements < 0: raise ValueError("cannot multiply ParserElement by negative value") if optElements < 0: raise ValueError("second tuple value must be greater or equal to first tuple value") if minElements == optElements == 0: raise ValueError("cannot multiply ParserElement by 0 or (0,0)") if (optElements): def makeOptionalList(n): if n>1: return Optional(self + makeOptionalList(n-1)) else: return Optional(self) if minElements: if minElements == 1: ret = self + makeOptionalList(optElements) else: ret = And([self]*minElements) + makeOptionalList(optElements) else: ret = makeOptionalList(optElements) else: if minElements == 1: ret = self else: ret = And([self]*minElements) return ret def __rmul__(self, other): return self.__mul__(other) def __or__(self, other ): """Implementation of | operator - returns C{MatchFirst}""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return MatchFirst( [ self, other ] ) def __ror__(self, other ): """Implementation of | operator when left operand is not a C{ParserElement}""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other | self def __xor__(self, other ): """Implementation of ^ operator - returns C{Or}""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return Or( [ self, other ] ) def __rxor__(self, other ): """Implementation of ^ operator when left operand is not a C{ParserElement}""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other ^ self def __and__(self, other ): """Implementation of & operator - returns C{Each}""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return Each( [ self, other ] ) def __rand__(self, other ): """Implementation of & operator when left operand is not a C{ParserElement}""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other & self def __invert__( self ): """Implementation of ~ operator - returns C{NotAny}""" return NotAny( self ) def __call__(self, name): """Shortcut for C{setResultsName}, with C{listAllMatches=default}:: userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") could be written as:: userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. """ return self.setResultsName(name) def suppress( self ): """Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output. """ return Suppress( self ) def leaveWhitespace( self ): """Disables the skipping of whitespace before matching the characters in the C{ParserElement}'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars. """ self.skipWhitespace = False return self def setWhitespaceChars( self, chars ): """Overrides the default whitespace chars """ self.skipWhitespace = True self.whiteChars = chars self.copyDefaultWhiteChars = False return self def parseWithTabs( self ): """Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string. Must be called before C{parseString} when the input grammar contains elements that match C{<TAB>} characters.""" self.keepTabs = True return self def ignore( self, other ): """Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. """ if isinstance( other, Suppress ): if other not in self.ignoreExprs: self.ignoreExprs.append( other.copy() ) else: self.ignoreExprs.append( Suppress( other.copy() ) ) return self def setDebugActions( self, startAction, successAction, exceptionAction ): """Enable display of debugging messages while doing pattern matching.""" self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction) self.debug = True return self def setDebug( self, flag=True ): """Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable.""" if flag: self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction ) else: self.debug = False return self def __str__( self ): return self.name def __repr__( self ): return _ustr(self) def streamline( self ): self.streamlined = True self.strRepr = None return self def checkRecursion( self, parseElementList ): pass def validate( self, validateTrace=[] ): """Check defined expressions for valid structure, check for infinite recursive definitions.""" self.checkRecursion( [] ) def parseFile( self, file_or_filename, parseAll=False ): """Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing. """ try: file_contents = file_or_filename.read() except AttributeError: f = open(file_or_filename, "rb") file_contents = f.read() f.close() try: return self.parseString(file_contents, parseAll) except ParseBaseException: # catch and re-raise exception from here, clears out pyparsing internal stack trace exc = sys.exc_info()[1] raise exc def getException(self): return ParseException("",0,self.errmsg,self) def __getattr__(self,aname): if aname == "myException": self.myException = ret = self.getException(); return ret; else: raise AttributeError("no such attribute " + aname) def __eq__(self,other): if isinstance(other, ParserElement): return self is other or self.__dict__ == other.__dict__ elif isinstance(other, basestring): try: self.parseString(_ustr(other), parseAll=True) return True except ParseBaseException: return False else: return super(ParserElement,self)==other def __ne__(self,other): return not (self == other) def __hash__(self): return hash(id(self)) def __req__(self,other): return self == other def __rne__(self,other): return not (self == other) class Token(ParserElement): """Abstract C{ParserElement} subclass, for defining atomic matching patterns.""" def __init__( self ): super(Token,self).__init__( savelist=False ) def setName(self, name): s = super(Token,self).setName(name) self.errmsg = "Expected " + self.name return s class Empty(Token): """An empty token, will always match.""" def __init__( self ): super(Empty,self).__init__() self.name = "Empty" self.mayReturnEmpty = True self.mayIndexError = False class NoMatch(Token): """A token that will never match.""" def __init__( self ): super(NoMatch,self).__init__() self.name = "NoMatch" self.mayReturnEmpty = True self.mayIndexError = False self.errmsg = "Unmatchable token" def parseImpl( self, instring, loc, doActions=True ): exc = self.myException exc.loc = loc exc.pstr = instring raise exc class Literal(Token): """Token to exactly match a specified string.""" def __init__( self, matchString ): super(Literal,self).__init__() self.match = matchString self.matchLen = len(matchString) try: self.firstMatchChar = matchString[0] except IndexError: warnings.warn("null string passed to Literal; use Empty() instead", SyntaxWarning, stacklevel=2) self.__class__ = Empty self.name = '"%s"' % _ustr(self.match) self.errmsg = "Expected " + self.name self.mayReturnEmpty = False self.mayIndexError = False # Performance tuning: this routine gets called a *lot* # if this is a single character match string and the first character matches, # short-circuit as quickly as possible, and avoid calling startswith #~ @profile def parseImpl( self, instring, loc, doActions=True ): if (instring[loc] == self.firstMatchChar and (self.matchLen==1 or instring.startswith(self.match,loc)) ): return loc+self.matchLen, self.match #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc _L = Literal class Keyword(Token): """Token to exactly match a specified string as a keyword, that is, it must be immediately followed by a non-keyword character. Compare with C{Literal}:: Literal("if") will match the leading C{'if'} in C{'ifAndOnlyIf'}. Keyword("if") will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'} Accepts two optional constructor arguments in addition to the keyword string: C{identChars} is a string of characters that would be valid identifier characters, defaulting to all alphanumerics + "_" and "$"; C{caseless} allows case-insensitive matching, default is C{False}. """ DEFAULT_KEYWORD_CHARS = alphanums+"_$" def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ): super(Keyword,self).__init__() self.match = matchString self.matchLen = len(matchString) try: self.firstMatchChar = matchString[0] except IndexError: warnings.warn("null string passed to Keyword; use Empty() instead", SyntaxWarning, stacklevel=2) self.name = '"%s"' % self.match self.errmsg = "Expected " + self.name self.mayReturnEmpty = False self.mayIndexError = False self.caseless = caseless if caseless: self.caselessmatch = matchString.upper() identChars = identChars.upper() self.identChars = set(identChars) def parseImpl( self, instring, loc, doActions=True ): if self.caseless: if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and (loc == 0 or instring[loc-1].upper() not in self.identChars) ): return loc+self.matchLen, self.match else: if (instring[loc] == self.firstMatchChar and (self.matchLen==1 or instring.startswith(self.match,loc)) and (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and (loc == 0 or instring[loc-1] not in self.identChars) ): return loc+self.matchLen, self.match #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc def copy(self): c = super(Keyword,self).copy() c.identChars = Keyword.DEFAULT_KEYWORD_CHARS return c def setDefaultKeywordChars( chars ): """Overrides the default Keyword chars """ Keyword.DEFAULT_KEYWORD_CHARS = chars setDefaultKeywordChars = staticmethod(setDefaultKeywordChars) class CaselessLiteral(Literal): """Token to match a specified string, ignoring case of letters. Note: the matched results will always be in the case of the given match string, NOT the case of the input text. """ def __init__( self, matchString ): super(CaselessLiteral,self).__init__( matchString.upper() ) # Preserve the defining literal. self.returnString = matchString self.name = "'%s'" % self.returnString self.errmsg = "Expected " + self.name def parseImpl( self, instring, loc, doActions=True ): if instring[ loc:loc+self.matchLen ].upper() == self.match: return loc+self.matchLen, self.returnString #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc class CaselessKeyword(Keyword): def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ): super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True ) def parseImpl( self, instring, loc, doActions=True ): if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ): return loc+self.matchLen, self.match #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc class Word(Token): """Token for matching words composed of allowed character sets. Defined with string containing all allowed initial characters, an optional string containing allowed body characters (if omitted, defaults to the initial character set), and an optional minimum, maximum, and/or exact length. The default value for C{min} is 1 (a minimum value < 1 is not valid); the default values for C{max} and C{exact} are 0, meaning no maximum or exact length restriction. An optional C{exclude} parameter can list characters that might be found in the input C{bodyChars} string; useful to define a word of all printables except for one or two characters, for instance. """ def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None ): super(Word,self).__init__() if excludeChars: initChars = ''.join([c for c in initChars if c not in excludeChars]) if bodyChars: bodyChars = ''.join([c for c in bodyChars if c not in excludeChars]) self.initCharsOrig = initChars self.initChars = set(initChars) if bodyChars : self.bodyCharsOrig = bodyChars self.bodyChars = set(bodyChars) else: self.bodyCharsOrig = initChars self.bodyChars = set(initChars) self.maxSpecified = max > 0 if min < 1: raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted") self.minLen = min if max > 0: self.maxLen = max else: self.maxLen = _MAX_INT if exact > 0: self.maxLen = exact self.minLen = exact self.name = _ustr(self) self.errmsg = "Expected " + self.name self.mayIndexError = False self.asKeyword = asKeyword if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0): if self.bodyCharsOrig == self.initCharsOrig: self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig) elif len(self.bodyCharsOrig) == 1: self.reString = "%s[%s]*" % \ (re.escape(self.initCharsOrig), _escapeRegexRangeChars(self.bodyCharsOrig),) else: self.reString = "[%s][%s]*" % \ (_escapeRegexRangeChars(self.initCharsOrig), _escapeRegexRangeChars(self.bodyCharsOrig),) if self.asKeyword: self.reString = r"\b"+self.reString+r"\b" try: self.re = re.compile( self.reString ) except: self.re = None def parseImpl( self, instring, loc, doActions=True ): if self.re: result = self.re.match(instring,loc) if not result: exc = self.myException exc.loc = loc exc.pstr = instring raise exc loc = result.end() return loc, result.group() if not(instring[ loc ] in self.initChars): #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc start = loc loc += 1 instrlen = len(instring) bodychars = self.bodyChars maxloc = start + self.maxLen maxloc = min( maxloc, instrlen ) while loc < maxloc and instring[loc] in bodychars: loc += 1 throwException = False if loc - start < self.minLen: throwException = True if self.maxSpecified and loc < instrlen and instring[loc] in bodychars: throwException = True if self.asKeyword: if (start>0 and instring[start-1] in bodychars) or (loc<instrlen and instring[loc] in bodychars): throwException = True if throwException: #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, instring[start:loc] def __str__( self ): try: return super(Word,self).__str__() except: pass if self.strRepr is None: def charsAsStr(s): if len(s)>4: return s[:4]+"..." else: return s if ( self.initCharsOrig != self.bodyCharsOrig ): self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) ) else: self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig) return self.strRepr class Regex(Token): """Token for matching strings that match a given regular expression. Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module. """ compiledREtype = type(re.compile("[A-Z]")) def __init__( self, pattern, flags=0): """The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags.""" super(Regex,self).__init__() if isinstance(pattern, basestring): if len(pattern) == 0: warnings.warn("null string passed to Regex; use Empty() instead", SyntaxWarning, stacklevel=2) self.pattern = pattern self.flags = flags try: self.re = re.compile(self.pattern, self.flags) self.reString = self.pattern except sre_constants.error: warnings.warn("invalid pattern (%s) passed to Regex" % pattern, SyntaxWarning, stacklevel=2) raise elif isinstance(pattern, Regex.compiledREtype): self.re = pattern self.pattern = \ self.reString = str(pattern) self.flags = flags else: raise ValueError("Regex may only be constructed with a string or a compiled RE object") self.name = _ustr(self) self.errmsg = "Expected " + self.name self.mayIndexError = False self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): result = self.re.match(instring,loc) if not result: exc = self.myException exc.loc = loc exc.pstr = instring raise exc loc = result.end() d = result.groupdict() ret = ParseResults(result.group()) if d: for k in d: ret[k] = d[k] return loc,ret def __str__( self ): try: return super(Regex,self).__str__() except: pass if self.strRepr is None: self.strRepr = "Re:(%s)" % repr(self.pattern) return self.strRepr class QuotedString(Token): """Token for matching strings that are delimited by quoting characters. """ def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None): """ Defined with the following parameters: - quoteChar - string of one or more characters defining the quote delimiting string - escChar - character to escape quotes, typically backslash (default=None) - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None) - multiline - boolean indicating whether quotes can span multiple lines (default=False) - unquoteResults - boolean indicating whether the matched text should be unquoted (default=True) - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar) """ super(QuotedString,self).__init__() # remove white space from quote chars - wont work anyway quoteChar = quoteChar.strip() if len(quoteChar) == 0: warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2) raise SyntaxError() if endQuoteChar is None: endQuoteChar = quoteChar else: endQuoteChar = endQuoteChar.strip() if len(endQuoteChar) == 0: warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2) raise SyntaxError() self.quoteChar = quoteChar self.quoteCharLen = len(quoteChar) self.firstQuoteChar = quoteChar[0] self.endQuoteChar = endQuoteChar self.endQuoteCharLen = len(endQuoteChar) self.escChar = escChar self.escQuote = escQuote self.unquoteResults = unquoteResults if multiline: self.flags = re.MULTILINE | re.DOTALL self.pattern = r'%s(?:[^%s%s]' % \ ( re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), (escChar is not None and _escapeRegexRangeChars(escChar) or '') ) else: self.flags = 0 self.pattern = r'%s(?:[^%s\n\r%s]' % \ ( re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), (escChar is not None and _escapeRegexRangeChars(escChar) or '') ) if len(self.endQuoteChar) > 1: self.pattern += ( '|(?:' + ')|(?:'.join(["%s[^%s]" % (re.escape(self.endQuoteChar[:i]), _escapeRegexRangeChars(self.endQuoteChar[i])) for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')' ) if escQuote: self.pattern += (r'|(?:%s)' % re.escape(escQuote)) if escChar: self.pattern += (r'|(?:%s.)' % re.escape(escChar)) charset = ''.join(set(self.quoteChar[0]+self.endQuoteChar[0])).replace('^',r'\^').replace('-',r'\-') self.escCharReplacePattern = re.escape(self.escChar)+("([%s])" % charset) self.pattern += (r')*%s' % re.escape(self.endQuoteChar)) try: self.re = re.compile(self.pattern, self.flags) self.reString = self.pattern except sre_constants.error: warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern, SyntaxWarning, stacklevel=2) raise self.name = _ustr(self) self.errmsg = "Expected " + self.name self.mayIndexError = False self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None if not result: exc = self.myException exc.loc = loc exc.pstr = instring raise exc loc = result.end() ret = result.group() if self.unquoteResults: # strip off quotes ret = ret[self.quoteCharLen:-self.endQuoteCharLen] if isinstance(ret,basestring): # replace escaped characters if self.escChar: ret = re.sub(self.escCharReplacePattern,"\g<1>",ret) # replace escaped quotes if self.escQuote: ret = ret.replace(self.escQuote, self.endQuoteChar) return loc, ret def __str__( self ): try: return super(QuotedString,self).__str__() except: pass if self.strRepr is None: self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar) return self.strRepr class CharsNotIn(Token): """Token for matching words composed of characters *not* in a given set. Defined with string containing all disallowed characters, and an optional minimum, maximum, and/or exact length. The default value for C{min} is 1 (a minimum value < 1 is not valid); the default values for C{max} and C{exact} are 0, meaning no maximum or exact length restriction. """ def __init__( self, notChars, min=1, max=0, exact=0 ): super(CharsNotIn,self).__init__() self.skipWhitespace = False self.notChars = notChars if min < 1: raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted") self.minLen = min if max > 0: self.maxLen = max else: self.maxLen = _MAX_INT if exact > 0: self.maxLen = exact self.minLen = exact self.name = _ustr(self) self.errmsg = "Expected " + self.name self.mayReturnEmpty = ( self.minLen == 0 ) self.mayIndexError = False def parseImpl( self, instring, loc, doActions=True ): if instring[loc] in self.notChars: #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc start = loc loc += 1 notchars = self.notChars maxlen = min( start+self.maxLen, len(instring) ) while loc < maxlen and \ (instring[loc] not in notchars): loc += 1 if loc - start < self.minLen: #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, instring[start:loc] def __str__( self ): try: return super(CharsNotIn, self).__str__() except: pass if self.strRepr is None: if len(self.notChars) > 4: self.strRepr = "!W:(%s...)" % self.notChars[:4] else: self.strRepr = "!W:(%s)" % self.notChars return self.strRepr class White(Token): """Special matching class for matching whitespace. Normally, whitespace is ignored by pyparsing grammars. This class is included when some whitespace structures are significant. Define with a string containing the whitespace characters to be matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments, as defined for the C{Word} class.""" whiteStrs = { " " : "<SPC>", "\t": "<TAB>", "\n": "<LF>", "\r": "<CR>", "\f": "<FF>", } def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0): super(White,self).__init__() self.matchWhite = ws self.setWhitespaceChars( "".join([c for c in self.whiteChars if c not in self.matchWhite]) ) #~ self.leaveWhitespace() self.name = ("".join([White.whiteStrs[c] for c in self.matchWhite])) self.mayReturnEmpty = True self.errmsg = "Expected " + self.name self.minLen = min if max > 0: self.maxLen = max else: self.maxLen = _MAX_INT if exact > 0: self.maxLen = exact self.minLen = exact def parseImpl( self, instring, loc, doActions=True ): if not(instring[ loc ] in self.matchWhite): #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc start = loc loc += 1 maxloc = start + self.maxLen maxloc = min( maxloc, len(instring) ) while loc < maxloc and instring[loc] in self.matchWhite: loc += 1 if loc - start < self.minLen: #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, instring[start:loc] class _PositionToken(Token): def __init__( self ): super(_PositionToken,self).__init__() self.name=self.__class__.__name__ self.mayReturnEmpty = True self.mayIndexError = False class GoToColumn(_PositionToken): """Token to advance to a specific column of input text; useful for tabular report scraping.""" def __init__( self, colno ): super(GoToColumn,self).__init__() self.col = colno def preParse( self, instring, loc ): if col(loc,instring) != self.col: instrlen = len(instring) if self.ignoreExprs: loc = self._skipIgnorables( instring, loc ) while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col : loc += 1 return loc def parseImpl( self, instring, loc, doActions=True ): thiscol = col( loc, instring ) if thiscol > self.col: raise ParseException( instring, loc, "Text not in expected column", self ) newloc = loc + self.col - thiscol ret = instring[ loc: newloc ] return newloc, ret class LineStart(_PositionToken): """Matches if current position is at the beginning of a line within the parse string""" def __init__( self ): super(LineStart,self).__init__() self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") ) self.errmsg = "Expected start of line" def preParse( self, instring, loc ): preloc = super(LineStart,self).preParse(instring,loc) if instring[preloc] == "\n": loc += 1 return loc def parseImpl( self, instring, loc, doActions=True ): if not( loc==0 or (loc == self.preParse( instring, 0 )) or (instring[loc-1] == "\n") ): #col(loc, instring) != 1: #~ raise ParseException( instring, loc, "Expected start of line" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] class LineEnd(_PositionToken): """Matches if current position is at the end of a line within the parse string""" def __init__( self ): super(LineEnd,self).__init__() self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") ) self.errmsg = "Expected end of line" def parseImpl( self, instring, loc, doActions=True ): if loc<len(instring): if instring[loc] == "\n": return loc+1, "\n" else: #~ raise ParseException( instring, loc, "Expected end of line" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc elif loc == len(instring): return loc+1, [] else: exc = self.myException exc.loc = loc exc.pstr = instring raise exc class StringStart(_PositionToken): """Matches if current position is at the beginning of the parse string""" def __init__( self ): super(StringStart,self).__init__() self.errmsg = "Expected start of text" def parseImpl( self, instring, loc, doActions=True ): if loc != 0: # see if entire string up to here is just whitespace and ignoreables if loc != self.preParse( instring, 0 ): #~ raise ParseException( instring, loc, "Expected start of text" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] class StringEnd(_PositionToken): """Matches if current position is at the end of the parse string""" def __init__( self ): super(StringEnd,self).__init__() self.errmsg = "Expected end of text" def parseImpl( self, instring, loc, doActions=True ): if loc < len(instring): #~ raise ParseException( instring, loc, "Expected end of text" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc elif loc == len(instring): return loc+1, [] elif loc > len(instring): return loc, [] else: exc = self.myException exc.loc = loc exc.pstr = instring raise exc class WordStart(_PositionToken): """Matches if the current position is at the beginning of a Word, and is not preceded by any character in a given set of C{wordChars} (default=C{printables}). To emulate the C{\b} behavior of regular expressions, use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of the string being parsed, or at the beginning of a line. """ def __init__(self, wordChars = printables): super(WordStart,self).__init__() self.wordChars = set(wordChars) self.errmsg = "Not at the start of a word" def parseImpl(self, instring, loc, doActions=True ): if loc != 0: if (instring[loc-1] in self.wordChars or instring[loc] not in self.wordChars): exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] class WordEnd(_PositionToken): """Matches if the current position is at the end of a Word, and is not followed by any character in a given set of C{wordChars} (default=C{printables}). To emulate the C{\b} behavior of regular expressions, use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of the string being parsed, or at the end of a line. """ def __init__(self, wordChars = printables): super(WordEnd,self).__init__() self.wordChars = set(wordChars) self.skipWhitespace = False self.errmsg = "Not at the end of a word" def parseImpl(self, instring, loc, doActions=True ): instrlen = len(instring) if instrlen>0 and loc<instrlen: if (instring[loc] in self.wordChars or instring[loc-1] not in self.wordChars): #~ raise ParseException( instring, loc, "Expected end of word" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] class ParseExpression(ParserElement): """Abstract subclass of ParserElement, for combining and post-processing parsed tokens.""" def __init__( self, exprs, savelist = False ): super(ParseExpression,self).__init__(savelist) if isinstance( exprs, list ): self.exprs = exprs elif isinstance( exprs, basestring ): self.exprs = [ Literal( exprs ) ] else: try: self.exprs = list( exprs ) except TypeError: self.exprs = [ exprs ] self.callPreparse = False def __getitem__( self, i ): return self.exprs[i] def append( self, other ): self.exprs.append( other ) self.strRepr = None return self def leaveWhitespace( self ): """Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on all contained expressions.""" self.skipWhitespace = False self.exprs = [ e.copy() for e in self.exprs ] for e in self.exprs: e.leaveWhitespace() return self def ignore( self, other ): if isinstance( other, Suppress ): if other not in self.ignoreExprs: super( ParseExpression, self).ignore( other ) for e in self.exprs: e.ignore( self.ignoreExprs[-1] ) else: super( ParseExpression, self).ignore( other ) for e in self.exprs: e.ignore( self.ignoreExprs[-1] ) return self def __str__( self ): try: return super(ParseExpression,self).__str__() except: pass if self.strRepr is None: self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) ) return self.strRepr def streamline( self ): super(ParseExpression,self).streamline() for e in self.exprs: e.streamline() # collapse nested And's of the form And( And( And( a,b), c), d) to And( a,b,c,d ) # but only if there are no parse actions or resultsNames on the nested And's # (likewise for Or's and MatchFirst's) if ( len(self.exprs) == 2 ): other = self.exprs[0] if ( isinstance( other, self.__class__ ) and not(other.parseAction) and other.resultsName is None and not other.debug ): self.exprs = other.exprs[:] + [ self.exprs[1] ] self.strRepr = None self.mayReturnEmpty |= other.mayReturnEmpty self.mayIndexError |= other.mayIndexError other = self.exprs[-1] if ( isinstance( other, self.__class__ ) and not(other.parseAction) and other.resultsName is None and not other.debug ): self.exprs = self.exprs[:-1] + other.exprs[:] self.strRepr = None self.mayReturnEmpty |= other.mayReturnEmpty self.mayIndexError |= other.mayIndexError return self def setResultsName( self, name, listAllMatches=False ): ret = super(ParseExpression,self).setResultsName(name,listAllMatches) return ret def validate( self, validateTrace=[] ): tmp = validateTrace[:]+[self] for e in self.exprs: e.validate(tmp) self.checkRecursion( [] ) def copy(self): ret = super(ParseExpression,self).copy() ret.exprs = [e.copy() for e in self.exprs] return ret class And(ParseExpression): """Requires all given C{ParseExpression}s to be found in the given order. Expressions may be separated by whitespace. May be constructed using the C{'+'} operator. """ class _ErrorStop(Empty): def __init__(self, *args, **kwargs): super(Empty,self).__init__(*args, **kwargs) self.leaveWhitespace() def __init__( self, exprs, savelist = True ): super(And,self).__init__(exprs, savelist) self.mayReturnEmpty = True for e in self.exprs: if not e.mayReturnEmpty: self.mayReturnEmpty = False break self.setWhitespaceChars( exprs[0].whiteChars ) self.skipWhitespace = exprs[0].skipWhitespace self.callPreparse = True def parseImpl( self, instring, loc, doActions=True ): # pass False as last arg to _parse for first element, since we already # pre-parsed the string as part of our And pre-parsing loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False ) errorStop = False for e in self.exprs[1:]: if isinstance(e, And._ErrorStop): errorStop = True continue if errorStop: try: loc, exprtokens = e._parse( instring, loc, doActions ) except ParseSyntaxException: raise except ParseBaseException: pe = sys.exc_info()[1] raise ParseSyntaxException(pe) except IndexError: raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) ) else: loc, exprtokens = e._parse( instring, loc, doActions ) if exprtokens or exprtokens.keys(): resultlist += exprtokens return loc, resultlist def __iadd__(self, other ): if isinstance( other, basestring ): other = Literal( other ) return self.append( other ) #And( [ self, other ] ) def checkRecursion( self, parseElementList ): subRecCheckList = parseElementList[:] + [ self ] for e in self.exprs: e.checkRecursion( subRecCheckList ) if not e.mayReturnEmpty: break def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + " ".join( [ _ustr(e) for e in self.exprs ] ) + "}" return self.strRepr class Or(ParseExpression): """Requires that at least one C{ParseExpression} is found. If two expressions match, the expression that matches the longest string will be used. May be constructed using the C{'^'} operator. """ def __init__( self, exprs, savelist = False ): super(Or,self).__init__(exprs, savelist) self.mayReturnEmpty = False for e in self.exprs: if e.mayReturnEmpty: self.mayReturnEmpty = True break def parseImpl( self, instring, loc, doActions=True ): maxExcLoc = -1 maxMatchLoc = -1 maxException = None for e in self.exprs: try: loc2 = e.tryParse( instring, loc ) except ParseException: err = sys.exc_info()[1] if err.loc > maxExcLoc: maxException = err maxExcLoc = err.loc except IndexError: if len(instring) > maxExcLoc: maxException = ParseException(instring,len(instring),e.errmsg,self) maxExcLoc = len(instring) else: if loc2 > maxMatchLoc: maxMatchLoc = loc2 maxMatchExp = e if maxMatchLoc < 0: if maxException is not None: raise maxException else: raise ParseException(instring, loc, "no defined alternatives to match", self) return maxMatchExp._parse( instring, loc, doActions ) def __ixor__(self, other ): if isinstance( other, basestring ): other = Literal( other ) return self.append( other ) #Or( [ self, other ] ) def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + " ^ ".join( [ _ustr(e) for e in self.exprs ] ) + "}" return self.strRepr def checkRecursion( self, parseElementList ): subRecCheckList = parseElementList[:] + [ self ] for e in self.exprs: e.checkRecursion( subRecCheckList ) class MatchFirst(ParseExpression): """Requires that at least one C{ParseExpression} is found. If two expressions match, the first one listed is the one that will match. May be constructed using the C{'|'} operator. """ def __init__( self, exprs, savelist = False ): super(MatchFirst,self).__init__(exprs, savelist) if exprs: self.mayReturnEmpty = False for e in self.exprs: if e.mayReturnEmpty: self.mayReturnEmpty = True break else: self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): maxExcLoc = -1 maxException = None for e in self.exprs: try: ret = e._parse( instring, loc, doActions ) return ret except ParseException, err: if err.loc > maxExcLoc: maxException = err maxExcLoc = err.loc except IndexError: if len(instring) > maxExcLoc: maxException = ParseException(instring,len(instring),e.errmsg,self) maxExcLoc = len(instring) # only got here if no expression matched, raise exception for match that made it the furthest else: if maxException is not None: raise maxException else: raise ParseException(instring, loc, "no defined alternatives to match", self) def __ior__(self, other ): if isinstance( other, basestring ): other = Literal( other ) return self.append( other ) #MatchFirst( [ self, other ] ) def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + " | ".join( [ _ustr(e) for e in self.exprs ] ) + "}" return self.strRepr def checkRecursion( self, parseElementList ): subRecCheckList = parseElementList[:] + [ self ] for e in self.exprs: e.checkRecursion( subRecCheckList ) class Each(ParseExpression): """Requires all given C{ParseExpression}s to be found, but in any order. Expressions may be separated by whitespace. May be constructed using the C{'&'} operator. """ def __init__( self, exprs, savelist = True ): super(Each,self).__init__(exprs, savelist) self.mayReturnEmpty = True for e in self.exprs: if not e.mayReturnEmpty: self.mayReturnEmpty = False break self.skipWhitespace = True self.initExprGroups = True def parseImpl( self, instring, loc, doActions=True ): if self.initExprGroups: opt1 = [ e.expr for e in self.exprs if isinstance(e,Optional) ] opt2 = [ e for e in self.exprs if e.mayReturnEmpty and e not in opt1 ] self.optionals = opt1 + opt2 self.multioptionals = [ e.expr for e in self.exprs if isinstance(e,ZeroOrMore) ] self.multirequired = [ e.expr for e in self.exprs if isinstance(e,OneOrMore) ] self.required = [ e for e in self.exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ] self.required += self.multirequired self.initExprGroups = False tmpLoc = loc tmpReqd = self.required[:] tmpOpt = self.optionals[:] matchOrder = [] keepMatching = True while keepMatching: tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired failed = [] for e in tmpExprs: try: tmpLoc = e.tryParse( instring, tmpLoc ) except ParseException: failed.append(e) else: matchOrder.append(e) if e in tmpReqd: tmpReqd.remove(e) elif e in tmpOpt: tmpOpt.remove(e) if len(failed) == len(tmpExprs): keepMatching = False if tmpReqd: missing = ", ".join( [ _ustr(e) for e in tmpReqd ] ) raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing ) # add any unmatched Optionals, in case they have default values defined matchOrder += [e for e in self.exprs if isinstance(e,Optional) and e.expr in tmpOpt] resultlist = [] for e in matchOrder: loc,results = e._parse(instring,loc,doActions) resultlist.append(results) finalResults = ParseResults([]) for r in resultlist: dups = {} for k in r.keys(): if k in finalResults.keys(): tmp = ParseResults(finalResults[k]) tmp += ParseResults(r[k]) dups[k] = tmp finalResults += ParseResults(r) for k,v in dups.items(): finalResults[k] = v return loc, finalResults def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + " & ".join( [ _ustr(e) for e in self.exprs ] ) + "}" return self.strRepr def checkRecursion( self, parseElementList ): subRecCheckList = parseElementList[:] + [ self ] for e in self.exprs: e.checkRecursion( subRecCheckList ) class ParseElementEnhance(ParserElement): """Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens.""" def __init__( self, expr, savelist=False ): super(ParseElementEnhance,self).__init__(savelist) if isinstance( expr, basestring ): expr = Literal(expr) self.expr = expr self.strRepr = None if expr is not None: self.mayIndexError = expr.mayIndexError self.mayReturnEmpty = expr.mayReturnEmpty self.setWhitespaceChars( expr.whiteChars ) self.skipWhitespace = expr.skipWhitespace self.saveAsList = expr.saveAsList self.callPreparse = expr.callPreparse self.ignoreExprs.extend(expr.ignoreExprs) def parseImpl( self, instring, loc, doActions=True ): if self.expr is not None: return self.expr._parse( instring, loc, doActions, callPreParse=False ) else: raise ParseException("",loc,self.errmsg,self) def leaveWhitespace( self ): self.skipWhitespace = False self.expr = self.expr.copy() if self.expr is not None: self.expr.leaveWhitespace() return self def ignore( self, other ): if isinstance( other, Suppress ): if other not in self.ignoreExprs: super( ParseElementEnhance, self).ignore( other ) if self.expr is not None: self.expr.ignore( self.ignoreExprs[-1] ) else: super( ParseElementEnhance, self).ignore( other ) if self.expr is not None: self.expr.ignore( self.ignoreExprs[-1] ) return self def streamline( self ): super(ParseElementEnhance,self).streamline() if self.expr is not None: self.expr.streamline() return self def checkRecursion( self, parseElementList ): if self in parseElementList: raise RecursiveGrammarException( parseElementList+[self] ) subRecCheckList = parseElementList[:] + [ self ] if self.expr is not None: self.expr.checkRecursion( subRecCheckList ) def validate( self, validateTrace=[] ): tmp = validateTrace[:]+[self] if self.expr is not None: self.expr.validate(tmp) self.checkRecursion( [] ) def __str__( self ): try: return super(ParseElementEnhance,self).__str__() except: pass if self.strRepr is None and self.expr is not None: self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) ) return self.strRepr class FollowedBy(ParseElementEnhance): """Lookahead matching of the given parse expression. C{FollowedBy} does *not* advance the parsing position within the input string, it only verifies that the specified parse expression matches at the current position. C{FollowedBy} always returns a null token list.""" def __init__( self, expr ): super(FollowedBy,self).__init__(expr) self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): self.expr.tryParse( instring, loc ) return loc, [] class NotAny(ParseElementEnhance): """Lookahead to disallow matching with the given parse expression. C{NotAny} does *not* advance the parsing position within the input string, it only verifies that the specified parse expression does *not* match at the current position. Also, C{NotAny} does *not* skip over leading whitespace. C{NotAny} always returns a null token list. May be constructed using the '~' operator.""" def __init__( self, expr ): super(NotAny,self).__init__(expr) #~ self.leaveWhitespace() self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs self.mayReturnEmpty = True self.errmsg = "Found unwanted token, "+_ustr(self.expr) def parseImpl( self, instring, loc, doActions=True ): try: self.expr.tryParse( instring, loc ) except (ParseException,IndexError): pass else: #~ raise ParseException(instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "~{" + _ustr(self.expr) + "}" return self.strRepr class ZeroOrMore(ParseElementEnhance): """Optional repetition of zero or more of the given expression.""" def __init__( self, expr ): super(ZeroOrMore,self).__init__(expr) self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): tokens = [] try: loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) hasIgnoreExprs = ( len(self.ignoreExprs) > 0 ) while 1: if hasIgnoreExprs: preloc = self._skipIgnorables( instring, loc ) else: preloc = loc loc, tmptokens = self.expr._parse( instring, preloc, doActions ) if tmptokens or tmptokens.keys(): tokens += tmptokens except (ParseException,IndexError): pass return loc, tokens def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "[" + _ustr(self.expr) + "]..." return self.strRepr def setResultsName( self, name, listAllMatches=False ): ret = super(ZeroOrMore,self).setResultsName(name,listAllMatches) ret.saveAsList = True return ret class OneOrMore(ParseElementEnhance): """Repetition of one or more of the given expression.""" def parseImpl( self, instring, loc, doActions=True ): # must be at least one loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) try: hasIgnoreExprs = ( len(self.ignoreExprs) > 0 ) while 1: if hasIgnoreExprs: preloc = self._skipIgnorables( instring, loc ) else: preloc = loc loc, tmptokens = self.expr._parse( instring, preloc, doActions ) if tmptokens or tmptokens.keys(): tokens += tmptokens except (ParseException,IndexError): pass return loc, tokens def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + _ustr(self.expr) + "}..." return self.strRepr def setResultsName( self, name, listAllMatches=False ): ret = super(OneOrMore,self).setResultsName(name,listAllMatches) ret.saveAsList = True return ret class _NullToken(object): def __bool__(self): return False __nonzero__ = __bool__ def __str__(self): return "" _optionalNotMatched = _NullToken() class Optional(ParseElementEnhance): """Optional matching of the given expression. A default return string can also be specified, if the optional expression is not found. """ def __init__( self, exprs, default=_optionalNotMatched ): super(Optional,self).__init__( exprs, savelist=False ) self.defaultValue = default self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): try: loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) except (ParseException,IndexError): if self.defaultValue is not _optionalNotMatched: if self.expr.resultsName: tokens = ParseResults([ self.defaultValue ]) tokens[self.expr.resultsName] = self.defaultValue else: tokens = [ self.defaultValue ] else: tokens = [] return loc, tokens def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "[" + _ustr(self.expr) + "]" return self.strRepr class SkipTo(ParseElementEnhance): """Token for skipping over all undefined text until the matched expression is found. If C{include} is set to true, the matched expression is also parsed (the skipped text and matched expression are returned as a 2-element list). The C{ignore} argument is used to define grammars (typically quoted strings and comments) that might contain false matches. """ def __init__( self, other, include=False, ignore=None, failOn=None ): super( SkipTo, self ).__init__( other ) self.ignoreExpr = ignore self.mayReturnEmpty = True self.mayIndexError = False self.includeMatch = include self.asList = False if failOn is not None and isinstance(failOn, basestring): self.failOn = Literal(failOn) else: self.failOn = failOn self.errmsg = "No match found for "+_ustr(self.expr) def parseImpl( self, instring, loc, doActions=True ): startLoc = loc instrlen = len(instring) expr = self.expr failParse = False while loc <= instrlen: try: if self.failOn: try: self.failOn.tryParse(instring, loc) except ParseBaseException: pass else: failParse = True raise ParseException(instring, loc, "Found expression " + str(self.failOn)) failParse = False if self.ignoreExpr is not None: while 1: try: loc = self.ignoreExpr.tryParse(instring,loc) # print "found ignoreExpr, advance to", loc except ParseBaseException: break expr._parse( instring, loc, doActions=False, callPreParse=False ) skipText = instring[startLoc:loc] if self.includeMatch: loc,mat = expr._parse(instring,loc,doActions,callPreParse=False) if mat: skipRes = ParseResults( skipText ) skipRes += mat return loc, [ skipRes ] else: return loc, [ skipText ] else: return loc, [ skipText ] except (ParseException,IndexError): if failParse: raise else: loc += 1 exc = self.myException exc.loc = loc exc.pstr = instring raise exc class Forward(ParseElementEnhance): """Forward declaration of an expression to be defined later - used for recursive grammars, such as algebraic infix notation. When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator. Note: take care when assigning to C{Forward} not to overlook precedence of operators. Specifically, '|' has a lower precedence than '<<', so that:: fwdExpr << a | b | c will actually be evaluated as:: (fwdExpr << a) | b | c thereby leaving b and c out as parseable alternatives. It is recommended that you explicitly group the values inserted into the C{Forward}:: fwdExpr << (a | b | c) """ def __init__( self, other=None ): super(Forward,self).__init__( other, savelist=False ) def __lshift__( self, other ): if isinstance( other, basestring ): other = Literal(other) self.expr = other self.mayReturnEmpty = other.mayReturnEmpty self.strRepr = None self.mayIndexError = self.expr.mayIndexError self.mayReturnEmpty = self.expr.mayReturnEmpty self.setWhitespaceChars( self.expr.whiteChars ) self.skipWhitespace = self.expr.skipWhitespace self.saveAsList = self.expr.saveAsList self.ignoreExprs.extend(self.expr.ignoreExprs) return None def leaveWhitespace( self ): self.skipWhitespace = False return self def streamline( self ): if not self.streamlined: self.streamlined = True if self.expr is not None: self.expr.streamline() return self def validate( self, validateTrace=[] ): if self not in validateTrace: tmp = validateTrace[:]+[self] if self.expr is not None: self.expr.validate(tmp) self.checkRecursion([]) def __str__( self ): if hasattr(self,"name"): return self.name self._revertClass = self.__class__ self.__class__ = _ForwardNoRecurse try: if self.expr is not None: retString = _ustr(self.expr) else: retString = "None" finally: self.__class__ = self._revertClass return self.__class__.__name__ + ": " + retString def copy(self): if self.expr is not None: return super(Forward,self).copy() else: ret = Forward() ret << self return ret class _ForwardNoRecurse(Forward): def __str__( self ): return "..." class TokenConverter(ParseElementEnhance): """Abstract subclass of C{ParseExpression}, for converting parsed results.""" def __init__( self, expr, savelist=False ): super(TokenConverter,self).__init__( expr )#, savelist ) self.saveAsList = False class Upcase(TokenConverter): """Converter to upper case all matching tokens.""" def __init__(self, *args): super(Upcase,self).__init__(*args) warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead", DeprecationWarning,stacklevel=2) def postParse( self, instring, loc, tokenlist ): return list(map( string.upper, tokenlist )) class Combine(TokenConverter): """Converter to concatenate all matching tokens to a single string. By default, the matching patterns must also be contiguous in the input string; this can be disabled by specifying C{'adjacent=False'} in the constructor. """ def __init__( self, expr, joinString="", adjacent=True ): super(Combine,self).__init__( expr ) # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself if adjacent: self.leaveWhitespace() self.adjacent = adjacent self.skipWhitespace = True self.joinString = joinString self.callPreparse = True def ignore( self, other ): if self.adjacent: ParserElement.ignore(self, other) else: super( Combine, self).ignore( other ) return self def postParse( self, instring, loc, tokenlist ): retToks = tokenlist.copy() del retToks[:] retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults) if self.resultsName and len(retToks.keys())>0: return [ retToks ] else: return retToks class Group(TokenConverter): """Converter to return the matched tokens as a list - useful for returning tokens of C{ZeroOrMore} and C{OneOrMore} expressions.""" def __init__( self, expr ): super(Group,self).__init__( expr ) self.saveAsList = True def postParse( self, instring, loc, tokenlist ): return [ tokenlist ] class Dict(TokenConverter): """Converter to return a repetitive expression as a list, but also as a dictionary. Each element can also be referenced using the first token in the expression as its key. Useful for tabular report scraping when the first column can be used as a item key. """ def __init__( self, exprs ): super(Dict,self).__init__( exprs ) self.saveAsList = True def postParse( self, instring, loc, tokenlist ): for i,tok in enumerate(tokenlist): if len(tok) == 0: continue ikey = tok[0] if isinstance(ikey,int): ikey = _ustr(tok[0]).strip() if len(tok)==1: tokenlist[ikey] = _ParseResultsWithOffset("",i) elif len(tok)==2 and not isinstance(tok[1],ParseResults): tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i) else: dictvalue = tok.copy() #ParseResults(i) del dictvalue[0] if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.keys()): tokenlist[ikey] = _ParseResultsWithOffset(dictvalue,i) else: tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0],i) if self.resultsName: return [ tokenlist ] else: return tokenlist class Suppress(TokenConverter): """Converter for ignoring the results of a parsed expression.""" def postParse( self, instring, loc, tokenlist ): return [] def suppress( self ): return self class OnlyOnce(object): """Wrapper for parse actions, to ensure they are only called once.""" def __init__(self, methodCall): self.callable = _trim_arity(methodCall) self.called = False def __call__(self,s,l,t): if not self.called: results = self.callable(s,l,t) self.called = True return results raise ParseException(s,l,"") def reset(self): self.called = False def traceParseAction(f): """Decorator for debugging parse actions.""" f = _trim_arity(f) def z(*paArgs): thisFunc = f.func_name s,l,t = paArgs[-3:] if len(paArgs)>3: thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) ) try: ret = f(*paArgs) except Exception: exc = sys.exc_info()[1] sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) ) raise sys.stderr.write( "<<leaving %s (ret: %s)\n" % (thisFunc,ret) ) return ret try: z.__name__ = f.__name__ except AttributeError: pass return z # # global helpers # def delimitedList( expr, delim=",", combine=False ): """Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing C{combine=True} in the constructor. If C{combine} is set to True, the matching tokens are returned as a single token string, with the delimiters included; otherwise, the matching tokens are returned as a list of tokens, with the delimiters suppressed. """ dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..." if combine: return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName) else: return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName) def countedArray( expr, intExpr=None ): """Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. """ arrayExpr = Forward() def countFieldParseAction(s,l,t): n = t[0] arrayExpr << (n and Group(And([expr]*n)) or Group(empty)) return [] if intExpr is None: intExpr = Word(nums).setParseAction(lambda t:int(t[0])) else: intExpr = intExpr.copy() intExpr.setName("arrayLen") intExpr.addParseAction(countFieldParseAction, callDuringTry=True) return ( intExpr + arrayExpr ) def _flatten(L): ret = [] for i in L: if isinstance(i,list): ret.extend(_flatten(i)) else: ret.append(i) return ret def matchPreviousLiteral(expr): """Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousLiteral(first) matchExpr = first + ":" + second will match C{"1:1"}, but not C{"1:2"}. Because this matches a previous literal, will also match the leading C{"1:1"} in C{"1:10"}. If this is not desired, use C{matchPreviousExpr}. Do *not* use with packrat parsing enabled. """ rep = Forward() def copyTokenToRepeater(s,l,t): if t: if len(t) == 1: rep << t[0] else: # flatten t tokens tflat = _flatten(t.asList()) rep << And( [ Literal(tt) for tt in tflat ] ) else: rep << Empty() expr.addParseAction(copyTokenToRepeater, callDuringTry=True) return rep def matchPreviousExpr(expr): """Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousExpr(first) matchExpr = first + ":" + second will match C{"1:1"}, but not C{"1:2"}. Because this matches by expressions, will *not* match the leading C{"1:1"} in C{"1:10"}; the expressions are evaluated first, and then compared, so C{"1"} is compared with C{"10"}. Do *not* use with packrat parsing enabled. """ rep = Forward() e2 = expr.copy() rep << e2 def copyTokenToRepeater(s,l,t): matchTokens = _flatten(t.asList()) def mustMatchTheseTokens(s,l,t): theseTokens = _flatten(t.asList()) if theseTokens != matchTokens: raise ParseException("",0,"") rep.setParseAction( mustMatchTheseTokens, callDuringTry=True ) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) return rep def _escapeRegexRangeChars(s): #~ escape these chars: ^-] for c in r"\^-]": s = s.replace(c,_bslash+c) s = s.replace("\n",r"\n") s = s.replace("\t",r"\t") return _ustr(s) def oneOf( strs, caseless=False, useRegex=True ): """Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a C{MatchFirst} for best performance. Parameters: - strs - a string of space-delimited literals, or a list of string literals - caseless - (default=False) - treat all literals as caseless - useRegex - (default=True) - as an optimization, will generate a Regex object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or if creating a C{Regex} raises an exception) """ if caseless: isequal = ( lambda a,b: a.upper() == b.upper() ) masks = ( lambda a,b: b.upper().startswith(a.upper()) ) parseElementClass = CaselessLiteral else: isequal = ( lambda a,b: a == b ) masks = ( lambda a,b: b.startswith(a) ) parseElementClass = Literal if isinstance(strs,(list,tuple)): symbols = list(strs[:]) elif isinstance(strs,basestring): symbols = strs.split() else: warnings.warn("Invalid argument to oneOf, expected string or list", SyntaxWarning, stacklevel=2) i = 0 while i < len(symbols)-1: cur = symbols[i] for j,other in enumerate(symbols[i+1:]): if ( isequal(other, cur) ): del symbols[i+j+1] break elif ( masks(cur, other) ): del symbols[i+j+1] symbols.insert(i,other) cur = other break else: i += 1 if not caseless and useRegex: #~ print (strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] )) try: if len(symbols)==len("".join(symbols)): return Regex( "[%s]" % "".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) ) else: return Regex( "|".join( [ re.escape(sym) for sym in symbols] ) ) except: warnings.warn("Exception creating Regex for oneOf, building MatchFirst", SyntaxWarning, stacklevel=2) # last resort, just use MatchFirst return MatchFirst( [ parseElementClass(sym) for sym in symbols ] ) def dictOf( key, value ): """Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{Dict}, C{ZeroOrMore}, and C{Group} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields. """ return Dict( ZeroOrMore( Group ( key + value ) ) ) def originalTextFor(expr, asString=True): """Helper to return the original, untokenized text for a given expression. Useful to restore the parsed fields of an HTML start tag into the raw tag text itself, or to revert separate tokens with intervening whitespace back to the original matching input text. Simpler to use than the parse action C{L{keepOriginalText}}, and does not require the inspect module to chase up the call stack. By default, returns a string containing the original parsed text. If the optional C{asString} argument is passed as C{False}, then the return value is a C{ParseResults} containing any results names that were originally matched, and a single token containing the original matched text from the input string. So if the expression passed to C{L{originalTextFor}} contains expressions with defined results names, you must set C{asString} to C{False} if you want to preserve those results name values.""" locMarker = Empty().setParseAction(lambda s,loc,t: loc) endlocMarker = locMarker.copy() endlocMarker.callPreparse = False matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end") if asString: extractText = lambda s,l,t: s[t._original_start:t._original_end] else: def extractText(s,l,t): del t[:] t.insert(0, s[t._original_start:t._original_end]) del t["_original_start"] del t["_original_end"] matchExpr.setParseAction(extractText) return matchExpr def ungroup(expr): """Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty.""" return TokenConverter(expr).setParseAction(lambda t:t[0]) # convenience constants for positional expressions empty = Empty().setName("empty") lineStart = LineStart().setName("lineStart") lineEnd = LineEnd().setName("lineEnd") stringStart = StringStart().setName("stringStart") stringEnd = StringEnd().setName("stringEnd") _escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1]) _printables_less_backslash = "".join([ c for c in printables if c not in r"\]" ]) _escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").setParseAction(lambda s,l,t:unichr(int(t[0][1:],16))) _escapedOctChar = Regex(r"\\0[0-7]+").setParseAction(lambda s,l,t:unichr(int(t[0][1:],8))) _singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(_printables_less_backslash,exact=1) _charRange = Group(_singleChar + Suppress("-") + _singleChar) _reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]" _expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p) def srange(s): r"""Helper to easily define string ranges for use in Word construction. Borrows syntax from regexp '[]' string range definitions:: srange("[0-9]") -> "0123456789" srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" The input string must be enclosed in []'s, and the returned string is the expanded character set joined into a single string. The values enclosed in the []'s may be:: a single character an escaped character with a leading backslash (such as \- or \]) an escaped hex character with a leading '\x' (\x21, which is a '!' character) (\0x## is also supported for backwards compatibility) an escaped octal character with a leading '\0' (\041, which is a '!' character) a range of any of the above, separated by a dash ('a-z', etc.) any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.) """ try: return "".join([_expanded(part) for part in _reBracketExpr.parseString(s).body]) except: return "" def matchOnlyAtCol(n): """Helper method for defining parse actions that require matching at a specific column in the input text. """ def verifyCol(strg,locn,toks): if col(locn,strg) != n: raise ParseException(strg,locn,"matched token not at column %d" % n) return verifyCol def replaceWith(replStr): """Helper method for common parse actions that simply return a literal value. Especially useful when used with C{transformString()}. """ def _replFunc(*args): return [replStr] return _replFunc def removeQuotes(s,l,t): """Helper parse action for removing quotation marks from parsed quoted strings. To use, add this parse action to quoted string using:: quotedString.setParseAction( removeQuotes ) """ return t[0][1:-1] def upcaseTokens(s,l,t): """Helper parse action to convert tokens to upper case.""" return [ tt.upper() for tt in map(_ustr,t) ] def downcaseTokens(s,l,t): """Helper parse action to convert tokens to lower case.""" return [ tt.lower() for tt in map(_ustr,t) ] def keepOriginalText(s,startLoc,t): """DEPRECATED - use new helper method C{originalTextFor}. Helper parse action to preserve original parsed text, overriding any nested parse actions.""" try: endloc = getTokensEndLoc() except ParseException: raise ParseFatalException("incorrect usage of keepOriginalText - may only be called as a parse action") del t[:] t += ParseResults(s[startLoc:endloc]) return t def getTokensEndLoc(): """Method to be called from within a parse action to determine the end location of the parsed tokens.""" import inspect fstack = inspect.stack() try: # search up the stack (through intervening argument normalizers) for correct calling routine for f in fstack[2:]: if f[3] == "_parseNoCache": endloc = f[0].f_locals["loc"] return endloc else: raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action") finally: del fstack def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" if isinstance(tagStr,basestring): resname = tagStr tagStr = Keyword(tagStr, caseless=not xml) else: resname = tagStr.name tagAttrName = Word(alphas,alphanums+"_-:") if (xml): tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) openTag = Suppress("<") + tagStr("tag") + \ Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") else: printablesLessRAbrack = "".join( [ c for c in printables if c not in ">" ] ) tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack) openTag = Suppress("<") + tagStr("tag") + \ Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \ Optional( Suppress("=") + tagAttrValue ) ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") closeTag = Combine(_L("</") + tagStr + ">") openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr) closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % tagStr) openTag.tag = resname closeTag.tag = resname return openTag, closeTag def makeHTMLTags(tagStr): """Helper to construct opening and closing tag expressions for HTML, given a tag name""" return _makeTags( tagStr, False ) def makeXMLTags(tagStr): """Helper to construct opening and closing tag expressions for XML, given a tag name""" return _makeTags( tagStr, True ) def withAttribute(*args,**attrDict): """Helper to create a validating parse action to be used with start tags created with C{makeXMLTags} or C{makeHTMLTags}. Use C{withAttribute} to qualify a starting tag with a required attribute value, to avoid false matches on common tags such as C{<TD>} or C{<DIV>}. Call C{withAttribute} with a series of attribute names and values. Specify the list of filter attributes names and values as: - keyword arguments, as in C{(align="right")}, or - as an explicit dict with C{**} operator, when an attribute name is also a Python reserved word, as in C{**{"class":"Customer", "align":"right"}} - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") ) For attribute names with a namespace prefix, you must use the second form. Attribute names are matched insensitive to upper/lower case. To verify that the attribute exists, but without specifying a value, pass C{withAttribute.ANY_VALUE} as the value. """ if args: attrs = args[:] else: attrs = attrDict.items() attrs = [(k,v) for k,v in attrs] def pa(s,l,tokens): for attrName,attrValue in attrs: if attrName not in tokens: raise ParseException(s,l,"no matching attribute " + attrName) if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue: raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" % (attrName, tokens[attrName], attrValue)) return pa withAttribute.ANY_VALUE = object() opAssoc = _Constants() opAssoc.LEFT = object() opAssoc.RIGHT = object() def operatorPrecedence( baseExpr, opList ): """Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions. Parameters: - baseExpr - expression representing the most basic element for the nested - opList - list of tuples, one for each operator precedence level in the expression grammar; each tuple is of the form (opExpr, numTerms, rightLeftAssoc, parseAction), where: - opExpr is the pyparsing expression for the operator; may also be a string, which will be converted to a Literal; if numTerms is 3, opExpr is a tuple of two expressions, for the two operators separating the 3 terms - numTerms is the number of terms for this operator (must be 1, 2, or 3) - rightLeftAssoc is the indicator whether the operator is right or left associative, using the pyparsing-defined constants opAssoc.RIGHT and opAssoc.LEFT. - parseAction is the parse action to be associated with expressions matching this operator expression (the parse action tuple member may be omitted) """ ret = Forward() lastExpr = baseExpr | ( Suppress('(') + ret + Suppress(')') ) for i,operDef in enumerate(opList): opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4] if arity == 3: if opExpr is None or len(opExpr) != 2: raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions") opExpr1, opExpr2 = opExpr thisExpr = Forward()#.setName("expr%d" % i) if rightLeftAssoc == opAssoc.LEFT: if arity == 1: matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) ) elif arity == 2: if opExpr is not None: matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) ) else: matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) ) elif arity == 3: matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \ Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr ) else: raise ValueError("operator must be unary (1), binary (2), or ternary (3)") elif rightLeftAssoc == opAssoc.RIGHT: if arity == 1: # try to avoid LR with this extra test if not isinstance(opExpr, Optional): opExpr = Optional(opExpr) matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr ) elif arity == 2: if opExpr is not None: matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) ) else: matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) ) elif arity == 3: matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \ Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr ) else: raise ValueError("operator must be unary (1), binary (2), or ternary (3)") else: raise ValueError("operator must indicate right or left associativity") if pa: matchExpr.setParseAction( pa ) thisExpr << ( matchExpr | lastExpr ) lastExpr = thisExpr ret << lastExpr return ret dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*"').setName("string enclosed in double quotes") sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*'").setName("string enclosed in single quotes") quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*')''').setName("quotedString using single or double quotes") unicodeString = Combine(_L('u') + quotedString.copy()) def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()): """Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default="("); can also be a pyparsing expression - closer - closing character for a nested list (default=")"); can also be a pyparsing expression - content - expression for items within the nested lists (default=None) - ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString) If an expression is not provided for the content argument, the nested expression will capture all whitespace-delimited content between delimiters as a list of separate values. Use the C{ignoreExpr} argument to define expressions that may contain opening or closing characters that should not be treated as opening or closing characters for nesting, such as quotedString or a comment expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}. The default is L{quotedString}, but if no expressions are to be ignored, then pass C{None} for this argument. """ if opener == closer: raise ValueError("opening and closing strings cannot be the same") if content is None: if isinstance(opener,basestring) and isinstance(closer,basestring): if len(opener) == 1 and len(closer)==1: if ignoreExpr is not None: content = (Combine(OneOrMore(~ignoreExpr + CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS,exact=1)) ).setParseAction(lambda t:t[0].strip())) else: content = (empty.copy()+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS ).setParseAction(lambda t:t[0].strip())) else: if ignoreExpr is not None: content = (Combine(OneOrMore(~ignoreExpr + ~Literal(opener) + ~Literal(closer) + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1)) ).setParseAction(lambda t:t[0].strip())) else: content = (Combine(OneOrMore(~Literal(opener) + ~Literal(closer) + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1)) ).setParseAction(lambda t:t[0].strip())) else: raise ValueError("opening and closing arguments must be strings if no content expression is given") ret = Forward() if ignoreExpr is not None: ret << Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) ) else: ret << Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) ) return ret def indentedBlock(blockStatementExpr, indentStack, indent=True): """Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - indentStack - list created by caller to manage indentation stack (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack) - indent - boolean indicating whether block must be indented beyond the the current level; set to False for block of left-most statements (default=True) A valid block must contain at least one C{blockStatement}. """ def checkPeerIndent(s,l,t): if l >= len(s): return curCol = col(l,s) if curCol != indentStack[-1]: if curCol > indentStack[-1]: raise ParseFatalException(s,l,"illegal nesting") raise ParseException(s,l,"not a peer entry") def checkSubIndent(s,l,t): curCol = col(l,s) if curCol > indentStack[-1]: indentStack.append( curCol ) else: raise ParseException(s,l,"not a subentry") def checkUnindent(s,l,t): if l >= len(s): return curCol = col(l,s) if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]): raise ParseException(s,l,"not an unindent") indentStack.pop() NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress()) INDENT = Empty() + Empty().setParseAction(checkSubIndent) PEER = Empty().setParseAction(checkPeerIndent) UNDENT = Empty().setParseAction(checkUnindent) if indent: smExpr = Group( Optional(NL) + #~ FollowedBy(blockStatementExpr) + INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT) else: smExpr = Group( Optional(NL) + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) ) blockStatementExpr.ignore(_bslash + LineEnd()) return smExpr alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]") punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]") anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:")) commonHTMLEntity = Combine(_L("&") + oneOf("gt lt amp nbsp quot").setResultsName("entity") +";").streamline() _htmlEntityMap = dict(zip("gt lt amp nbsp quot".split(),'><& "')) replaceHTMLEntity = lambda t : t.entity in _htmlEntityMap and _htmlEntityMap[t.entity] or None # it's easy to get these comment structures wrong - they're very common, so may as well make them available cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment") htmlComment = Regex(r"<!--[\s\S]*?-->") restOfLine = Regex(r".*").leaveWhitespace() dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment") cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?<!\\)|\Z))").setName("C++ style comment") javaStyleComment = cppStyleComment pythonStyleComment = Regex(r"#.*").setName("Python style comment") _noncomma = "".join( [ c for c in printables if c != "," ] ) _commasepitem = Combine(OneOrMore(Word(_noncomma) + Optional( Word(" \t") + ~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem") commaSeparatedList = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("commaSeparatedList") if __name__ == "__main__": def test( teststring ): try: tokens = simpleSQL.parseString( teststring ) tokenlist = tokens.asList() print (teststring + "->" + str(tokenlist)) print ("tokens = " + str(tokens)) print ("tokens.columns = " + str(tokens.columns)) print ("tokens.tables = " + str(tokens.tables)) print (tokens.asXML("SQL",True)) except ParseBaseException: err = sys.exc_info()[1] print (teststring + "->") print (err.line) print (" "*(err.column-1) + "^") print (err) print() selectToken = CaselessLiteral( "select" ) fromToken = CaselessLiteral( "from" ) ident = Word( alphas, alphanums + "_$" ) columnName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens ) columnNameList = Group( delimitedList( columnName ) )#.setName("columns") tableName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens ) tableNameList = Group( delimitedList( tableName ) )#.setName("tables") simpleSQL = ( selectToken + \ ( '*' | columnNameList ).setResultsName( "columns" ) + \ fromToken + \ tableNameList.setResultsName( "tables" ) ) test( "SELECT * from XYZZY, ABC" ) test( "select * from SYS.XYZZY" ) test( "Select A from Sys.dual" ) test( "Select AA,BB,CC from Sys.dual" ) test( "Select A, B, C from Sys.dual" ) test( "Select A, B, C from Sys.dual" ) test( "Xelect A, B, C from Sys.dual" ) test( "Select A, B, C frox Sys.dual" ) test( "Select" ) test( "Select ^^^ frox Sys.dual" ) test( "Select A, B, C from Sys.dual, Table2 " )
bsd-3-clause
-8,982,969,325,968,208,000
39.458789
196
0.565017
false
the-metaverse/metaverse
test/test-rpc/utils/cryptojs.py
3
1274
#!/usr/bin/python # -*- coding: utf-8 -*- from Crypto.Hash import MD5 from Crypto.Cipher import AES from Crypto import Random import base64 def toString(s): return ''.join(['%02x' % ord(i) for i in s]) def toBase64(s): return base64.b64encode(s) def derive_key(passphrase, salt): key_size = 32 iv_size = 16 iterations = 1 derivedKeyWords = '' block = '' while len(derivedKeyWords) < (key_size + iv_size): hash = MD5.new() hash.update(block + passphrase + salt) block = hash.digest() derivedKeyWords += block key = derivedKeyWords[:key_size] iv = derivedKeyWords[key_size:] return key, iv def Pkcs7(data, block_size=16): nPaddingBytes = block_size - (len(data) % block_size) return chr(nPaddingBytes) * nPaddingBytes def AES_CBC_encrypt(message, key, iv): cipher = AES.new(key, AES.MODE_CBC, iv) msg = cipher.encrypt(message + Pkcs7(message)) return msg def AES_CBC_decrypt(cipher_txt, passphrase): s = base64.b64decode(cipher_txt) salt = s[8:16] raw_cipher_txt = s[16:] key, iv = derive_key(passphrase, salt) cipher = AES.new(key, AES.MODE_CBC, iv) msg = cipher.decrypt(raw_cipher_txt) padding = ord(msg[-1]) return msg[:-padding]
agpl-3.0
-8,707,886,375,918,535,000
22.163636
57
0.635008
false
ondrejmular/pcs
pcs/lib/commands/cluster.py
3
76808
# pylint: disable=too-many-lines import math import os.path import time from typing import ( Any, Container, Mapping, Optional, Sequence, ) from pcs import settings from pcs.common import ( file_type_codes, reports, ssl, ) from pcs.common.corosync_conf import ( CorosyncConfDto, CorosyncQuorumDeviceSettingsDto, ) from pcs.common.file import RawFileError from pcs.common.node_communicator import HostNotFound from pcs.common.reports import ( codes as report_codes, ReportProcessor, ) from pcs.common.reports.item import ReportItem from pcs.common.tools import format_environment_error from pcs.common.types import ( CorosyncTransportType, UnknownCorosyncTransportTypeException, ) from pcs.common.str_tools import join_multilines from pcs.lib import node_communication_format, sbd, validate from pcs.lib.booth import sync as booth_sync from pcs.lib.cib import fencing_topology from pcs.lib.cib.resource.remote_node import find_node_list as get_remote_nodes from pcs.lib.cib.resource.guest_node import find_node_list as get_guest_nodes from pcs.lib.cib.tools import ( get_fencing_topology, get_resources, ) from pcs.lib.communication import cluster from pcs.lib.communication.corosync import ( CheckCorosyncOffline, DistributeCorosyncConf, ReloadCorosyncConf, ) from pcs.lib.communication.nodes import ( CheckPacemakerStarted, DistributeFilesWithoutForces, EnableCluster, GetHostInfo, GetOnlineTargets, RemoveFilesWithoutForces, RemoveNodesFromCib, SendPcsdSslCertAndKey, StartCluster, UpdateKnownHosts, ) from pcs.lib.communication.sbd import ( CheckSbd, SetSbdConfig, EnableSbdService, DisableSbdService, ) from pcs.lib.communication.tools import ( run as run_com, run_and_raise, AllSameDataMixin, ) from pcs.lib.corosync import ( config_facade, config_parser, config_validators, constants as corosync_constants, qdevice_net, ) from pcs.lib.env import LibraryEnvironment from pcs.lib.file.instance import FileInstance from pcs.lib.node import get_existing_nodes_names from pcs.lib.errors import LibraryError from pcs.lib.interface.config import ParserErrorException from pcs.lib.pacemaker.live import ( get_cib, get_cib_xml, get_cib_xml_cmd_results, remove_node, verify as verify_cmd, ) from pcs.lib.pacemaker.state import ClusterState from pcs.lib.pacemaker.values import get_valid_timeout_seconds from pcs.lib.tools import ( environment_file_to_dict, generate_binary_key, ) def node_clear( env: LibraryEnvironment, node_name, allow_clear_cluster_node=False, ): """ Remove specified node from various cluster caches. LibraryEnvironment env provides all for communication with externals string node_name bool allow_clear_cluster_node -- flag allows to clear node even if it's still in a cluster """ _ensure_live_env(env) # raises if env is not live current_nodes, report_list = get_existing_nodes_names( env.get_corosync_conf(), env.get_cib() ) if env.report_processor.report_list(report_list).has_errors: raise LibraryError() if node_name in current_nodes: if env.report_processor.report( ReportItem( severity=reports.item.get_severity( report_codes.FORCE_CLEAR_CLUSTER_NODE, allow_clear_cluster_node, ), message=reports.messages.NodeToClearIsStillInCluster(node_name), ) ).has_errors: raise LibraryError() remove_node(env.cmd_runner(), node_name) def verify(env: LibraryEnvironment, verbose=False): runner = env.cmd_runner() ( dummy_stdout, verify_stderr, verify_returncode, can_be_more_verbose, ) = verify_cmd(runner, verbose=verbose) # 1) Do not even try to think about upgrading! # 2) We do not need cib management in env (no need for push...). # So env.get_cib is not best choice here (there were considerations to # upgrade cib at all times inside env.get_cib). Go to a lower level here. if verify_returncode != 0: env.report_processor.report( ReportItem.error( reports.messages.InvalidCibContent( verify_stderr, can_be_more_verbose, ) ) ) # Cib is sometimes loadable even if `crm_verify` fails (e.g. when # fencing topology is invalid). On the other hand cib with id # duplication is not loadable. # We try extra checks when cib is possible to load. cib_xml, dummy_stderr, returncode = get_cib_xml_cmd_results(runner) if returncode != 0: raise LibraryError() else: cib_xml = get_cib_xml(runner) cib = get_cib(cib_xml) env.report_processor.report_list( fencing_topology.verify( get_fencing_topology(cib), get_resources(cib), ClusterState(env.get_cluster_state()).node_section.nodes, ) ) if env.report_processor.has_errors: raise LibraryError() def setup( env, cluster_name, nodes, transport_type=None, transport_options=None, link_list=None, compression_options=None, crypto_options=None, totem_options=None, quorum_options=None, wait=False, start=False, enable=False, no_keys_sync=False, force_flags: Container[reports.types.ForceCode] = (), ): # pylint: disable=too-many-arguments # pylint: disable=too-many-locals # pylint: disable=too-many-statements # pylint: disable=too-many-branches """ Set up cluster on specified nodes. Validation of the inputs is done here. Possible existing clusters are destroyed (when using force). Authkey files for corosync and pacemaer, known hosts and and newly generated corosync.conf are distributed to all nodes. Raise LibraryError on any error. env LibraryEnvironment cluster_name string -- name of a cluster to set up nodes list -- list of dicts which represents node. Supported keys are: name (required), addrs. See note bellow. transport_type string -- transport type of a cluster transport_options dict -- transport specific options link_list list of dict -- list of links, depends of transport_type compression_options dict -- only available for knet transport. In corosync.conf they are prefixed 'knet_compression_' crypto_options dict -- only available for knet transport'. In corosync.conf they are prefixed 'crypto_' totem_options dict -- options of section 'totem' in corosync.conf quorum_options dict -- options of section 'quorum' in corosync.conf wait -- specifies if command should try to wait for cluster to start up. Has no effect start is False. If set to False command will not wait for cluster to start. If None command will wait for some default timeout. If int wait set timeout to int value of seconds. start bool -- if True start cluster when it is set up enable bool -- if True enable cluster when it is set up no_keys_sync bool -- if True do not crete and distribute files: pcsd ssl cert and key, pacemaker authkey, corosync authkey force_flags list -- list of flags codes The command is defaulting node addresses if they are not specified. The defaulting is done for each node individually if and only if the "addrs" key is not present for the node. If the "addrs" key is present and holds an empty list, no defaulting is done. This will default addresses for node2 and won't modify addresses for other nodes (no addresses will be defined for node3): nodes=[ {"name": "node1", "addrs": ["node1-addr"]}, {"name": "node2"}, {"name": "node3", "addrs": []}, ] """ _ensure_live_env(env) # raises if env is not live force = report_codes.FORCE in force_flags transport_type = transport_type or "knet" transport_options = transport_options or {} link_list = link_list or [] compression_options = compression_options or {} crypto_options = crypto_options or {} totem_options = totem_options or {} quorum_options = quorum_options or {} nodes = [_normalize_dict(node, {"addrs"}) for node in nodes] if ( transport_type in corosync_constants.TRANSPORTS_KNET and not crypto_options ): crypto_options = { "cipher": "aes256", "hash": "sha256", } report_processor = env.report_processor target_factory = env.get_node_target_factory() # Get targets for all nodes and report unknown (== not-authorized) nodes. # If a node doesn't contain the 'name' key, validation of inputs reports it. # That means we don't report missing names but cannot rely on them being # present either. ( target_report_list, target_list, ) = target_factory.get_target_list_with_reports( [node["name"] for node in nodes if "name" in node], allow_skip=False, ) report_processor.report_list(target_report_list) # Use an address defined in known-hosts for each node with no addresses # specified. This allows users not to specify node addresses at all which # simplifies the whole cluster setup command / form significantly. addrs_defaulter = _get_addrs_defaulter( report_processor, {target.label: target for target in target_list} ) nodes = [ _set_defaults_in_dict(node, {"addrs": addrs_defaulter}) for node in nodes ] # Validate inputs. report_processor.report_list( _validate_create_corosync_conf( cluster_name, nodes, transport_type, transport_options, link_list, compression_options, crypto_options, totem_options, quorum_options, force, ) ) # Validate flags wait_timeout = _get_validated_wait_timeout(report_processor, wait, start) # Validate the nodes com_cmd: AllSameDataMixin = GetHostInfo(report_processor) com_cmd.set_targets(target_list) report_processor.report_list( _host_check_cluster_setup( run_com(env.get_node_communicator(), com_cmd), force ) ) # If there is an error reading the file, this will report it and exit # safely before any change is made to the nodes. sync_ssl_certs = _is_ssl_cert_sync_enabled(report_processor) if report_processor.has_errors: raise LibraryError() # Validation done. If errors occured, an exception has been raised and we # don't get below this line. # Destroy cluster on all nodes. com_cmd = cluster.Destroy(env.report_processor) com_cmd.set_targets(target_list) run_and_raise(env.get_node_communicator(), com_cmd) # Distribute auth tokens. com_cmd = UpdateKnownHosts( env.report_processor, known_hosts_to_add=env.get_known_hosts( [target.label for target in target_list] ), known_hosts_to_remove=[], ) com_cmd.set_targets(target_list) run_and_raise(env.get_node_communicator(), com_cmd) # TODO This should be in the file distribution call but so far we don't # have a call which allows to save and delete files at the same time. com_cmd = RemoveFilesWithoutForces( env.report_processor, {"pcsd settings": {"type": "pcsd_settings"}}, ) com_cmd.set_targets(target_list) run_and_raise(env.get_node_communicator(), com_cmd) if not no_keys_sync: # Distribute configuration files except corosync.conf. Sending # corosync.conf serves as a "commit" as its presence on a node marks the # node as a part of a cluster. corosync_authkey = generate_binary_key( random_bytes_count=settings.corosync_authkey_bytes ) pcmk_authkey = generate_binary_key( random_bytes_count=settings.pacemaker_authkey_bytes ) actions = {} actions.update( node_communication_format.corosync_authkey_file(corosync_authkey) ) actions.update( node_communication_format.pcmk_authkey_file(pcmk_authkey) ) com_cmd = DistributeFilesWithoutForces(env.report_processor, actions) com_cmd.set_targets(target_list) run_and_raise(env.get_node_communicator(), com_cmd) # Distribute and reload pcsd SSL certificate if sync_ssl_certs: report_processor.report( ReportItem.info( reports.messages.PcsdSslCertAndKeyDistributionStarted( sorted([target.label for target in target_list]) ) ) ) # Local certificate and key cannot be used because the local node # may not be a part of the new cluter at all. ssl_key_raw = ssl.generate_key() ssl_key = ssl.dump_key(ssl_key_raw) ssl_cert = ssl.dump_cert( ssl.generate_cert(ssl_key_raw, target_list[0].label) ) com_cmd = SendPcsdSslCertAndKey( env.report_processor, ssl_cert, ssl_key ) com_cmd.set_targets(target_list) run_and_raise(env.get_node_communicator(), com_cmd) # Create and distribute corosync.conf. Once a node saves corosync.conf it # is considered to be in a cluster. # raises if corosync not valid com_cmd = DistributeFilesWithoutForces( env.report_processor, node_communication_format.corosync_conf_file( _create_corosync_conf( cluster_name, nodes, transport_type, transport_options, link_list, compression_options, crypto_options, totem_options, quorum_options, ).config.export() ), ) com_cmd.set_targets(target_list) run_and_raise(env.get_node_communicator(), com_cmd) if env.report_processor.report( ReportItem.info(reports.messages.ClusterSetupSuccess()) ).has_errors: raise LibraryError() # Optionally enable and start cluster services. if enable: com_cmd = EnableCluster(env.report_processor) com_cmd.set_targets(target_list) run_and_raise(env.get_node_communicator(), com_cmd) if start: _start_cluster( env.communicator_factory, env.report_processor, target_list, wait_timeout=wait_timeout, ) def setup_local( env: LibraryEnvironment, cluster_name: str, nodes: Sequence[Mapping[str, Any]], transport_type: Optional[str], transport_options: Mapping[str, str], link_list: Sequence[Mapping[str, Any]], compression_options: Mapping[str, str], crypto_options: Mapping[str, str], totem_options: Mapping[str, str], quorum_options: Mapping[str, str], force_flags: Container[reports.types.ForceCode] = (), ) -> bytes: """ Return corosync.conf text based on specified parameters. Raise LibraryError on any error. env cluster_name -- name of a cluster to set up nodes list -- list of dicts which represents node. Supported keys are: name (required), addrs. See note bellow. transport_type -- transport type of a cluster transport_options -- transport specific options link_list -- list of links, depends of transport_type compression_options -- only available for knet transport. In corosync.conf they are prefixed 'knet_compression_' crypto_options -- only available for knet transport'. In corosync.conf they are prefixed 'crypto_' totem_options -- options of section 'totem' in corosync.conf quorum_options -- options of section 'quorum' in corosync.conf force_flags -- list of flags codes The command is defaulting node addresses if they are not specified. The defaulting is done for each node individually if and only if the "addrs" key is not present for the node. If the "addrs" key is present and holds an empty list, no defaulting is done. This will default addresses for node2 and won't modify addresses for other nodes (no addresses will be defined for node3): nodes=[ {"name": "node1", "addrs": ["node1-addr"]}, {"name": "node2"}, {"name": "node3", "addrs": []}, ] """ # pylint: disable=too-many-arguments # pylint: disable=too-many-locals force = report_codes.FORCE in force_flags transport_type = transport_type or "knet" nodes = [_normalize_dict(node, {"addrs"}) for node in nodes] if ( transport_type in corosync_constants.TRANSPORTS_KNET and not crypto_options ): crypto_options = { "cipher": "aes256", "hash": "sha256", } report_processor = env.report_processor target_factory = env.get_node_target_factory() # Get targets just for address defaulting, no need to report unknown nodes _, target_list = target_factory.get_target_list_with_reports( [node["name"] for node in nodes if "name" in node], allow_skip=False, ) # Use an address defined in known-hosts for each node with no addresses # specified. This allows users not to specify node addresses at all which # simplifies the whole cluster setup command / form significantly. # If there is no address for a node in known-hosts, use its name as the # default address addrs_defaulter = _get_addrs_defaulter( report_processor, {target.label: target for target in target_list}, default_to_name_if_no_target=True, ) nodes = [ _set_defaults_in_dict(node, {"addrs": addrs_defaulter}) for node in nodes ] # Validate inputs. if report_processor.report_list( _validate_create_corosync_conf( cluster_name, nodes, transport_type, transport_options, link_list, compression_options, crypto_options, totem_options, quorum_options, force, ) ).has_errors: raise LibraryError() # Validation done. If errors occured, an exception has been raised and we # don't get below this line. return ( _create_corosync_conf( cluster_name, nodes, transport_type, transport_options, link_list, compression_options, crypto_options, totem_options, quorum_options, ) .config.export() .encode("utf-8") ) def _validate_create_corosync_conf( cluster_name: str, nodes: Sequence[Mapping[str, Any]], transport_type: str, transport_options: Mapping[str, str], link_list: Sequence[Mapping[str, Any]], compression_options: Mapping[str, str], crypto_options: Mapping[str, str], totem_options: Mapping[str, str], quorum_options: Mapping[str, str], force: bool, ) -> reports.ReportItemList: # pylint: disable=too-many-arguments # Get IP version for node addresses validation. Defaults taken from man # corosync.conf ip_version = ( corosync_constants.IP_VERSION_4 if transport_type == "udp" else corosync_constants.IP_VERSION_64 ) if ( transport_options.get("ip_version") in corosync_constants.IP_VERSION_VALUES ): ip_version = transport_options["ip_version"] report_list = [] report_list += config_validators.create( cluster_name, nodes, transport_type, ip_version, force_unresolvable=force, force_cluster_name=force, ) max_node_addr_count = max([len(node["addrs"]) for node in nodes], default=0) if transport_type in corosync_constants.TRANSPORTS_KNET: report_list += config_validators.create_transport_knet( transport_options, compression_options, crypto_options ) report_list += config_validators.create_link_list_knet( link_list, max_node_addr_count ) elif transport_type in corosync_constants.TRANSPORTS_UDP: report_list += config_validators.create_transport_udp( transport_options, compression_options, crypto_options ) report_list += config_validators.create_link_list_udp( link_list, max_node_addr_count ) return ( report_list + config_validators.create_totem(totem_options) # We are creating the config and we know there is no qdevice in it. + config_validators.create_quorum_options(quorum_options, False) ) def _create_corosync_conf( cluster_name: str, nodes: Sequence[Mapping[str, Any]], transport_type: str, transport_options: Mapping[str, str], link_list: Sequence[Mapping[str, Any]], compression_options: Mapping[str, str], crypto_options: Mapping[str, str], totem_options: Mapping[str, str], quorum_options: Mapping[str, str], ) -> config_facade.ConfigFacade: # pylint: disable=too-many-arguments corosync_conf = config_facade.ConfigFacade.create( cluster_name, nodes, transport_type ) corosync_conf.set_totem_options(totem_options) corosync_conf.set_quorum_options(quorum_options) corosync_conf.create_link_list(link_list) corosync_conf.set_transport_options( transport_options, compression_options, crypto_options, ) _verify_corosync_conf(corosync_conf) # raises if corosync not valid return corosync_conf def _config_update( report_processor: ReportProcessor, corosync_conf: config_facade.ConfigFacade, transport_options: Mapping[str, str], compression_options: Mapping[str, str], crypto_options: Mapping[str, str], totem_options: Mapping[str, str], ) -> None: transport_type = corosync_conf.get_transport() report_list = config_validators.update_totem(totem_options) if transport_type in corosync_constants.TRANSPORTS_KNET: report_list += config_validators.update_transport_knet( transport_options, compression_options, crypto_options, corosync_conf.get_crypto_options(), ) elif transport_type in corosync_constants.TRANSPORTS_UDP: report_list += config_validators.update_transport_udp( transport_options, compression_options, crypto_options, ) else: report_processor.report( ReportItem.error( reports.messages.CorosyncConfigUnsupportedTransport( transport_type, sorted(corosync_constants.TRANSPORTS_ALL) ) ) ) if report_processor.report_list(report_list).has_errors: raise LibraryError() corosync_conf.set_totem_options(totem_options) corosync_conf.set_transport_options( transport_options, compression_options, crypto_options, ) _verify_corosync_conf(corosync_conf) # raises if corosync not valid def config_update( env: LibraryEnvironment, transport_options: Mapping[str, str], compression_options: Mapping[str, str], crypto_options: Mapping[str, str], totem_options: Mapping[str, str], ) -> None: """ Update corosync.conf in the local cluster env transport_options -- transport specific options compression_options -- only available for knet transport. In corosync.conf they are prefixed 'knet_compression_' crypto_options -- only available for knet transport. In corosync.conf they are prefixed 'crypto_' totem_options -- options of section 'totem' in corosync.conf """ _ensure_live_env(env) corosync_conf = env.get_corosync_conf() _config_update( env.report_processor, corosync_conf, transport_options, compression_options, crypto_options, totem_options, ) env.push_corosync_conf(corosync_conf) def config_update_local( env: LibraryEnvironment, corosync_conf_content: bytes, transport_options: Mapping[str, str], compression_options: Mapping[str, str], crypto_options: Mapping[str, str], totem_options: Mapping[str, str], ) -> bytes: """ Update corosync.conf passed as an argument and return the updated conf env corosync_conf_content -- corosync.conf to be updated transport_options -- transport specific options compression_options -- only available for knet transport. In corosync.conf they are prefixed 'knet_compression_' crypto_options -- only available for knet transport. In corosync.conf they are prefixed 'crypto_' totem_options -- options of section 'totem' in corosync.conf """ # As we are getting a corosync.conf content as an argument, we want to make # sure it was not given to LibraryEnvironment as well. Also we don't # allow/need CIB to be handled by LibraryEnvironment. _ensure_live_env(env) corosync_conf_instance = FileInstance.for_corosync_conf() try: corosync_conf: config_facade.ConfigFacade = ( corosync_conf_instance.raw_to_facade(corosync_conf_content) ) except ParserErrorException as e: if env.report_processor.report_list( corosync_conf_instance.toolbox.parser.exception_to_report_list( e, corosync_conf_instance.toolbox.file_type_code, None, force_code=None, is_forced_or_warning=False, ) ).has_errors: raise LibraryError() from e _config_update( env.report_processor, corosync_conf, transport_options, compression_options, crypto_options, totem_options, ) return corosync_conf_instance.facade_to_raw(corosync_conf) def get_corosync_conf_struct(env: LibraryEnvironment) -> CorosyncConfDto: """ Read corosync.conf from the local node and return it in a structured form """ corosync_conf = env.get_corosync_conf() quorum_device_dto: Optional[CorosyncQuorumDeviceSettingsDto] = None if corosync_conf.has_quorum_device(): ( qd_model, qd_model_options, qd_generic_options, qd_heuristics_options, ) = corosync_conf.get_quorum_device_settings() quorum_device_dto = CorosyncQuorumDeviceSettingsDto( model=qd_model, model_options=qd_model_options, generic_options=qd_generic_options, heuristics_options=qd_heuristics_options, ) try: return CorosyncConfDto( cluster_name=corosync_conf.get_cluster_name(), transport=CorosyncTransportType.from_str( corosync_conf.get_transport() ), totem_options=corosync_conf.get_totem_options(), transport_options=corosync_conf.get_transport_options(), compression_options=corosync_conf.get_compression_options(), crypto_options=corosync_conf.get_crypto_options(), nodes=[node.to_dto() for node in corosync_conf.get_nodes()], links_options=corosync_conf.get_links_options(), quorum_options=corosync_conf.get_quorum_options(), quorum_device=quorum_device_dto, ) except UnknownCorosyncTransportTypeException as e: raise LibraryError( ReportItem.error( reports.messages.CorosyncConfigUnsupportedTransport( e.transport, sorted(corosync_constants.TRANSPORTS_ALL) ) ) ) from e def add_nodes( env: LibraryEnvironment, nodes, wait=False, start=False, enable=False, no_watchdog_validation=False, force_flags: Container[reports.types.ForceCode] = (), ): # pylint: disable=too-many-locals, too-many-statements, too-many-branches """ Add specified nodes to the local cluster Raise LibraryError on any error. env LibraryEnvironment nodes list -- list of dicts which represents node. Supported keys are: name (required), addrs (list), devices (list), watchdog. See note below. wait -- specifies if command should try to wait for cluster to start up. Has no effect start is False. If set to False command will not wait for cluster to start. If None command will wait for some default timeout. If int wait set timeout to int value of seconds. start bool -- if True start cluster when it is set up enable bool -- if True enable cluster when it is set up no_watchdog_validation bool -- if True do not validate specified watchdogs on remote hosts force_flags list -- list of flags codes The command is defaulting node addresses if they are not specified. The defaulting is done for each node individually if and only if the "addrs" key is not present for the node. If the "addrs" key is present and holds an empty list, no defaulting is done. This will default addresses for node2 and won't modify addresses for other nodes (no addresses will be defined for node3): nodes=[ {"name": "node1", "addrs": ["node1-addr"]}, {"name": "node2"}, {"name": "node3", "addrs": []}, ] """ _ensure_live_env(env) # raises if env is not live force = report_codes.FORCE in force_flags skip_offline_nodes = report_codes.SKIP_OFFLINE_NODES in force_flags report_processor = env.report_processor target_factory = env.get_node_target_factory() is_sbd_enabled = sbd.is_sbd_enabled(env.service_manager) corosync_conf = env.get_corosync_conf() corosync_node_options = {"name", "addrs"} sbd_node_options = {"devices", "watchdog"} keys_to_normalize = {"addrs"} if is_sbd_enabled: keys_to_normalize |= sbd_node_options new_nodes = [_normalize_dict(node, keys_to_normalize) for node in nodes] # get targets for existing nodes cluster_nodes_names, nodes_report_list = get_existing_nodes_names( corosync_conf, # Pcs is unable to communicate with nodes missing names. It cannot send # new corosync.conf to them. That might break the cluster. Hence we # error out. error_on_missing_name=True, ) report_processor.report_list(nodes_report_list) ( target_report_list, cluster_nodes_target_list, ) = target_factory.get_target_list_with_reports( cluster_nodes_names, skip_non_existing=skip_offline_nodes, ) report_processor.report_list(target_report_list) # get a target for qnetd if needed ( qdevice_model, qdevice_model_options, _, _, ) = corosync_conf.get_quorum_device_settings() if qdevice_model == "net": try: qnetd_target = target_factory.get_target( qdevice_model_options["host"] ) except HostNotFound: report_processor.report( ReportItem.error( reports.messages.HostNotFound( [qdevice_model_options["host"]] ) ) ) # Get targets for new nodes and report unknown (== not-authorized) nodes. # If a node doesn't contain the 'name' key, validation of inputs reports it. # That means we don't report missing names but cannot rely on them being # present either. ( target_report_list, new_nodes_target_list, ) = target_factory.get_target_list_with_reports( [node["name"] for node in new_nodes if "name" in node], allow_skip=False, ) report_processor.report_list(target_report_list) # Set default values for not-specified node options. # Use an address defined in known-hosts for each node with no addresses # specified. This allows users not to specify node addresses at all which # simplifies the whole node add command / form significantly. new_nodes_target_dict = { target.label: target for target in new_nodes_target_list } addrs_defaulter = _get_addrs_defaulter( report_processor, new_nodes_target_dict ) new_nodes_defaulters = {"addrs": addrs_defaulter} if is_sbd_enabled: watchdog_defaulter = _get_watchdog_defaulter( report_processor, new_nodes_target_dict ) new_nodes_defaulters["devices"] = lambda _: [] new_nodes_defaulters["watchdog"] = watchdog_defaulter new_nodes = [ _set_defaults_in_dict(node, new_nodes_defaulters) for node in new_nodes ] new_nodes_dict = { node["name"]: node for node in new_nodes if "name" in node } # Validate inputs - node options names # We do not want to make corosync validators know about SBD options and # vice versa. Therefore corosync and SBD validators get only valid corosync # and SBD options respectively, and we need to check for any surplus # options here. report_processor.report_list( validate.NamesIn( corosync_node_options | sbd_node_options, option_type="node" ).validate( { # Get a dict containing options of all nodes. Values don't # matter for validate.NamesIn validator. option_name: "" for node_option_names in [node.keys() for node in new_nodes] for option_name in node_option_names } ) ) # Validate inputs - corosync part try: cib = env.get_cib() cib_nodes = get_remote_nodes(cib) + get_guest_nodes(cib) except LibraryError: cib_nodes = [] report_processor.report( ReportItem( reports.item.get_severity( report_codes.FORCE_LOAD_NODES_FROM_CIB, force ), reports.messages.CibLoadErrorGetNodesForValidation(), ) ) # corosync validator rejects non-corosync keys new_nodes_corosync = [ {key: node[key] for key in corosync_node_options if key in node} for node in new_nodes ] report_processor.report_list( config_validators.add_nodes( new_nodes_corosync, corosync_conf.get_nodes(), cib_nodes, force_unresolvable=force, ) ) # Validate inputs - SBD part if is_sbd_enabled: report_processor.report_list( sbd.validate_new_nodes_devices( { node["name"]: node["devices"] for node in new_nodes if "name" in node } ) ) else: for node in new_nodes: sbd_options = sbd_node_options.intersection(node.keys()) if sbd_options and "name" in node: report_processor.report( ReportItem.error( reports.messages.SbdNotUsedCannotSetSbdOptions( sorted(sbd_options), node["name"] ) ) ) # Validate inputs - flags part wait_timeout = _get_validated_wait_timeout(report_processor, wait, start) # Get online cluster nodes # This is the only call in which we accept skip_offline_nodes option for the # cluster nodes. In all the other actions we communicate only with the # online nodes. This allows us to simplify code as any communication issue # is considered an error, ends the command processing and is not possible # to skip it by skip_offline_nodes. We do not have to care about a situation # when a communication command cannot connect to some nodes and then the # next command can connect but fails due to the previous one did not # succeed. online_cluster_target_list = [] if cluster_nodes_target_list: com_cmd: AllSameDataMixin = GetOnlineTargets( report_processor, ignore_offline_targets=skip_offline_nodes, ) com_cmd.set_targets(cluster_nodes_target_list) online_cluster_target_list = run_com( env.get_node_communicator(), com_cmd ) offline_cluster_target_list = [ target for target in cluster_nodes_target_list if target not in online_cluster_target_list ] if not online_cluster_target_list: report_processor.report( ReportItem.error( reports.messages.UnableToPerformOperationOnAnyNode() ) ) elif offline_cluster_target_list and skip_offline_nodes: # TODO: report (warn) how to fix offline nodes when they come online # report_processor.report(None) pass # Validate existing cluster nodes status atb_has_to_be_enabled = sbd.atb_has_to_be_enabled( env.service_manager, corosync_conf, len(new_nodes) ) if atb_has_to_be_enabled: report_processor.report( ReportItem.warning( reports.messages.CorosyncQuorumAtbWillBeEnabledDueToSbd() ) ) if online_cluster_target_list: com_cmd = CheckCorosyncOffline( report_processor, allow_skip_offline=False, ) com_cmd.set_targets(online_cluster_target_list) run_com(env.get_node_communicator(), com_cmd) # Validate new nodes. All new nodes have to be online. com_cmd = GetHostInfo(report_processor) com_cmd.set_targets(new_nodes_target_list) report_processor.report_list( _host_check_cluster_setup( run_com(env.get_node_communicator(), com_cmd), force, # version of services may not be the same across the existing # cluster nodes, so it's not easy to make this check properly check_services_versions=False, ) ) # Validate SBD on new nodes if is_sbd_enabled: if no_watchdog_validation: report_processor.report( ReportItem.warning( reports.messages.SbdWatchdogValidationInactive() ) ) com_cmd_sbd = CheckSbd(report_processor) for new_node_target in new_nodes_target_list: new_node = new_nodes_dict[new_node_target.label] # Do not send watchdog if validation is turned off. Listing of # available watchdogs in pcsd may restart the machine in some # corner cases. # pylint: disable=unexpected-keyword-arg com_cmd_sbd.add_request( new_node_target, watchdog="" if no_watchdog_validation else new_node["watchdog"], device_list=new_node["devices"], ) run_com(env.get_node_communicator(), com_cmd_sbd) # If there is an error reading the file, this will report it and exit # safely before any change is made to the nodes. sync_ssl_certs = _is_ssl_cert_sync_enabled(report_processor) if report_processor.has_errors: raise LibraryError() # Validation done. If errors occured, an exception has been raised and we # don't get below this line. # First set up everything else than corosync. Once the new nodes are present # in corosync.conf, they're considered part of a cluster and the node add # command cannot be run again. So we need to minimize the amout of actions # (and therefore possible failures) after adding the nodes to corosync. # distribute auth tokens of all cluster nodes (including the new ones) to # all new nodes com_cmd = UpdateKnownHosts( env.report_processor, known_hosts_to_add=env.get_known_hosts( cluster_nodes_names + list(new_nodes_dict.keys()) ), known_hosts_to_remove=[], ) com_cmd.set_targets(new_nodes_target_list) run_and_raise(env.get_node_communicator(), com_cmd) # qdevice setup if qdevice_model == "net": qdevice_net.set_up_client_certificates( env.cmd_runner(), env.report_processor, env.communicator_factory, qnetd_target, corosync_conf.get_cluster_name(), new_nodes_target_list, # we don't want to allow skiping offline nodes which are being # added, otherwise qdevice will not work properly skip_offline_nodes=False, allow_skip_offline=False, ) # sbd setup if is_sbd_enabled: sbd_cfg = environment_file_to_dict(sbd.get_local_sbd_config()) com_cmd_sbd_cfg = SetSbdConfig(env.report_processor) for new_node_target in new_nodes_target_list: new_node = new_nodes_dict[new_node_target.label] # pylint: disable=too-many-function-args com_cmd_sbd_cfg.add_request( new_node_target, sbd.create_sbd_config( sbd_cfg, new_node["name"], watchdog=new_node["watchdog"], device_list=new_node["devices"], ), ) run_and_raise(env.get_node_communicator(), com_cmd_sbd_cfg) com_cmd = EnableSbdService(env.report_processor) com_cmd.set_targets(new_nodes_target_list) run_and_raise(env.get_node_communicator(), com_cmd) else: com_cmd = DisableSbdService(env.report_processor) com_cmd.set_targets(new_nodes_target_list) run_and_raise(env.get_node_communicator(), com_cmd) # booth setup booth_sync.send_all_config_to_node( env.get_node_communicator(), env.report_processor, new_nodes_target_list, rewrite_existing=force, skip_wrong_config=force, ) # distribute corosync and pacemaker authkeys and other config files files_action = {} severity = reports.item.get_severity( reports.codes.SKIP_FILE_DISTRIBUTION_ERRORS, force ) if os.path.isfile(settings.corosync_authkey_file): try: files_action.update( node_communication_format.corosync_authkey_file( open(settings.corosync_authkey_file, "rb").read() ) ) except EnvironmentError as e: report_processor.report( ReportItem( severity, reports.messages.FileIoError( file_type_codes.COROSYNC_AUTHKEY, RawFileError.ACTION_READ, format_environment_error(e), file_path=settings.corosync_authkey_file, ), ) ) if os.path.isfile(settings.pacemaker_authkey_file): try: files_action.update( node_communication_format.pcmk_authkey_file( open(settings.pacemaker_authkey_file, "rb").read() ) ) except EnvironmentError as e: report_processor.report( ReportItem( severity, reports.messages.FileIoError( file_type_codes.PACEMAKER_AUTHKEY, RawFileError.ACTION_READ, format_environment_error(e), file_path=settings.pacemaker_authkey_file, ), ) ) if os.path.isfile(settings.pcsd_dr_config_location): try: files_action.update( node_communication_format.pcs_dr_config_file( open(settings.pcsd_dr_config_location, "rb").read() ) ) except EnvironmentError as e: report_processor.report( ReportItem( severity, reports.messages.FileIoError( file_type_codes.PCS_DR_CONFIG, RawFileError.ACTION_READ, format_environment_error(e), file_path=settings.pcsd_dr_config_location, ), ) ) # pcs_settings.conf was previously synced using pcsdcli send_local_configs. # This has been changed temporarily until new system for distribution and # syncronization of configs will be introduced. if os.path.isfile(settings.pcsd_settings_conf_location): try: files_action.update( node_communication_format.pcs_settings_conf_file( open(settings.pcsd_settings_conf_location, "r").read() ) ) except EnvironmentError as e: report_processor.report( ReportItem( severity, reports.messages.FileIoError( file_type_codes.PCS_SETTINGS_CONF, RawFileError.ACTION_READ, format_environment_error(e), file_path=settings.pcsd_settings_conf_location, ), ) ) # stop here if one of the files could not be loaded and it was not forced if report_processor.has_errors: raise LibraryError() if files_action: com_cmd = DistributeFilesWithoutForces( env.report_processor, files_action ) com_cmd.set_targets(new_nodes_target_list) run_and_raise(env.get_node_communicator(), com_cmd) # Distribute and reload pcsd SSL certificate if sync_ssl_certs: report_processor.report( ReportItem.info( reports.messages.PcsdSslCertAndKeyDistributionStarted( sorted([target.label for target in new_nodes_target_list]) ) ) ) try: with open(settings.pcsd_cert_location, "r") as file: ssl_cert = file.read() except EnvironmentError as e: report_processor.report( ReportItem.error( reports.messages.FileIoError( file_type_codes.PCSD_SSL_CERT, RawFileError.ACTION_READ, format_environment_error(e), file_path=settings.pcsd_cert_location, ) ) ) try: with open(settings.pcsd_key_location, "r") as file: ssl_key = file.read() except EnvironmentError as e: report_processor.report( ReportItem.error( reports.messages.FileIoError( file_type_codes.PCSD_SSL_KEY, RawFileError.ACTION_READ, format_environment_error(e), file_path=settings.pcsd_key_location, ) ) ) if report_processor.has_errors: raise LibraryError() com_cmd = SendPcsdSslCertAndKey(env.report_processor, ssl_cert, ssl_key) com_cmd.set_targets(new_nodes_target_list) run_and_raise(env.get_node_communicator(), com_cmd) # When corosync >= 2 is in use, the procedure for adding a node is: # 1. add the new node to corosync.conf on all existing nodes # 2. reload corosync.conf before the new node is started # 3. start the new node # If done otherwise, membership gets broken and qdevice hangs. Cluster # will recover after a minute or so but still it's a wrong way. corosync_conf.add_nodes(new_nodes_corosync) if atb_has_to_be_enabled: corosync_conf.set_quorum_options(dict(auto_tie_breaker="1")) _verify_corosync_conf(corosync_conf) # raises if corosync not valid com_cmd = DistributeCorosyncConf( env.report_processor, corosync_conf.config.export(), allow_skip_offline=False, ) com_cmd.set_targets(online_cluster_target_list + new_nodes_target_list) run_and_raise(env.get_node_communicator(), com_cmd) com_cmd = ReloadCorosyncConf(env.report_processor) com_cmd.set_targets(online_cluster_target_list) run_and_raise(env.get_node_communicator(), com_cmd) # Optionally enable and start cluster services. if enable: com_cmd = EnableCluster(env.report_processor) com_cmd.set_targets(new_nodes_target_list) run_and_raise(env.get_node_communicator(), com_cmd) if start: _start_cluster( env.communicator_factory, env.report_processor, new_nodes_target_list, wait_timeout=wait_timeout, ) def _ensure_live_env(env: LibraryEnvironment): not_live = [] if not env.is_cib_live: not_live.append(file_type_codes.CIB) if not env.is_corosync_conf_live: not_live.append(file_type_codes.COROSYNC_CONF) if not_live: raise LibraryError( ReportItem.error(reports.messages.LiveEnvironmentRequired(not_live)) ) def _start_cluster( communicator_factory, report_processor: ReportProcessor, target_list, wait_timeout=False, ): # Large clusters take longer time to start up. So we make the timeout # longer for each 8 nodes: # 1 - 8 nodes: 1 * timeout # 9 - 16 nodes: 2 * timeout # 17 - 24 nodes: 3 * timeout # and so on ... # Users can override this and set their own timeout by specifying # the --request-timeout option. timeout = int( settings.default_request_timeout * math.ceil(len(target_list) / 8.0) ) com_cmd = StartCluster(report_processor) com_cmd.set_targets(target_list) run_and_raise( communicator_factory.get_communicator(request_timeout=timeout), com_cmd ) if wait_timeout is not False: if report_processor.report_list( _wait_for_pacemaker_to_start( communicator_factory.get_communicator(), report_processor, target_list, # wait_timeout is either None or a timeout timeout=wait_timeout, ) ).has_errors: raise LibraryError() def _wait_for_pacemaker_to_start( node_communicator, report_processor: ReportProcessor, target_list, timeout=None, ): timeout = 60 * 15 if timeout is None else timeout interval = 2 stop_at = time.time() + timeout report_processor.report( ReportItem.info( reports.messages.WaitForNodeStartupStarted( sorted([target.label for target in target_list]) ) ) ) error_report_list = [] has_errors = False while target_list: if time.time() > stop_at: error_report_list.append( ReportItem.error(reports.messages.WaitForNodeStartupTimedOut()) ) break time.sleep(interval) com_cmd = CheckPacemakerStarted(report_processor) com_cmd.set_targets(target_list) target_list = run_com(node_communicator, com_cmd) has_errors = has_errors or com_cmd.has_errors if error_report_list or has_errors: error_report_list.append( ReportItem.error(reports.messages.WaitForNodeStartupError()) ) return error_report_list def _host_check_cluster_setup( host_info_dict, force, check_services_versions=True ): # pylint: disable=too-many-locals report_list = [] # We only care about services which matter for creating a cluster. It does # not make sense to check e.g. booth when a) it will never be used b) it # will be used in a year - which means we should do the check in a year. service_version_dict = { "pacemaker": {}, "corosync": {}, "pcsd": {}, } required_service_list = ["pacemaker", "corosync"] required_as_stopped_service_list = required_service_list + [ "pacemaker_remote" ] severity = reports.item.get_severity( report_codes.FORCE_ALREADY_IN_CLUSTER, force ) cluster_exists_on_nodes = False for host_name, host_info in host_info_dict.items(): try: services = host_info["services"] if check_services_versions: for service, version_dict in service_version_dict.items(): version_dict[host_name] = services[service]["version"] missing_service_list = [ service for service in required_service_list if not services[service]["installed"] ] if missing_service_list: report_list.append( ReportItem.error( reports.messages.ServiceNotInstalled( host_name, sorted(missing_service_list) ) ) ) cannot_be_running_service_list = [ service for service in required_as_stopped_service_list if service in services and services[service]["running"] ] if cannot_be_running_service_list: cluster_exists_on_nodes = True report_list.append( ReportItem( severity=severity, message=reports.messages.HostAlreadyInClusterServices( host_name, sorted(cannot_be_running_service_list), ), ) ) if host_info["cluster_configuration_exists"]: cluster_exists_on_nodes = True report_list.append( ReportItem( severity=severity, message=reports.messages.HostAlreadyInClusterConfig( host_name, ), ) ) except KeyError: report_list.append( ReportItem.error( reports.messages.InvalidResponseFormat(host_name) ) ) if check_services_versions: for service, version_dict in service_version_dict.items(): report_list.extend( _check_for_not_matching_service_versions(service, version_dict) ) if cluster_exists_on_nodes and not force: # This is always a forceable error report_list.append( ReportItem( severity=reports.item.ReportItemSeverity.error( report_codes.FORCE_ALREADY_IN_CLUSTER ), message=reports.messages.ClusterWillBeDestroyed(), ) ) return report_list def _check_for_not_matching_service_versions(service, service_version_dict): if len(set(service_version_dict.values())) <= 1: return [] return [ ReportItem.error( reports.messages.ServiceVersionMismatch( service, service_version_dict ) ) ] def _normalize_dict(input_dict, required_keys): normalized = dict(input_dict) for key in required_keys: if key not in normalized: normalized[key] = None return normalized def _set_defaults_in_dict(input_dict, defaults): completed = dict(input_dict) for key, factory in defaults.items(): if completed[key] is None: completed[key] = factory(input_dict) return completed def _get_addrs_defaulter( report_processor: ReportProcessor, targets_dict, default_to_name_if_no_target: bool = False, ): def defaulter(node): if "name" not in node: return [] address_for_use = None target = targets_dict.get(node["name"]) if target: address_for_use = target.first_addr address_source = reports.const.DEFAULT_ADDRESS_SOURCE_KNOWN_HOSTS elif default_to_name_if_no_target: address_for_use = node["name"] address_source = reports.const.DEFAULT_ADDRESS_SOURCE_HOST_NAME if address_for_use: report_processor.report( ReportItem.info( reports.messages.UsingDefaultAddressForHost( node["name"], address_for_use, address_source ) ) ) return [address_for_use] return [] return defaulter def _get_watchdog_defaulter(report_processor: ReportProcessor, targets_dict): del targets_dict def defaulter(node): report_processor.report( ReportItem.info( reports.messages.UsingDefaultWatchdog( settings.sbd_watchdog_default, node["name"], ) ) ) return settings.sbd_watchdog_default return defaulter def _get_validated_wait_timeout(report_processor, wait, start): try: if wait is False: return False if not start: report_processor.report( ReportItem.error( reports.messages.WaitForNodeStartupWithoutStart() ) ) return get_valid_timeout_seconds(wait) except LibraryError as e: report_processor.report_list(e.args) return None def _is_ssl_cert_sync_enabled(report_processor: ReportProcessor): try: if os.path.isfile(settings.pcsd_config): with open(settings.pcsd_config, "r") as cfg_file: cfg = environment_file_to_dict(cfg_file.read()) return ( cfg.get("PCSD_SSL_CERT_SYNC_ENABLED", "false").lower() == "true" ) except EnvironmentError as e: report_processor.report( ReportItem.error( reports.messages.FileIoError( file_type_codes.PCSD_ENVIRONMENT_CONFIG, RawFileError.ACTION_READ, format_environment_error(e), file_path=settings.pcsd_config, ) ) ) return False def _verify_corosync_conf(corosync_conf_facade): # This is done in pcs.lib.env.LibraryEnvironment.push_corosync_conf # usually. But there are special cases here which use custom corosync.conf # pushing so the check must be done individually. ( bad_sections, bad_attr_names, bad_attr_values, ) = config_parser.verify_section(corosync_conf_facade.config) if bad_sections or bad_attr_names or bad_attr_values: raise LibraryError( ReportItem.error( reports.messages.CorosyncConfigCannotSaveInvalidNamesValues( bad_sections, bad_attr_names, bad_attr_values, ) ) ) def remove_nodes( env: LibraryEnvironment, node_list, force_flags: Container[reports.types.ForceCode] = (), ): # pylint: disable=too-many-locals, too-many-branches, too-many-statements """ Remove nodes from a cluster. env LibraryEnvironment node_list iterable -- names of nodes to remove force_flags list -- list of flags codes """ _ensure_live_env(env) # raises if env is not live force_quorum_loss = report_codes.FORCE in force_flags skip_offline = report_codes.SKIP_OFFLINE_NODES in force_flags report_processor = env.report_processor target_factory = env.get_node_target_factory() corosync_conf = env.get_corosync_conf() # validations cluster_nodes_names, report_list = get_existing_nodes_names( corosync_conf, # Pcs is unable to communicate with nodes missing names. It cannot send # new corosync.conf to them. That might break the cluster. Hence we # error out. error_on_missing_name=True, ) report_processor.report_list(report_list) report_processor.report_list( config_validators.remove_nodes( node_list, corosync_conf.get_nodes(), corosync_conf.get_quorum_device_settings(), ) ) if report_processor.has_errors: # If there is an error, there is usually not much sense in doing other # validations: # - if there would be no node left in the cluster, it's pointless # to check for quorum loss or if at least one remaining node is online # - if only one node is being removed and it doesn't exist, it's again # pointless to check for other issues raise LibraryError() ( target_report_list, cluster_nodes_target_list, ) = target_factory.get_target_list_with_reports( cluster_nodes_names, skip_non_existing=skip_offline, ) known_nodes = {target.label for target in cluster_nodes_target_list} unknown_nodes = { name for name in cluster_nodes_names if name not in known_nodes } report_processor.report_list(target_report_list) com_cmd: AllSameDataMixin = GetOnlineTargets( report_processor, ignore_offline_targets=skip_offline, ) com_cmd.set_targets(cluster_nodes_target_list) online_target_list = run_com(env.get_node_communicator(), com_cmd) offline_target_list = [ target for target in cluster_nodes_target_list if target not in online_target_list ] staying_online_target_list = [ target for target in online_target_list if target.label not in node_list ] targets_to_remove = [ target for target in cluster_nodes_target_list if target.label in node_list ] if not staying_online_target_list: report_processor.report( ReportItem.error( reports.messages.UnableToConnectToAnyRemainingNode() ) ) # If no remaining node is online, there is no point in checking quorum # loss or anything as we would just get errors. raise LibraryError() if skip_offline: staying_offline_nodes = [ target.label for target in offline_target_list if target.label not in node_list ] + [name for name in unknown_nodes if name not in node_list] if staying_offline_nodes: report_processor.report( ReportItem.warning( reports.messages.UnableToConnectToAllRemainingNodes( sorted(staying_offline_nodes) ) ) ) atb_has_to_be_enabled = sbd.atb_has_to_be_enabled( env.service_manager, corosync_conf, -len(node_list) ) if atb_has_to_be_enabled: report_processor.report( ReportItem.warning( reports.messages.CorosyncQuorumAtbWillBeEnabledDueToSbd() ) ) com_cmd = CheckCorosyncOffline( report_processor, allow_skip_offline=False, ) com_cmd.set_targets(staying_online_target_list) run_com(env.get_node_communicator(), com_cmd) else: # Check if removing the nodes would cause quorum loss. We ask the nodes # to be removed for their view of quorum. If they are all stopped or # not in a quorate partition, their removal cannot cause quorum loss. # That's why we ask them and not the remaining nodes. # example: 5-node cluster, 3 online nodes, removing one online node, # results in 4-node cluster with 2 online nodes => quorum lost # Check quorum loss only if ATB does not need to be enabled. If it is # required, cluster has to be turned off and therefore it loses quorum. com_cmd = cluster.GetQuorumStatus(report_processor) com_cmd.set_targets(targets_to_remove) failures, quorum_status = run_com(env.get_node_communicator(), com_cmd) if quorum_status: if quorum_status.stopping_nodes_cause_quorum_loss(node_list): report_processor.report( ReportItem( severity=reports.item.get_severity( report_codes.FORCE_QUORUM_LOSS, force_quorum_loss, ), message=reports.messages.CorosyncQuorumWillBeLost(), ) ) elif failures or not targets_to_remove: report_processor.report( ReportItem( severity=reports.item.get_severity( report_codes.FORCE_QUORUM_LOSS, force_quorum_loss, ), message=reports.messages.CorosyncQuorumLossUnableToCheck(), ) ) if report_processor.has_errors: raise LibraryError() # validations done unknown_to_remove = [name for name in unknown_nodes if name in node_list] if unknown_to_remove: report_processor.report( ReportItem.warning( reports.messages.NodesToRemoveUnreachable( sorted(unknown_to_remove) ) ) ) if targets_to_remove: com_cmd = cluster.DestroyWarnOnFailure(report_processor) com_cmd.set_targets(targets_to_remove) run_and_raise(env.get_node_communicator(), com_cmd) corosync_conf.remove_nodes(node_list) if atb_has_to_be_enabled: corosync_conf.set_quorum_options(dict(auto_tie_breaker="1")) _verify_corosync_conf(corosync_conf) # raises if corosync not valid com_cmd = DistributeCorosyncConf( env.report_processor, corosync_conf.config.export(), allow_skip_offline=False, ) com_cmd.set_targets(staying_online_target_list) run_and_raise(env.get_node_communicator(), com_cmd) com_cmd = ReloadCorosyncConf(env.report_processor) com_cmd.set_targets(staying_online_target_list) run_and_raise(env.get_node_communicator(), com_cmd) # try to remove nodes from pcmk using crm_node -R <node> --force and if not # successful remove it directly from CIB file on all nodes in parallel com_cmd = RemoveNodesFromCib(env.report_processor, node_list) com_cmd.set_targets(staying_online_target_list) run_and_raise(env.get_node_communicator(), com_cmd) def remove_nodes_from_cib(env: LibraryEnvironment, node_list): """ Remove specified nodes from CIB. When pcmk is running 'crm_node -R <node>' will be used. Otherwise nodes will be removed directly from CIB file. env LibraryEnvironment node_list iterable -- names of nodes to remove """ # TODO: more advanced error handling if not env.is_cib_live: raise LibraryError( ReportItem.error( reports.messages.LiveEnvironmentRequired([file_type_codes.CIB]) ) ) if env.service_manager.is_running("pacemaker"): for node in node_list: # this may raise a LibraryError # NOTE: crm_node cannot remove multiple nodes at once remove_node(env.cmd_runner(), node) return # TODO: We need to remove nodes from the CIB file. We don't want to do it # using environment as this is a special case in which we have to edit CIB # file directly. for node in node_list: stdout, stderr, retval = env.cmd_runner().run( [ settings.cibadmin, "--delete-all", "--force", f"--xpath=/cib/configuration/nodes/node[@uname='{node}']", ], env_extend={"CIB_file": os.path.join(settings.cib_dir, "cib.xml")}, ) if retval != 0: raise LibraryError( ReportItem.error( reports.messages.NodeRemoveInPacemakerFailed( node_list_to_remove=[node], reason=join_multilines([stderr, stdout]), ) ) ) def add_link( env: LibraryEnvironment, node_addr_map, link_options=None, force_flags: Container[reports.types.ForceCode] = (), ): """ Add a corosync link to a cluster env LibraryEnvironment dict node_addr_map -- key: node name, value: node address for the link dict link_options -- link options force_flags list -- list of flags codes """ _ensure_live_env(env) # raises if env is not live link_options = link_options or dict() force = report_codes.FORCE in force_flags skip_offline = report_codes.SKIP_OFFLINE_NODES in force_flags report_processor = env.report_processor corosync_conf = env.get_corosync_conf() # validations dummy_cluster_nodes_names, nodes_report_list = get_existing_nodes_names( corosync_conf, # New link addresses are assigned to nodes based on node names. If # there are nodes with no names, we cannot assign them new link # addresses. This is a no-go situation. error_on_missing_name=True, ) report_processor.report_list(nodes_report_list) try: cib = env.get_cib() cib_nodes = get_remote_nodes(cib) + get_guest_nodes(cib) except LibraryError: cib_nodes = [] report_processor.report( ReportItem( reports.item.get_severity( report_codes.FORCE_LOAD_NODES_FROM_CIB, force ), reports.messages.CibLoadErrorGetNodesForValidation(), ) ) report_processor.report_list( config_validators.add_link( node_addr_map, link_options, corosync_conf.get_nodes(), cib_nodes, corosync_conf.get_used_linknumber_list(), corosync_conf.get_transport(), corosync_conf.get_ip_version(), force_unresolvable=force, ) ) if report_processor.has_errors: raise LibraryError() # validations done corosync_conf.add_link(node_addr_map, link_options) env.push_corosync_conf(corosync_conf, skip_offline) def remove_links( env: LibraryEnvironment, linknumber_list, force_flags: Container[reports.types.ForceCode] = (), ): """ Remove corosync links from a cluster env LibraryEnvironment iterable linknumber_list -- linknumbers (as strings) of links to be removed force_flags list -- list of flags codes """ # TODO library interface should make sure linknumber_list is an iterable of # strings. The layer in which the check should be done does not exist yet. _ensure_live_env(env) # raises if env is not live skip_offline = report_codes.SKIP_OFFLINE_NODES in force_flags report_processor = env.report_processor corosync_conf = env.get_corosync_conf() # validations report_processor.report_list( config_validators.remove_links( linknumber_list, corosync_conf.get_used_linknumber_list(), corosync_conf.get_transport(), ) ) if report_processor.has_errors: raise LibraryError() # validations done corosync_conf.remove_links(linknumber_list) env.push_corosync_conf(corosync_conf, skip_offline) def update_link( env: LibraryEnvironment, linknumber, node_addr_map=None, link_options=None, force_flags: Container[reports.types.ForceCode] = (), ): """ Change an existing corosync link env LibraryEnvironment string linknumber -- the link to be changed dict node_addr_map -- key: node name, value: node address for the link dict link_options -- link options force_flags list -- list of flags codes """ _ensure_live_env(env) # raises if env is not live node_addr_map = node_addr_map or dict() link_options = link_options or dict() force = report_codes.FORCE in force_flags skip_offline = report_codes.SKIP_OFFLINE_NODES in force_flags report_processor = env.report_processor corosync_conf = env.get_corosync_conf() # validations dummy_cluster_nodes_names, nodes_report_list = get_existing_nodes_names( corosync_conf, # Pcs is unable to communicate with nodes missing names. It cannot send # new corosync.conf to them. That might break the cluster. Hence we # error out. # This check is done later as well, when sending corosync.conf to # nodes. But we need node names to be present so we can set new # addresses to them. We may as well do the check right now. error_on_missing_name=True, ) report_processor.report_list(nodes_report_list) report_processor.report_list( config_validators.update_link( linknumber, node_addr_map, link_options, corosync_conf.get_links_options().get(linknumber, {}), corosync_conf.get_nodes(), # cluster must be stopped for updating a link and then we cannot get # nodes from CIB [], corosync_conf.get_used_linknumber_list(), corosync_conf.get_transport(), corosync_conf.get_ip_version(), force_unresolvable=force, ) ) if report_processor.has_errors: raise LibraryError() # validations done corosync_conf.update_link(linknumber, node_addr_map, link_options) env.push_corosync_conf(corosync_conf, skip_offline) def corosync_authkey_change( env: LibraryEnvironment, corosync_authkey: Optional[bytes] = None, force_flags: Container[reports.types.ForceCode] = (), ) -> None: """ Distribute new corosync authkey to all cluster nodes. env -- LibraryEnvironment corosync_authkey -- new authkey; if None, generate a random one force_flags -- list of flags codes """ report_processor = env.report_processor target_factory = env.get_node_target_factory() cluster_nodes_names, nodes_report_list = get_existing_nodes_names( env.get_corosync_conf(), error_on_missing_name=True, ) report_processor.report_list(nodes_report_list) ( target_report_list, cluster_nodes_target_list, ) = target_factory.get_target_list_with_reports( cluster_nodes_names, allow_skip=False, ) report_processor.report_list(target_report_list) if corosync_authkey is not None: if len(corosync_authkey) != settings.corosync_authkey_bytes: report_processor.report( ReportItem( severity=reports.item.get_severity( report_codes.FORCE, report_codes.FORCE in force_flags, ), message=reports.messages.CorosyncAuthkeyWrongLength( len(corosync_authkey), settings.corosync_authkey_bytes, settings.corosync_authkey_bytes, ), ) ) else: corosync_authkey = generate_binary_key( random_bytes_count=settings.corosync_authkey_bytes ) if report_processor.has_errors: raise LibraryError() com_cmd: AllSameDataMixin = GetOnlineTargets( report_processor, ignore_offline_targets=report_codes.SKIP_OFFLINE_NODES in force_flags, ) com_cmd.set_targets(cluster_nodes_target_list) online_cluster_target_list = run_and_raise( env.get_node_communicator(), com_cmd ) if not online_cluster_target_list: if report_processor.report( ReportItem.error( reports.messages.UnableToPerformOperationOnAnyNode() ) ).has_errors: raise LibraryError() com_cmd = DistributeFilesWithoutForces( env.report_processor, node_communication_format.corosync_authkey_file(corosync_authkey), ) com_cmd.set_targets(online_cluster_target_list) run_and_raise(env.get_node_communicator(), com_cmd) com_cmd = ReloadCorosyncConf(env.report_processor) com_cmd.set_targets(online_cluster_target_list) run_and_raise(env.get_node_communicator(), com_cmd)
gpl-2.0
5,267,389,758,631,492,000
34.200733
80
0.611421
false
hbhzwj/imalse
tools/ns-allinone-3.14.1/pybindgen-0.15.0.809/pybindgen/typehandlers/inttype.py
2
29713
# docstrings not needed here (the type handler interfaces are fully # documented in base.py) # pylint: disable-msg=C0111 import struct assert struct.calcsize('i') == 4 # assumption is made that sizeof(int) == 4 for all platforms pybindgen runs on from base import ReturnValue, Parameter, PointerParameter, PointerReturnValue, \ ReverseWrapperBase, ForwardWrapperBase, TypeConfigurationError, NotSupportedError class IntParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['int', 'int32_t'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('i', [self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable(self.ctype_no_const, self.name, self.default_value) wrapper.parse_params.add_parameter('i', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.call_params.append(name) class UnsignedIntParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['unsigned int', 'uint32_t'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('N', ["PyLong_FromUnsignedLong(%s)" % self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable('unsigned int', self.name, self.default_value) wrapper.parse_params.add_parameter('I', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.call_params.append(name) class UnsignedIntPtrParam(PointerParameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_OUT, Parameter.DIRECTION_INOUT] CTYPES = ['unsigned int*', 'uint32_t*'] def __init__(self, ctype, name, direction=Parameter.DIRECTION_IN, is_const=False, default_value=None, transfer_ownership=False, array_length=None): super(UnsignedIntPtrParam, self).__init__(ctype, name, direction, is_const, default_value, transfer_ownership) self.array_length = array_length if transfer_ownership: raise NotSupportedError("%s: transfer_ownership=True not yet implemented." % ctype) def convert_c_to_python(self, wrapper): if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('I', ['*'+self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter('I', [self.value], self.name) def convert_python_to_c(self, wrapper): #assert self.ctype == 'unsigned int*' if self.array_length is None: name = wrapper.declarations.declare_variable(str(self.type_traits.target), self.name) wrapper.call_params.append('&'+name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('I', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter('I', [name]) else: # complicated code path to deal with arrays... name = wrapper.declarations.declare_variable(str(self.type_traits.target), self.name, array="[%i]" % self.array_length) py_list = wrapper.declarations.declare_variable("PyObject*", "py_list") idx = wrapper.declarations.declare_variable("int", "idx") wrapper.call_params.append(name) if self.direction & self.DIRECTION_IN: elem = wrapper.declarations.declare_variable("PyObject*", "element") wrapper.parse_params.add_parameter('O!', ['&PyList_Type', '&'+py_list], self.name) wrapper.before_call.write_error_check( 'PyList_Size(%s) != %i' % (py_list, self.array_length), 'PyErr_SetString(PyExc_TypeError, "Parameter `%s\' must be a list of %i ints/longs");' % (self.name, self.array_length)) wrapper.before_call.write_code( "for (%s = 0; %s < %i; %s++) {" % (idx, idx, self.array_length, idx)) wrapper.before_call.indent() wrapper.before_call.write_code("%(elem)s = PyList_GET_ITEM(%(py_list)s, %(idx)s);" % vars()) wrapper.before_call.write_error_check( '!(PyInt_Check(%(elem)s) || PyLong_Check(%(elem)s))', 'PyErr_SetString(PyExc_TypeError, "Parameter `%s\' must be a list of %i ints / longs");' % (self.name, self.array_length)) wrapper.before_call.write_code("%(name)s[%(idx)s] = PyLong_AsUnsignedInt(%(elem)s);" % vars()) wrapper.before_call.unindent() wrapper.before_call.write_code('}') if self.direction & self.DIRECTION_OUT: wrapper.after_call.write_code("%s = PyList_New(%i);" % (py_list, self.array_length)) wrapper.after_call.write_code( "for (%s = 0; %s < %i; %s++) {" % (idx, idx, self.array_length, idx)) wrapper.after_call.indent() wrapper.after_call.write_code("PyList_SET_ITEM(%(py_list)s, %(idx)s, PyLong_FromUnsignedLong(%(name)s[%(idx)s]));" % vars()) wrapper.after_call.unindent() wrapper.after_call.write_code('}') wrapper.build_params.add_parameter("N", [py_list]) class IntReturn(ReturnValue): CTYPES = ['int', 'int32_t'] def get_c_error_return(self): return "return INT_MIN;" def convert_python_to_c(self, wrapper): wrapper.parse_params.add_parameter("i", ["&"+self.value], prepend=True) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("i", [self.value], prepend=True) class UnsignedIntReturn(ReturnValue): CTYPES = ['unsigned int', 'uint32_t'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): wrapper.parse_params.add_parameter("I", ["&"+self.value], prepend=True) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter('N', ["PyLong_FromUnsignedLong(%s)" % self.value], prepend=True) class IntPtrParam(PointerParameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_OUT, Parameter.DIRECTION_IN|Parameter.DIRECTION_OUT] CTYPES = ['int*'] def __init__(self, ctype, name, direction=None, is_const=None, transfer_ownership=None): if direction is None: if is_const: direction = Parameter.DIRECTION_IN else: raise TypeConfigurationError("direction not given") super(IntPtrParam, self).__init__(ctype, name, direction, is_const, transfer_ownership) def convert_c_to_python(self, wrapper): if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('i', ['*'+self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter("i", [self.value], self.name) def convert_python_to_c(self, wrapper): name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) wrapper.call_params.append('&'+name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('i', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("i", [name]) class IntRefParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_OUT, Parameter.DIRECTION_IN|Parameter.DIRECTION_OUT] CTYPES = ['int&'] def convert_c_to_python(self, wrapper): if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('i', [self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter("i", [self.value], self.name) def convert_python_to_c(self, wrapper): #assert self.ctype == 'int&' name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) wrapper.call_params.append(name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('i', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("i", [name]) class UnsignedIntRefParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_OUT, Parameter.DIRECTION_IN|Parameter.DIRECTION_OUT] CTYPES = ['unsigned int&', 'unsigned &'] def convert_c_to_python(self, wrapper): if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('I', [self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter("I", [self.value], self.name) def convert_python_to_c(self, wrapper): #assert self.ctype == 'int&' name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) wrapper.call_params.append(name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('I', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("I", [name]) class UInt16Return(ReturnValue): CTYPES = ['uint16_t', 'unsigned short', 'unsigned short int', 'short unsigned int'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): tmp_var = wrapper.declarations.declare_variable("int", "tmp") wrapper.parse_params.add_parameter("i", ["&"+tmp_var], prepend=True) wrapper.after_call.write_error_check('%s > 0xffff' % tmp_var, 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.after_call.write_code( "%s = %s;" % (self.value, tmp_var)) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("i", [self.value], prepend=True) class Int16Return(ReturnValue): CTYPES = ['int16_t', 'short', 'short int'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): tmp_var = wrapper.declarations.declare_variable("int", "tmp") wrapper.parse_params.add_parameter("i", ["&"+tmp_var], prepend=True) wrapper.after_call.write_error_check('%s > 32767 || %s < -32768' % (tmp_var, tmp_var), 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.after_call.write_code( "%s = %s;" % (self.value, tmp_var)) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("i", [self.value], prepend=True) class UInt16Param(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['uint16_t', 'unsigned short', 'unsigned short int'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('i', ["(int) "+self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable("int", self.name, self.default_value) wrapper.parse_params.add_parameter('i', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.before_call.write_error_check('%s > 0xffff' % name, 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.call_params.append(name) class UInt16RefParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_INOUT, Parameter.DIRECTION_OUT] CTYPES = ['uint16_t&', 'unsigned short&', 'unsigned short int&', 'short unsigned&', 'short unsigned int&'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('H', [self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter("H", [self.value], self.name) def convert_python_to_c(self, wrapper): name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) wrapper.call_params.append(name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('H', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("H", [name]) class Int16Param(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['int16_t', 'short', 'short int'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('i', ["(int) "+self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable("int", self.name, self.default_value) wrapper.parse_params.add_parameter('i', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.before_call.write_error_check('%s > 0x7fff' % name, 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.call_params.append(name) class Int16RefParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_INOUT, Parameter.DIRECTION_OUT] CTYPES = ['int16_t&', 'short&', 'short int&'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('h', [self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter("h", [self.value], self.name) def convert_python_to_c(self, wrapper): name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) wrapper.call_params.append(name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('h', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("h", [name]) class UInt8Param(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['uint8_t', 'unsigned char', 'char unsigned'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('i', ["(int) "+self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable("int", self.name, self.default_value) wrapper.parse_params.add_parameter('i', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.before_call.write_error_check('%s > 0xff' % name, 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.call_params.append(name) class UInt8RefParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_INOUT, Parameter.DIRECTION_OUT] CTYPES = ['uint8_t&', 'unsigned char&', 'char unsigned&'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('B', [self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter("B", [self.value], self.name) def convert_python_to_c(self, wrapper): name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) wrapper.call_params.append(name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('B', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("B", [name]) class UInt8Return(ReturnValue): CTYPES = ['uint8_t', 'unsigned char', 'char unsigned'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): tmp_var = wrapper.declarations.declare_variable("int", "tmp") wrapper.parse_params.add_parameter("i", ["&"+tmp_var], prepend=True) wrapper.after_call.write_error_check('%s > 0xff' % tmp_var, 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.after_call.write_code( "%s = %s;" % (self.value, tmp_var)) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("i", ['(int)' + self.value], prepend=True) class Int8Param(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['int8_t', 'signed char', 'char signed'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('i', ["(int) "+self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable("int", self.name, self.default_value) wrapper.parse_params.add_parameter('i', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.before_call.write_error_check('%s > 0x7f' % name, 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.call_params.append(name) class Int8RefParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_INOUT, Parameter.DIRECTION_OUT] CTYPES = ['int8_t&', 'signed char &', 'char signed&'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('b', [self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter("b", [self.value], self.name) def convert_python_to_c(self, wrapper): name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) wrapper.call_params.append(name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('b', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("b", [name]) class Int8Return(ReturnValue): CTYPES = ['int8_t', 'signed char'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): tmp_var = wrapper.declarations.declare_variable("int", "tmp") wrapper.parse_params.add_parameter("i", ["&"+tmp_var], prepend=True) wrapper.after_call.write_error_check('%s > 128 || %s < -127' % (tmp_var, tmp_var), 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.after_call.write_code( "%s = %s;" % (self.value, tmp_var)) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("i", [self.value], prepend=True) class UnsignedLongLongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['unsigned long long', 'uint64_t', 'unsigned long long int', 'long long unsigned int', 'long long unsigned'] def get_ctype_without_ref(self): return str(self.type_traits.ctype_no_const) def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('K', [self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable(self.get_ctype_without_ref(), self.name, self.default_value) wrapper.parse_params.add_parameter('K', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.call_params.append(name) class UnsignedLongLongRefParam(UnsignedLongLongParam): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['unsigned long long&', 'uint64_t&', 'long long unsigned int&'] def get_ctype_without_ref(self): assert self.type_traits.target is not None return str(self.type_traits.target) class UnsignedLongLongReturn(ReturnValue): CTYPES = ['unsigned long long', 'uint64_t', 'long long unsigned int'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): wrapper.parse_params.add_parameter("K", ["&"+self.value], prepend=True) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("K", [self.value], prepend=True) class UnsignedLongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['unsigned long', 'unsigned long int', 'long unsigned', 'long unsigned int'] def get_ctype_without_ref(self): return str(self.type_traits.ctype_no_const) def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('k', [self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable(self.get_ctype_without_ref(), self.name, self.default_value) wrapper.parse_params.add_parameter('k', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.call_params.append(name) class UnsignedLongRefParam(UnsignedLongParam): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['unsigned long&', 'long unsigned&', 'long unsigned int&', 'unsigned long int&'] def get_ctype_without_ref(self): assert self.type_traits.target is not None return str(self.type_traits.target) class UnsignedLongReturn(ReturnValue): CTYPES = ['unsigned long', 'long unsigned int'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): wrapper.parse_params.add_parameter("k", ["&"+self.value], prepend=True) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("k", [self.value], prepend=True) class LongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['signed long', 'signed long int', 'long', 'long int', 'long signed', 'long signed int'] def get_ctype_without_ref(self): return str(self.type_traits.ctype_no_const) def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('l', [self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable(self.get_ctype_without_ref(), self.name, self.default_value) wrapper.parse_params.add_parameter('l', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.call_params.append(name) class LongRefParam(LongParam): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['signed long&', 'long signed&', 'long&', 'long int&', 'long signed int&', 'signed long int&'] def get_ctype_without_ref(self): assert self.type_traits.target is not None return str(self.type_traits.target) class LongReturn(ReturnValue): CTYPES = ['signed long', 'long signed int', 'long', 'long int'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): wrapper.parse_params.add_parameter("l", ["&"+self.value], prepend=True) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("l", [self.value], prepend=True) class SizeTReturn(ReturnValue): CTYPES = ['size_t', 'std::size_t'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): # using the intermediate variable is not always necessary but # it's safer this way in case of weird platforms where # sizeof(size_t) != sizeof(unsigned PY_LONG_LONG). name = wrapper.declarations.declare_variable("unsigned PY_LONG_LONG", "retval_tmp", self.value) wrapper.parse_params.add_parameter("K", ["&"+name], prepend=True) wrapper.after_call.write_code("retval = %s;" % (name)) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("K", ["((unsigned PY_LONG_LONG) %s)" % self.value], prepend=True) class SizeTParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['size_t', 'std::size_t'] def get_ctype_without_ref(self): return str(self.type_traits.ctype_no_const) def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('K', ["((unsigned PY_LONG_LONG) %s)" % self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable("unsigned PY_LONG_LONG", self.name, self.default_value) wrapper.parse_params.add_parameter('K', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.call_params.append(name) class LongLongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['long long', 'int64_t', 'long long int'] def get_ctype_without_ref(self): return str(self.type_traits.ctype_no_const) def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('L', [self.value]) def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable(self.get_ctype_without_ref(), self.name, self.default_value) wrapper.parse_params.add_parameter('L', ['&'+name], self.name, optional=bool(self.default_value)) wrapper.call_params.append(name) class LongLongRefParam(LongLongParam): DIRECTIONS = [Parameter.DIRECTION_IN] # other directions not yet implemented CTYPES = ['long long&', 'int64_t&', 'long long int&'] def get_ctype_without_ref(self): assert self.type_traits.target is not None return str(self.type_traits.target) class LongLongReturn(ReturnValue): CTYPES = ['long long', 'int64_t', 'long long int'] def get_c_error_return(self): return "return 0;" def convert_python_to_c(self, wrapper): wrapper.parse_params.add_parameter("L", ["&"+self.value], prepend=True) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("L", [self.value], prepend=True) class Int8PtrParam(PointerParameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_OUT, Parameter.DIRECTION_IN|Parameter.DIRECTION_OUT] CTYPES = ['int8_t*'] def __init__(self, ctype, name, direction=None, is_const=None, default_value=None, transfer_ownership=None): if direction is None: if is_const: direction = Parameter.DIRECTION_IN else: raise TypeConfigurationError("direction not given") super(Int8PtrParam, self).__init__(ctype, name, direction, is_const, default_value, transfer_ownership) def convert_c_to_python(self, wrapper): if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('b', ['*'+self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter("b", [self.value], self.name) def convert_python_to_c(self, wrapper): name = wrapper.declarations.declare_variable('int8_t', self.name) wrapper.call_params.append('&'+name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('b', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("b", [name]) class UInt8PtrParam(PointerParameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_OUT, Parameter.DIRECTION_IN|Parameter.DIRECTION_OUT] CTYPES = ['uint8_t*'] def __init__(self, ctype, name, direction=None, is_const=None, default_value=None, transfer_ownership=None): if direction is None: if is_const: direction = Parameter.DIRECTION_IN else: raise TypeConfigurationError("direction not given") super(UInt8PtrParam, self).__init__(ctype, name, direction, is_const, default_value, transfer_ownership) def convert_c_to_python(self, wrapper): if self.direction & self.DIRECTION_IN: wrapper.build_params.add_parameter('B', ['*'+self.value]) if self.direction & self.DIRECTION_OUT: wrapper.parse_params.add_parameter("B", [self.value], self.name) def convert_python_to_c(self, wrapper): name = wrapper.declarations.declare_variable('uint8_t', self.name) wrapper.call_params.append('&'+name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('B', ['&'+name], self.name) if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("B", [name])
gpl-3.0
8,115,015,865,077,106,000
41.205966
131
0.638912
false
useher/geowork
tools/addresslocator/addresslocator.py
1
1871
#! /usr/bin/python3 import json import requests import psycopg2 from psycopg2.extras import RealDictCursor baseurl = 'https://nominatim.openstreetmap.org/search?q=' options = '&format=json&polygon=1&addressdetails=1&accept-language=de_DE' sql_in = '''select id, adresse as address, plz as zip, city from verknet2.dst_wsv where geom is null and '' <> any (Array[adresse, plz::text, city])''' sql_update = '''update verknet2.dst_wsv set (lon, lat, bemerkungen) = (%(lon)s, %(lat)s, %(bem)s) where id = %(id)s''' class AddressLocator: def __init__(self, **kwargs): self.baseurl = baseurl self.options = options def search(self, address, city=None, zipcode=None): searchstring = ',+'.join([address, str(zipcode), city]).strip().replace(' ', '+') r = requests.get(''.join([self.baseurl, searchstring, self.options])) return r.text def locate_db(self, sql_in, database='db', host='a.b.c.d', port=5432, user='user', password='********'): failed = 0 db = psycopg2.connect(database=database, host=host, port=port, user=user, password=password) cur = db.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute(sql_in) data = [] for item in cur: try: r = json.loads(self.search(item['address'], item['city'], item['zip']))[0] result = {'lat': r['lat'], 'lon': r['lon'], 'id': item['id'], 'bem': "'Koordinaten mit Locator aus OSM'"} except: failed += 1 result = {'lat': 47 + failed/10, 'lon': 9, 'id': item['id'], 'bem':"'keine Koordinaten ermittelt'"} print(sql_update%result) data.append(result) cur.executemany(sql_update,data) db.commit() if __name__ == '__main__': al = AddressLocator() al.locate_db(sql_in)
agpl-3.0
-6,187,216,106,307,920,000
37.183673
151
0.589524
false
jmckaskill/subversion
tools/examples/blame.py
3
3066
#!/usr/bin/env python # # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # # # # USAGE: blame.py [-r REV] repos-path file # import sys import os import getopt try: my_getopt = getopt.gnu_getopt except AttributeError: my_getopt = getopt.getopt import difflib from svn import fs, core, repos CHUNK_SIZE = 100000 def blame(path, filename, rev=None): annotresult = {} path = core.svn_path_canonicalize(path) repos_ptr = repos.open(path) fsob = repos.fs(repos_ptr) if rev is None: rev = fs.youngest_rev(fsob) filedata = '' for i in range(0, rev+1): root = fs.revision_root(fsob, i) if fs.check_path(root, filename) != core.svn_node_none: first = i break print("First revision is %d" % first) print("Last revision is %d" % rev) for i in range(first, rev+1): previousroot = root root = fs.revision_root(fsob, i) if i != first: if not fs.contents_changed(root, filename, previousroot, filename): continue file = fs.file_contents(root, filename) previousdata = filedata filedata = '' while True: data = core.svn_stream_read(file, CHUNK_SIZE) if not data: break filedata = filedata + data print("Current revision is %d" % i) diffresult = difflib.ndiff(previousdata.splitlines(1), filedata.splitlines(1)) # print ''.join(diffresult) k = 0 for j in diffresult: if j[0] == ' ': if k in annotresult: k = k + 1 continue else: annotresult[k] = (i, j[2:]) k = k + 1 continue elif j[0] == '?': continue annotresult[k] = (i, j[2:]) if j[0] != '-': k = k + 1 # print ''.join(diffresult) # print annotresult for x in range(len(annotresult.keys())): sys.stdout.write("Line %d (rev %d):%s" % (x, annotresult[x][0], annotresult[x][1])) def usage(): print("USAGE: blame.py [-r REV] repos-path file") sys.exit(1) def main(): opts, args = getopt.getopt(sys.argv[1:], 'r:') if len(args) != 2: usage() rev = None for name, value in opts: if name == '-r': rev = int(value) blame(args[0], args[1], rev) if __name__ == '__main__': main()
apache-2.0
4,808,622,163,557,248,000
26.132743
73
0.607306
false
davidsanfal/bii-ide
bii-ide/bii_ide/common/style/biigui_stylesheet.py
2
1159
button_style = '''QPushButton { border: 1px solid #C4C4C4; border-radius: 8px; padding: 2px; } QPushButton:hover { background: #C4C4C4; }''' editor_style = '''QTextEdit{ border: 1px solid #C4C4C4; border-radius: 4px; padding: 2px; }''' shell_style = '''QTextEdit{ min-width: 20%; border: 1px solid #C4C4C4; border-radius: 4px; padding: 2px; background-color: #000000; color: #ffffff; }''' browser_style = '''QWebView{ border: 1px solid #C4C4C4; border-radius: 4px; padding: 2px; }''' tab_style = ''' QTabWidget::pane { /* The tab widget frame */ border: 1px solid #C4C4C4; border-radius: 4px; position: absolute; top: -0.5em; } QTabBar::tab { background-color: #C4C4C4; border: 1px solid #C4C4C4; border-bottom-color: #C4C4C4; /* same as the pane color */ border-top-left-radius: 4px; border-top-right-radius: 4px; min-width: 30ex; } QTabBar::tab:selected, QTabBar::tab:hover { background-color: #fafafa; } QTabBar::tab:selected { background-color: #FFFFFF; border-bottom-color: #FFFFFF; }'''
mit
1,786,208,888,203,158,500
20.462963
63
0.601381
false
sony/nnabla
python/src/nnabla/utils/converter/commands.py
1
18172
# Copyright 2018,2019,2020,2021 Sony Corporation. # Copyright 2021 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import os import sys from .nnabla import NnpImporter, NnpExporter from .nnablart import NnbExporter, CsrcExporter from .utils import func_set_import_nnp, \ func_set_import_onnx_config, \ func_set_import_config, \ func_set_nnabla_support, \ func_set_onnx_support def _import_file(args, ifiles): if args.import_format == 'NNP': # Input file that has unsupported extension store into output nnp # archive or directory. return NnpImporter(*ifiles, expand_network=not args.nnp_no_expand_network, executor_index=args.nnp_import_executor_index).execute() elif args.import_format == 'ONNX': from .onnx import OnnxImporter return OnnxImporter(*ifiles).execute() elif args.import_format == 'TF_PB' or \ args.import_format == 'TF_CKPT_V1' or \ args.import_format == "TF_CKPT_V2" or \ args.import_format == "SAVED_MODEL": from .tensorflow import TensorflowImporter return TensorflowImporter(*ifiles, tf_format=args.import_format, outputs=args.outputs, inputs=args.inputs).execute() elif args.import_format == 'TFLITE': from .tflite import TFLiteImporter return TFLiteImporter(*ifiles).execute() return None def _shrink_nnp(nnp, pos_start, pos_end): if len(nnp.protobuf.executor) != 1 or \ len(nnp.protobuf.network) != 1: print('[ERROR] Please make only one network in nnp.') sys.exit(-1) from nnabla.utils import nnabla_pb2 class _nnp: pass _nnp.protobuf = nnabla_pb2.NNablaProtoBuf() _nnp.other_files = nnp.other_files net = nnabla_pb2.NNablaProtoBuf().network.add() net.CopyFrom(nnp.protobuf.network[0]) # Shrink network variables = {} net.ClearField('function') for i in range(pos_start, pos_end+1): f = nnp.protobuf.network[0].function[i] func = net.function.add() func.CopyFrom(f) for v in func.input: variables[v] = True for v in func.output: variables[v] = True net.ClearField('variable') for v in nnp.protobuf.network[0].variable: if v.name in variables: variables[v.name] = v.type var = net.variable.add() var.CopyFrom(v) # Shrink parameter params = [] for param in nnp.protobuf.parameter: if param.variable_name in variables: p = nnabla_pb2.NNablaProtoBuf().parameter.add() p.CopyFrom(param) params.append(p) for p in params: param = _nnp.protobuf.parameter.add() param.CopyFrom(p) # Shrink executor exe = nnabla_pb2.NNablaProtoBuf().executor.add() exe.CopyFrom(nnp.protobuf.executor[0]) exe.ClearField('data_variable') for vname in nnp.protobuf.network[0].function[pos_start].input: if variables[vname] == 'Buffer': v = exe.data_variable.add() v.variable_name = vname exe.ClearField('generator_variable') for var in nnp.protobuf.executor[0].generator_variable: if var.variable_name in variables: v = exe.generator_variable.add() v.CopyFrom(var) exe.ClearField('output_variable') for vname in nnp.protobuf.network[0].function[pos_end].output: if variables[vname] == 'Buffer': v = exe.output_variable.add() v.variable_name = vname exe.ClearField('parameter_variable') for var in nnp.protobuf.executor[0].parameter_variable: if var.variable_name in variables: v = exe.parameter_variable.add() v.CopyFrom(var) n = _nnp.protobuf.network.add() n.CopyFrom(net) e = _nnp.protobuf.executor.add() e.CopyFrom(exe) return _nnp def _export_from_nnp(args, nnp, output): if args.export_format == 'NNP': parameter_type = 'protobuf' if args.nnp_parameter_nntxt: parameter_type = 'included' elif args.nnp_parameter_h5: parameter_type = 'h5' if args.nnp_exclude_parameter: parameter_type = 'none' NnpExporter(nnp, args.batch_size, parameter_type).execute(output) elif args.export_format == 'NNB': if args.batch_size < 0: print('NNB: Batch size adjust to 1.') print('NNB: If you want to use with other size use `-b` option.') args.batch_size = 1 if args.define_version and args.define_version.startswith('nnb_'): nnb_version = int(args.define_version.split("_")[1]) NnbExporter(nnp, args.batch_size, nnb_version=nnb_version, api_level=args.api).execute( output, None, args.settings, args.default_variable_type) else: NnbExporter(nnp, args.batch_size, api_level=args.api).execute( output, None, args.settings, args.default_variable_type) elif args.export_format == 'CSRC': if args.batch_size < 0: print('CSRC: Batch size adjust to 1.') print('CSRC: If you want to use with other size use `-b` option.') args.batch_size = 1 CsrcExporter(nnp, args.batch_size).execute(output) elif args.export_format == 'ONNX': from .onnx import OnnxExporter if args.define_version and args.define_version.startswith('opset_'): opset = args.define_version.split("_")[1] OnnxExporter(nnp, args.batch_size, opset=opset).execute(output) else: OnnxExporter(nnp, args.batch_size).execute(output) elif args.export_format == 'SAVED_MODEL' or args.export_format == 'TF_PB': from .tensorflow import TensorflowExporter TensorflowExporter(nnp, args.batch_size, model_format=args.export_format).execute(output) elif args.export_format == 'TFLITE': from .tflite import TFLiteExporter TFLiteExporter(nnp, args.batch_size, channel_last=args.channel_last).execute(output) else: print('Output file ({})'.format(args.export_format) + ' is not supported or output directory does not exist.') return False return True def _need_split(nnp, args, supported_set): if args.split is not None: if args.nnp_import_executor_index is None: print('[ERROR] "-S" needs "-E".') sys.exit(-1) return True if not args.config: return False if func_set_import_nnp(nnp) <= supported_set: return False return True def _get_split_ranges(nnp, args, supported_set): def get_ranges_from_param(split_spec): ranges = [] for srange in split_spec.split(','): srange_s = srange.split('-') if len(srange_s) == 2: if srange_s[0] == '': pos_start = 0 else: pos_start = int(srange_s[0]) if srange_s[1] == '': pos_end = len(network.function) - 1 else: pos_end = int(srange_s[1]) if pos_end < pos_start or pos_end > len(network.function) - 1: print('[ERROR] range must be in 0 to {}'.format( len(network.function) - 1)) sys.exit(-1) else: print('[ERROR] range must be "x0-y0,x1-y1,..."') sys.exit(-1) ranges.append((pos_start, pos_end)) return ranges def get_ranges_from_func_set(support_set): pos_start = 0 pos_end = 0 ranges = [] for pos, func in enumerate(network.function): if func.type in support_set: pos_end = pos else: if pos_end >= pos_start: ranges.append((pos_start, pos_end)) pos_start = pos + 1 if pos_end >= pos_start: ranges.append((pos_start, pos_end)) return ranges network = None for n in nnp.protobuf.network: if n.name == nnp.protobuf.executor[0].network_name: network = n if args.split: return get_ranges_from_param(args.split) return get_ranges_from_func_set(supported_set) def convert_files(args, ifiles, output): nnp = _import_file(args, ifiles) if nnp is not None: network_name = nnp.protobuf.executor[0].network_name if args.export_format == 'ONNX': if args.config: support_set = func_set_onnx_support() & \ func_set_import_onnx_config(args.config) else: support_set = func_set_onnx_support() elif args.export_format == 'NNB': if args.config: support_set = func_set_import_config(args.config) else: support_set = func_set_nnabla_support() else: if args.config: support_set = func_set_import_config(args.config) else: support_set = func_set_nnabla_support() if _need_split(nnp, args, support_set): for _net in nnp.protobuf.network[:]: if _net.name != network_name: nnp.protobuf.network.remove(_net) ranges = _get_split_ranges(nnp, args, support_set) nnb_info = collections.OrderedDict() for pos_start, pos_end in ranges: print(' Shrink {} to {}.'.format(pos_start, pos_end)) n, e = os.path.splitext(output) new_output = n + '_{}_{}'.format(pos_start, pos_end) + e print(' Output to [{}]'.format(new_output)) _nnp = _shrink_nnp(nnp, pos_start, pos_end) nnb_info[new_output] = collections.OrderedDict() nnb_info[new_output]['input'] = [] nnb_info[new_output]['output'] = [] i_var = [] o_var = [] for var in _nnp.protobuf.executor[0].data_variable: i_var.append(var.variable_name) for var in _nnp.protobuf.executor[0].output_variable: o_var.append(var.variable_name) for var in _nnp.protobuf.network[0].variable: if var.name in i_var: _info = collections.OrderedDict() _info['name'] = var.name _info['shape'] = '({})'.format( ', '.join(str(i) for i in var.shape.dim)) nnb_info[new_output]['input'].append(_info) if var.name in o_var: _info = collections.OrderedDict() _info['name'] = var.name _info['shape'] = '({})'.format( ', '.join(str(i) for i in var.shape.dim)) nnb_info[new_output]['output'].append(_info) _export_from_nnp(args, _nnp, new_output) import yaml print(yaml.dump(nnb_info, default_flow_style=False)) else: return _export_from_nnp(args, nnp, output) else: print('Import from {} failed.'.format(ifiles)) return False def _generate_nnb_template(args, nnp, output): NnbExporter(nnp, args.batch_size, api_level=args.api).execute( None, output, None, args.default_variable_type) return True def nnb_template(args, ifiles, output): nnp = _import_file(args, ifiles) if nnp is not None: return _generate_nnb_template(args, nnp, output) else: print('Import from [{}] failed.'.format(ifiles)) return False def _dump_protobuf(args, proto, prefix, depth): if args.dump_verbose: if 0 <= depth <= len(prefix): print('{} ...'.format(':'.join(prefix))) return for desc, field in proto.ListFields(): if isinstance(field, (int, float, complex, str)): print('{}:{}: {}'.format(':'.join(prefix), desc.name, field)) elif isinstance(field, collections.Iterable): print('{} has {} {}(s).'.format( ':'.join(prefix), len(field), desc.name)) for n, f in enumerate(field[:args.dump_limit]): if isinstance(f, (int, float, complex, str)): print('{}:{}[{}]: {}'.format( ':'.join(prefix), desc.name, n, f)) else: if depth < 0 or depth > len(prefix)+1: _dump_protobuf( args, f, prefix + ['{}[{}]'.format(desc.name, n)], depth) else: _dump_protobuf(args, field, prefix + [desc.name], depth) else: params = {} for par in proto.parameter: params[par.variable_name] = [x for x in par.shape.dim] nets = {} for net in proto.network: ninfo = {'variables': {}, 'functions': []} for var in net.variable: if var.type == 'Parameter': if var.name not in params: print('[ERROR] Parameter [{}] in network[{}] not found.'.format( var.name, net.name)) print(' ' + 'Make sure that you do not forget to read parameter file.') print(' ' + 'Otherwise it should be expander problem. Please report us.') sys.exit(-1) ninfo['variables'][var.name] = { 'type': var.type, 'shape': [x for x in var.shape.dim]} for func in net.function: ninfo['functions'].append(func) nets[net.name] = ninfo def _dump_network_arg(prefix, name, var): for i, v in enumerate(var): shape = ' - ' if v.variable_name in net['variables']: shape = net['variables'][v.variable_name]['shape'] print('{}{} variable[{}]:'.format(prefix, name, i) + ' Name:{:30}'.format(v.variable_name) + ' Shape:{}'.format(shape)) def _dump_network(prefix, net): if args.dump_variable_name: if args.dump_variable_name in net['variables']: v = args.dump_variable_name print('Variable Name: {:20} Shape: {}'.format( v, net['variables'][v]['shape'])) else: print('DUMP ERROR: variable {} not found.'.format( args.dump_variable_name)) return if args.dump_functions: for i, f in enumerate(net['functions']): func_prefix = '{} Function[{:^5}]: '.format(prefix, i) print('{}Type: {:20} Name: {}'.format( func_prefix, f.type, f.name)) if args.dump_variables: for j, v in enumerate(f.input): print('{} Input{}: Name: {:20} Shape: {}'.format( func_prefix, j, v, net['variables'][v]['shape'])) for j, v in enumerate(f.output): print('{} Output{}: Name: {:20} Shape: {}'.format( func_prefix, j, v, net['variables'][v]['shape'])) for i, opt in enumerate(proto.optimizer): net = nets[opt.network_name] prefix = ' Optimizer[{}]: '.format(i) print('{}{}'.format(prefix, opt.name)) _dump_network_arg(prefix, ' (In) Data ', opt.data_variable) _dump_network_arg(prefix, ' (In) Generator', opt.generator_variable) _dump_network_arg(prefix, ' (Out)Loss ', opt.loss_variable) _dump_network(prefix, net) for i, mon in enumerate(proto.monitor): net = nets[mon.network_name] prefix = ' Monitor [{}]: '.format(i) print('{}{}'.format(prefix, mon.name)) _dump_network_arg(prefix, ' (In) Data ', mon.data_variable) _dump_network_arg(prefix, ' (In) Generator', mon.generator_variable) _dump_network_arg(prefix, ' (Out)Monitor ', mon.monitor_variable) _dump_network(prefix, net) for i, exe in enumerate(proto.executor): net = nets[exe.network_name] prefix = ' Executor [{}]: '.format(i) print('{}{}'.format(prefix, exe.name)) _dump_network_arg(prefix, ' (In) Data ', exe.data_variable) _dump_network_arg(prefix, ' (In) Generator', exe.generator_variable) _dump_network_arg(prefix, ' (Out)Loss ', exe.loss_variable) _dump_network_arg(prefix, ' (Out)Output ', exe.output_variable) _dump_network(prefix, net) def _dump_nnp(args, nnp): _dump_protobuf(args, nnp.protobuf, [args.import_format], -1) return True def dump_files(args, ifiles): nnp = _import_file(args, ifiles) if nnp is not None: return _dump_nnp(args, nnp) else: print('Import from [{}] failed.'.format(ifiles)) return False
apache-2.0
1,649,019,417,689,159,000
39.11479
124
0.534008
false
karrtikr/ete
ete3/tools/ete_ncbiquery.py
1
8047
# #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://etetoolkit.org # # ETE 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. # # ETE 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 ETE. If not, see <http://www.gnu.org/licenses/>. # # # ABOUT THE ETE PACKAGE # ===================== # # ETE is distributed under the GPL copyleft license (2008-2015). # # If you make use of ETE in published work, please cite: # # Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. # ETE: a python Environment for Tree Exploration. Jaime BMC # Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 # # Note that extra references to the specific methods implemented in # the toolkit may be available in the documentation. # # More info at http://etetoolkit.org. Contact: [email protected] # # # #END_LICENSE############################################################# from __future__ import absolute_import from __future__ import print_function import sys from .common import log, dump import six from six.moves import map DESC = "" def populate_args(ncbi_args_p): ncbi_args = ncbi_args_p.add_argument_group('NCBI GENERAL OPTIONS') ncbi_args.add_argument("--search", dest="search", nargs="+", help="A list of taxid or species names") ncbi_args.add_argument("--db", dest="dbfile", type=str, help="""NCBI sqlite3 db file.""") ncbi_args.add_argument("--fuzzy", dest="fuzzy", type=float, help=("EXPERIMENTAL: Tries a fuzzy (and SLOW) search for those" " species names that could not be translated" " into taxids. A float number must be provided" " indicating the minimum string similarity." " Special sqlite compilation is necessary.")) output_args = ncbi_args_p.add_argument_group('NCBI OUTPUT OPTIONS') output_args.add_argument("--tree", dest="tree", action='store_true', help=("dump a pruned version of the NCBI taxonomy" " tree containing target species")) output_args.add_argument("--descendants", dest="descendants", action='store_true', help=("dump the descendant taxa for each of the queries")) output_args.add_argument("--info", dest="info", action='store_true', help="""dump NCBI taxonmy information for each target species into the specified file. """) output_args.add_argument("--collapse_subspecies", dest="collapse_subspecies", action="store_true", help=("When used, all nodes under the the species rank" " are collapsed, so all species and subspecies" " are seen as sister nodes")) output_args.add_argument("--rank_limit", dest="rank_limit", type=str, help=("When used, all nodes under the provided rank" " are discarded")) output_args.add_argument("--full_lineage", dest="full_lineage", action="store_true", help=("When used, topology is not pruned to avoid " " one-child-nodes, so the complete lineage" " track leading from root to tips is kept.")) def run(args): # add lineage profiles/stats import re from .. import PhyloTree, NCBITaxa # dump tree by default if not args.tree and not args.info and not args.descendants: args.tree = True ncbi = NCBITaxa() all_taxids = {} all_names = set() queries = [] if not args.search: log.error('Search terms should be provided (i.e. --search) ') sys.exit(-1) for n in args.search: queries.append(n) try: all_taxids[int(n)] = None except ValueError: all_names.add(n.strip()) # translate names name2tax = ncbi.get_name_translator(all_names) for tids in name2tax.values(): for tid in tids: all_taxids[tid] = None not_found_names = all_names - set(name2tax.keys()) if args.fuzzy and not_found_names: log.warn("%s unknown names", len(not_found_names)) for name in not_found_names: # enable extension loading tax, realname, sim = ncbi.get_fuzzy_name_translation(name, args.fuzzy) if tax: all_taxids[tax] = None name2tax[name] = [tax] name2realname[name] = realname name2score[name] = "Fuzzy:%0.2f" %sim if not_found_names: log.warn("[%s] could not be translated into taxids!" %','.join(not_found_names)) if args.tree: if len(all_taxids) == 1: target_taxid = list(all_taxids.keys())[0] log.info("Dumping NCBI descendants tree for %s" %(target_taxid)) t = ncbi.get_descendant_taxa(target_taxid, collapse_subspecies=args.collapse_subspecies, rank_limit=args.rank_limit, return_tree=True) else: log.info("Dumping NCBI taxonomy of %d taxa..." %(len(all_taxids))) t = ncbi.get_topology(list(all_taxids.keys()), intermediate_nodes=args.full_lineage, rank_limit=args.rank_limit, collapse_subspecies=args.collapse_subspecies) id2name = ncbi.get_taxid_translator([n.name for n in t.traverse()]) for n in t.traverse(): n.add_features(taxid=n.name) n.add_features(sci_name=str(id2name.get(int(n.name), "?"))) n.name = "%s - %s" %(id2name.get(int(n.name), n.name), n.name) lineage = ncbi.get_lineage(n.taxid) n.add_features(named_lineage = '|'.join(ncbi.translate_to_names(lineage))) dump(t, features=["taxid", "name", "rank", "bgcolor", "sci_name", "collapse_subspecies", "named_lineage"]) elif args.descendants: log.info("Dumping NCBI taxonomy of %d taxa..." %(len(all_taxids))) print('# ' + '\t'.join(["Taxid", "Sci.Name", "Rank", "descendant_taxids", "descendant_names"])) translator = ncbi.get_taxid_translator(all_taxids) ranks = ncbi.get_rank(all_taxids) for taxid in all_taxids: descendants = ncbi.get_descendant_taxa(taxid, collapse_subspecies=args.collapse_subspecies, rank_limit=args.rank_limit) print('\t'.join([str(taxid), translator.get(taxid, taxid), ranks.get(taxid, ''), '|'.join(map(str, descendants)), '|'.join(map(str, ncbi.translate_to_names(descendants)))])) elif args.info: print('# ' + '\t'.join(["Taxid", "Sci.Name", "Rank", "Named Lineage", "Taxid Lineage"])) translator = ncbi.get_taxid_translator(all_taxids) ranks = ncbi.get_rank(all_taxids) for taxid, name in six.iteritems(translator): lineage = ncbi.get_lineage(taxid) named_lineage = ','.join(ncbi.translate_to_names(lineage)) lineage_string = ','.join(map(str, lineage)) print('\t'.join([str(taxid), name, ranks.get(taxid, ''), named_lineage, lineage_string]))
gpl-3.0
1,931,690,131,779,926,800
42.263441
146
0.568038
false
charactory/namcap
Namcap/gnomemime.py
4
1682
# # namcap rules - gnomemime # Copyright (C) 2003-2007 Jason Chu <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # import tarfile class package: def short_name(self): return "gnomemime" def long_name(self): return "Checks for generated GNOME mime files" def prereq(self): return "tar" def analyze(self, pkginfo, tar): mime_files = [ 'opt/gnome/share/applications/mimeinfo.cache', 'opt/gnome/share/mime/XMLnamespaces', 'opt/gnome/share/mime/aliases', 'opt/gnome/share/mime/globs', 'opt/gnome/share/mime/magic', 'opt/gnome/share/mime/subclasses' ] ret = [[],[],[]] for i in tar.getnames(): if i in mime_files: ret[0].append("File (" + i + ") is an auto-generated GNOME mime file.") return ret def type(self): return "tarball" # vim: set ts=4 sw=4 noet:
gpl-2.0
-5,388,698,177,727,171,000
35.565217
87
0.627824
false
oarriaga/spatial_transformer_networks
src/models/STN.py
1
1242
from keras.layers import Input from keras.models import Model from keras.layers import Activation from keras.layers import MaxPool2D from keras.layers import Flatten from keras.layers import Conv2D from keras.layers import Dense from .utils import get_initial_weights from .layers import BilinearInterpolation def STN(input_shape=(60, 60, 1), sampling_size=(30, 30), num_classes=10): image = Input(shape=input_shape) locnet = MaxPool2D(pool_size=(2, 2))(image) locnet = Conv2D(20, (5, 5))(locnet) locnet = MaxPool2D(pool_size=(2, 2))(locnet) locnet = Conv2D(20, (5, 5))(locnet) locnet = Flatten()(locnet) locnet = Dense(50)(locnet) locnet = Activation('relu')(locnet) weights = get_initial_weights(50) locnet = Dense(6, weights=weights)(locnet) x = BilinearInterpolation(sampling_size)([image, locnet]) x = Conv2D(32, (3, 3), padding='same')(x) x = Activation('relu')(x) x = MaxPool2D(pool_size=(2, 2))(x) x = Conv2D(32, (3, 3))(x) x = Activation('relu')(x) x = MaxPool2D(pool_size=(2, 2))(x) x = Flatten()(x) x = Dense(256)(x) x = Activation('relu')(x) x = Dense(num_classes)(x) x = Activation('softmax')(x) return Model(inputs=image, outputs=x)
mit
-1,956,776,745,206,133,800
33.5
73
0.65942
false
jdugge/QGIS
tests/src/python/test_qgsdelimitedtextprovider_wanted.py
33
73028
# -*- coding: utf-8 -*- """ *************************************************************************** test_qgsdelimitedtextprovider_wanted.py --------------------- Date : May 2013 Copyright : (C) 2013 by Chris Crook Email : ccrook at linz dot govt dot nz *************************************************************************** * * * 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__ = 'Chris Crook' __date__ = 'May 2013' __copyright__ = '(C) 2013, Chris Crook' def test_002_load_csv_file(): wanted = {} wanted['uri'] = 'file://test.csv?geomType=none&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Basic unquoted record', 'data': 'Some data', 'info': 'Some info', 'field_5': 'NULL', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Quoted field', 'data': 'Quoted data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 3, '#geometry': 'None', }, 4: { 'id': '3', 'description': 'Escaped quotes', 'data': 'Quoted "citation" data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 4, '#geometry': 'None', }, 5: { 'id': '4', 'description': 'Quoted newlines', 'data': 'Line 1\nLine 2\n\nLine 4', 'info': 'No data', 'field_5': 'NULL', '#fid': 5, '#geometry': 'None', }, 9: { 'id': '5', 'description': 'Extra fields', 'data': 'data', 'info': 'info', 'field_5': 'message', '#fid': 9, '#geometry': 'None', }, 10: { 'id': '6', 'description': 'Missing fields', 'data': 'NULL', 'info': 'NULL', 'field_5': 'NULL', '#fid': 10, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_003_field_naming(): wanted = {} wanted['uri'] = 'file://testfields.csv?geomType=none&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Generation of field names', 'data': 'Some data', 'field_4': 'Some info', 'data_2': 'NULL', '28': 'NULL', '24.5': 'NULL', 'field_3_1': 'NULL', 'data_1': 'NULL', 'field_10': 'NULL', 'field_11': 'NULL', 'field_12': 'last data', '#fid': 2, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_004_max_fields(): wanted = {} wanted['uri'] = 'file://testfields.csv?geomType=none&maxFields=7&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Generation of field names', 'data': 'Some data', 'field_4': 'Some info', 'data_1': 'NULL', '28': 'NULL', '24.5': 'NULL', '#fid': 2, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_005_load_whitespace(): wanted = {} wanted['uri'] = 'file://test.space?geomType=none&type=whitespace' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Simple_whitespace_file', 'data': 'data1', 'info': 'info1', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Whitespace_at_start_of_line', 'data': 'data2', 'info': 'info2', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 3, '#geometry': 'None', }, 4: { 'id': '3', 'description': 'Tab_whitespace', 'data': 'data3', 'info': 'info3', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 4, '#geometry': 'None', }, 5: { 'id': '4', 'description': 'Multiple_whitespace_characters', 'data': 'data4', 'info': 'info4', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 5, '#geometry': 'None', }, 6: { 'id': '5', 'description': 'Extra_fields', 'data': 'data5', 'info': 'info5', 'field_5': 'message5', 'field_6': 'rubbish5', '#fid': 6, '#geometry': 'None', }, 7: { 'id': '6', 'description': 'Missing_fields', 'data': 'NULL', 'info': 'NULL', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 7, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_006_quote_escape(): wanted = {} wanted['uri'] = 'file://test.pipe?geomType=none&quote="&delimiter=|&escape=\\' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Using pipe delimiter', 'data': 'data 1', 'info': 'info 1', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Using backslash escape on pipe', 'data': 'data 2 | piped', 'info': 'info2', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 3, '#geometry': 'None', }, 4: { 'id': '3', 'description': 'Backslash escaped newline', 'data': 'data3 \nline2 \nline3', 'info': 'info3', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 4, '#geometry': 'None', }, 7: { 'id': '4', 'description': 'Empty field', 'data': 'NULL', 'info': 'info4', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 7, '#geometry': 'None', }, 8: { 'id': '5', 'description': 'Quoted field', 'data': 'More | piped data', 'info': 'info5', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 8, '#geometry': 'None', }, 9: { 'id': '6', 'description': 'Escaped quote', 'data': 'Field "citation" ', 'info': 'info6', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 9, '#geometry': 'None', }, 10: { 'id': '7', 'description': 'Missing fields', 'data': 'NULL', 'info': 'NULL', 'field_5': 'NULL', 'field_6': 'NULL', '#fid': 10, '#geometry': 'None', }, 11: { 'id': '8', 'description': 'Extra fields', 'data': 'data8', 'info': 'info8', 'field_5': 'message8', 'field_6': 'more', '#fid': 11, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_007_multiple_quote(): wanted = {} wanted['uri'] = 'file://test.quote?geomType=none&quote=\'"&type=csv&escape="\'' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Multiple quotes 1', 'data': 'Quoted,data1', 'info': 'info1', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Multiple quotes 2', 'data': 'Quoted,data2', 'info': 'info2', '#fid': 3, '#geometry': 'None', }, 4: { 'id': '3', 'description': 'Leading and following whitespace', 'data': 'Quoted, data3', 'info': 'info3', '#fid': 4, '#geometry': 'None', }, 5: { 'id': '4', 'description': 'Embedded quotes 1', 'data': 'Quoted \'\'"\'\' data4', 'info': 'info4', '#fid': 5, '#geometry': 'None', }, 6: { 'id': '5', 'description': 'Embedded quotes 2', 'data': 'Quoted \'""\' data5', 'info': 'info5', '#fid': 6, '#geometry': 'None', }, 10: { 'id': '9', 'description': 'Final record', 'data': 'date9', 'info': 'info9', '#fid': 10, '#geometry': 'None', }, } wanted['log'] = [ 'Errors in file test.quote', '3 records discarded due to invalid format', 'The following lines were not loaded into QGIS due to errors:', 'Invalid record format at line 7', 'Invalid record format at line 8', 'Invalid record format at line 9', ] return wanted def test_008_badly_formed_quotes(): wanted = {} wanted['uri'] = 'file://test.badquote?geomType=none&quote="&type=csv&escape="' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 4: { 'id': '3', 'description': 'Recovered after unclosed quore', 'data': 'Data ok', 'info': 'inf3', '#fid': 4, '#geometry': 'None', }, } wanted['log'] = [ 'Errors in file test.badquote', '2 records discarded due to invalid format', 'The following lines were not loaded into QGIS due to errors:', 'Invalid record format at line 2', 'Invalid record format at line 5', ] return wanted def test_009_skip_lines(): wanted = {} wanted['uri'] = 'file://test2.csv?geomType=none&skipLines=2&type=csv&useHeader=no' wanted['fieldTypes'] = ['integer', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 3: { 'id': '3', 'description': 'Less data', 'field_1': '3', 'field_2': 'Less data', 'field_3': 'data3', '#fid': 3, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_010_read_coordinates(): wanted = {} wanted['uri'] = 'file://testpt.csv?yField=geom_y&xField=geom_x&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'double', 'double'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': '1', 'description': 'Basic point', 'geom_x': '10.5', 'geom_y': '20.82', '#fid': 2, '#geometry': 'Point (10.5 20.82)', }, 3: { 'id': '2', 'description': 'Integer point', 'geom_x': '11.0', 'geom_y': '22.0', '#fid': 3, '#geometry': 'Point (11 22)', }, 5: { 'id': '4', 'description': 'Final point', 'geom_x': '13.0', 'geom_y': '23.0', '#fid': 5, '#geometry': 'Point (13 23)', }, } wanted['log'] = [ 'Errors in file testpt.csv', '1 records discarded due to invalid geometry definitions', 'The following lines were not loaded into QGIS due to errors:', 'Invalid X or Y fields at line 4', ] return wanted def test_011_read_wkt(): wanted = {} wanted['uri'] = 'file://testwkt.csv?delimiter=|&type=csv&wktField=geom_wkt' wanted['fieldTypes'] = ['integer', 'text'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': '1', 'description': 'Point wkt', '#fid': 2, '#geometry': 'Point (10 20)', }, 3: { 'id': '2', 'description': 'Multipoint wkt', '#fid': 3, '#geometry': 'MultiPoint ((10 20),(11 21))', }, 9: { 'id': '8', 'description': 'EWKT prefix', '#fid': 9, '#geometry': 'Point (10 10)', }, 10: { 'id': '9', 'description': 'Informix prefix', '#fid': 10, '#geometry': 'Point (10 10)', }, 11: { 'id': '10', 'description': 'Measure in point', '#fid': 11, '#geometry': 'PointM (10 20 30)', }, } wanted['log'] = [ 'Errors in file testwkt.csv', '1 records discarded due to invalid geometry definitions', '10 records discarded due to incompatible geometry types', 'The following lines were not loaded into QGIS due to errors:', 'Invalid WKT at line 8', ] return wanted def test_012_read_wkt_point(): wanted = {} wanted['uri'] = 'file://testwkt.csv?geomType=point&delimiter=|&type=csv&wktField=geom_wkt' wanted['fieldTypes'] = ['integer', 'text'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': '1', 'description': 'Point wkt', '#fid': 2, '#geometry': 'Point (10 20)', }, 3: { 'id': '2', 'description': 'Multipoint wkt', '#fid': 3, '#geometry': 'MultiPoint ((10 20),(11 21))', }, 9: { 'id': '8', 'description': 'EWKT prefix', '#fid': 9, '#geometry': 'Point (10 10)', }, 10: { 'id': '9', 'description': 'Informix prefix', '#fid': 10, '#geometry': 'Point (10 10)', }, 11: { 'id': '10', 'description': 'Measure in point', '#fid': 11, '#geometry': 'PointM (10 20 30)', }, } wanted['log'] = [ 'Errors in file testwkt.csv', '1 records discarded due to invalid geometry definitions', '10 records discarded due to incompatible geometry types', 'The following lines were not loaded into QGIS due to errors:', 'Invalid WKT at line 8', ] return wanted def test_013_read_wkt_line(): wanted = {} wanted['uri'] = 'file://testwkt.csv?geomType=line&delimiter=|&type=csv&wktField=geom_wkt' wanted['fieldTypes'] = ['integer', 'text'] wanted['geometryType'] = 1 wanted['data'] = { 4: { 'id': '3', 'description': 'Linestring wkt', '#fid': 4, '#geometry': 'LineString (10 20, 11 21)', }, 5: { 'id': '4', 'description': 'Multiline string wkt', '#fid': 5, '#geometry': 'MultiLineString ((10 20, 11 21), (20 30, 21 31))', }, 12: { 'id': '11', 'description': 'Measure in line', '#fid': 12, '#geometry': 'LineStringM (10 20 30, 11 21 31)', }, 13: { 'id': '12', 'description': 'Z in line', '#fid': 13, '#geometry': 'LineStringZ (10 20 30, 11 21 31)', }, 14: { 'id': '13', 'description': 'Measure and Z in line', '#fid': 14, '#geometry': 'LineStringZM (10 20 30 40, 11 21 31 41)', }, 15: { 'id': '14', 'description': 'CircularString', '#fid': 15, '#geometry': 'CircularString (268 415, 227 505, 227 406)', }, 17: { 'id': '16', 'description': 'CompoundCurve', '#fid': 17, '#geometry': 'CompoundCurve ((5 3, 5 13), CircularString(5 13, 7 15, 9 13), (9 13, 9 3), CircularString(9 3, 7 1, 5 3))', }, } wanted['log'] = [ 'Errors in file testwkt.csv', '1 records discarded due to invalid geometry definitions', '8 records discarded due to incompatible geometry types', 'The following lines were not loaded into QGIS due to errors:', 'Invalid WKT at line 8', ] return wanted def test_014_read_wkt_polygon(): wanted = {} wanted['uri'] = 'file://testwkt.csv?geomType=polygon&delimiter=|&type=csv&wktField=geom_wkt' wanted['fieldTypes'] = ['integer', 'text'] wanted['geometryType'] = 2 wanted['data'] = { 6: { 'id': '5', 'description': 'Polygon wkt', '#fid': 6, '#geometry': 'Polygon ((10 10,10 20,20 20,20 10,10 10),(14 14,14 16,16 16,14 14))', }, 7: { 'id': '6', 'description': 'MultiPolygon wkt', '#fid': 7, '#geometry': 'MultiPolygon (((10 10,10 20,20 20,20 10,10 10),(14 14,14 16,16 16,14 14)),((30 30,30 35,35 35,30 30)))', }, 16: { 'id': '15', 'description': 'CurvePolygon', '#fid': 16, '#geometry': 'CurvePolygon (CircularString (1 3, 3 5, 4 7, 7 3, 1 3))', }, } wanted['log'] = [ 'Errors in file testwkt.csv', '1 records discarded due to invalid geometry definitions', '12 records discarded due to incompatible geometry types', 'The following lines were not loaded into QGIS due to errors:', 'Invalid WKT at line 8', ] return wanted def test_015_read_dms_xy(): wanted = {} wanted['uri'] = 'file://testdms.csv?yField=lat&xField=lon&type=csv&xyDms=yes' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text'] wanted['geometryType'] = 0 wanted['data'] = { 3: { 'id': '1', 'description': 'Basic DMS string', 'lon': '1 5 30.6', 'lat': '35 51 20', '#fid': 3, '#geometry': 'Point (1.09183333 35.85555556)', }, 4: { 'id': '2', 'description': 'Basic DMS string 2', 'lon': '1 05 30.6005', 'lat': '035 51 20', '#fid': 4, '#geometry': 'Point (1.09183347 35.85555556)', }, 5: { 'id': '3', 'description': 'Basic DMS string 3', 'lon': '1 05 30.6', 'lat': '35 59 9.99', '#fid': 5, '#geometry': 'Point (1.09183333 35.98610833)', }, 7: { 'id': '4', 'description': 'Prefix sign 1', 'lon': 'n1 05 30.6', 'lat': 'e035 51 20', '#fid': 7, '#geometry': 'Point (1.09183333 35.85555556)', }, 8: { 'id': '5', 'description': 'Prefix sign 2', 'lon': 'N1 05 30.6', 'lat': 'E035 51 20', '#fid': 8, '#geometry': 'Point (1.09183333 35.85555556)', }, 9: { 'id': '6', 'description': 'Prefix sign 3', 'lon': 'N 1 05 30.6', 'lat': 'E 035 51 20', '#fid': 9, '#geometry': 'Point (1.09183333 35.85555556)', }, 10: { 'id': '7', 'description': 'Prefix sign 4', 'lon': 'S1 05 30.6', 'lat': 'W035 51 20', '#fid': 10, '#geometry': 'Point (-1.09183333 -35.85555556)', }, 11: { 'id': '8', 'description': 'Prefix sign 5', 'lon': '+1 05 30.6', 'lat': '+035 51 20', '#fid': 11, '#geometry': 'Point (1.09183333 35.85555556)', }, 12: { 'id': '9', 'description': 'Prefix sign 6', 'lon': '-1 05 30.6', 'lat': '-035 51 20', '#fid': 12, '#geometry': 'Point (-1.09183333 -35.85555556)', }, 14: { 'id': '10', 'description': 'Postfix sign 1', 'lon': '1 05 30.6n', 'lat': '035 51 20e', '#fid': 14, '#geometry': 'Point (1.09183333 35.85555556)', }, 15: { 'id': '11', 'description': 'Postfix sign 2', 'lon': '1 05 30.6N', 'lat': '035 51 20E', '#fid': 15, '#geometry': 'Point (1.09183333 35.85555556)', }, 16: { 'id': '12', 'description': 'Postfix sign 3', 'lon': '1 05 30.6 N', 'lat': '035 51 20 E', '#fid': 16, '#geometry': 'Point (1.09183333 35.85555556)', }, 17: { 'id': '13', 'description': 'Postfix sign 4', 'lon': '1 05 30.6S', 'lat': '035 51 20W', '#fid': 17, '#geometry': 'Point (-1.09183333 -35.85555556)', }, 18: { 'id': '14', 'description': 'Postfix sign 5', 'lon': '1 05 30.6+', 'lat': '035 51 20+', '#fid': 18, '#geometry': 'Point (1.09183333 35.85555556)', }, 19: { 'id': '15', 'description': 'Postfix sign 6', 'lon': '1 05 30.6-', 'lat': '035 51 20-', '#fid': 19, '#geometry': 'Point (-1.09183333 -35.85555556)', }, 21: { 'id': '16', 'description': 'Leading and trailing blanks 1', 'lon': ' 1 05 30.6', 'lat': '035 51 20 ', '#fid': 21, '#geometry': 'Point (1.09183333 35.85555556)', }, 22: { 'id': '17', 'description': 'Leading and trailing blanks 2', 'lon': ' N 1 05 30.6', 'lat': '035 51 20 E ', '#fid': 22, '#geometry': 'Point (1.09183333 35.85555556)', }, 24: { 'id': '18', 'description': 'Alternative characters for D,M,S', 'lon': '1d05m30.6s S', 'lat': "35d51'20", '#fid': 24, '#geometry': 'Point (-1.09183333 35.85555556)', }, 25: { 'id': '19', 'description': 'Degrees/minutes format', 'lon': '1 05.23', 'lat': '4 55.03', '#fid': 25, '#geometry': 'Point (1.08716667 4.91716667)', }, } wanted['log'] = [ 'Errors in file testdms.csv', '5 records discarded due to invalid geometry definitions', 'The following lines were not loaded into QGIS due to errors:', 'Invalid X or Y fields at line 27', 'Invalid X or Y fields at line 28', 'Invalid X or Y fields at line 29', 'Invalid X or Y fields at line 30', 'Invalid X or Y fields at line 31', ] return wanted def test_016_decimal_point(): wanted = {} wanted['uri'] = 'file://testdp.csv?yField=geom_y&xField=geom_x&type=csv&delimiter=;&decimalPoint=,' wanted['fieldTypes'] = ['integer', 'text', 'double', 'double', 'double', 'text'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': '1', 'description': 'Comma as decimal point 1', 'geom_x': '10.0', 'geom_y': '20.0', 'other': '30.0', 'text field': 'Field with , in it', '#fid': 2, '#geometry': 'Point (10 20)', }, 3: { 'id': '2', 'description': 'Comma as decimal point 2', 'geom_x': '12.0', 'geom_y': '25.003', 'other': '-38.55', 'text field': 'Plain text field', '#fid': 3, '#geometry': 'Point (12 25.003)', }, } wanted['log'] = [] return wanted def test_017_regular_expression_1(): wanted = {} wanted['uri'] = 'file://testre.txt?geomType=none&trimFields=Y&delimiter=RE(?:GEXP)?&type=regexp' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Basic regular expression test', 'data': 'data1', 'info': 'info', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Basic regular expression test 2', 'data': 'data2', 'info': 'info2', '#fid': 3, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_018_regular_expression_2(): wanted = {} wanted['uri'] = 'file://testre.txt?geomType=none&trimFields=Y&delimiter=(RE)(GEXP)?&type=regexp' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'RE': 'RE', 'GEXP': 'GEXP', 'description': 'RE', 'RE_1': 'RE', 'GEXP_1': 'GEXP', 'data': 'data1', 'RE_2': 'RE', 'GEXP_2': 'GEXP', 'info': 'info', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'RE': 'RE', 'GEXP': 'GEXP', 'description': 'RE', 'RE_1': 'RE', 'GEXP_1': 'NULL', 'data': 'data2', 'RE_2': 'RE', 'GEXP_2': 'NULL', 'info': 'info2', '#fid': 3, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_019_regular_expression_3(): wanted = {} wanted['uri'] = 'file://testre2.txt?geomType=none&trimFields=Y&delimiter=^(.{5})(.{30})(.{5,})&type=regexp' wanted['fieldTypes'] = ['integer', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Anchored regexp', 'information': 'Some data', '#fid': 2, '#geometry': 'None', }, 4: { 'id': '3', 'description': 'Anchored regexp recovered', 'information': 'Some data', '#fid': 4, '#geometry': 'None', }, } wanted['log'] = [ 'Errors in file testre2.txt', '1 records discarded due to invalid format', 'The following lines were not loaded into QGIS due to errors:', 'Invalid record format at line 3', ] return wanted def test_020_regular_expression_4(): wanted = {} wanted['uri'] = 'file://testre3.txt?geomType=none&delimiter=x?&type=regexp' wanted['fieldTypes'] = ['text', 'text', 'text', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': 'f', 'description': 'i', 's': 'f', 'm': 'i', 'a': '.', 'l': '.', 'l_1': 'i', 'field_6': 'l', 'field_7': 'e', '#fid': 2, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_021_regular_expression_5(): wanted = {} wanted['uri'] = 'file://testre3.txt?geomType=none&delimiter=\\b&type=regexp' wanted['fieldTypes'] = ['text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': 'fi', 'description': '..', 'small': 'fi', 'field_2': '..', 'field_3': 'ile', '#fid': 2, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_022_utf8_encoded_file(): wanted = {} wanted['uri'] = 'file://testutf8.csv?geomType=none&delimiter=|&type=csv&encoding=utf-8' wanted['fieldTypes'] = ['integer', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Correctly read UTF8 encoding', 'name': 'Field has \u0101cc\xe8nt\xe9d text', '#fid': 2, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_023_latin1_encoded_file(): wanted = {} wanted['uri'] = 'file://testlatin1.csv?geomType=none&delimiter=|&type=csv&encoding=latin1' wanted['fieldTypes'] = ['integer', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Correctly read latin1 encoding', 'name': 'This test is \xa9', '#fid': 2, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_024_filter_rect_xy(): wanted = {} wanted['uri'] = 'file://testextpt.txt?yField=y&delimiter=|&type=csv&xField=x' wanted['fieldTypes'] = ['integer', 'text', 'integer', 'integer'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': '1', 'description': 'Inside', 'x': '15', 'y': '35', '#fid': 2, '#geometry': 'Point (15 35)', }, 10: { 'id': '9', 'description': 'Inside 2', 'x': '25', 'y': '45', '#fid': 10, '#geometry': 'Point (25 45)', }, 1002: { 'id': '1', 'description': 'Inside', 'x': '15', 'y': '35', '#fid': 2, '#geometry': 'Point (15 35)', }, 1010: { 'id': '9', 'description': 'Inside 2', 'x': '25', 'y': '45', '#fid': 10, '#geometry': 'Point (25 45)', }, } wanted['log'] = [ 'Request 2 did not return any data', ] return wanted def test_025_filter_rect_wkt(): wanted = {} wanted['uri'] = 'file://testextw.txt?delimiter=|&type=csv&wktField=wkt' wanted['fieldTypes'] = ['integer', 'text'] wanted['geometryType'] = 1 wanted['data'] = { 2: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 4: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 5: { 'id': '4', 'description': 'Bounding box overlap', '#fid': 5, '#geometry': 'LineString (5 30, 5 55, 30 55)', }, 6: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 7: { 'id': '6', 'description': 'Bounding box overlap 2', '#fid': 7, '#geometry': 'LineString (28 29, 31 29, 31 33)', }, 1002: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 1004: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 1006: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, } wanted['log'] = [ 'Request 2 did not return any data', ] return wanted def test_026_filter_fid(): wanted = {} wanted['uri'] = 'file://test.csv?geomType=none&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 3: { 'id': '2', 'description': 'Quoted field', 'data': 'Quoted data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 3, '#geometry': 'None', }, 1009: { 'id': '5', 'description': 'Extra fields', 'data': 'data', 'info': 'info', 'field_5': 'message', '#fid': 9, '#geometry': 'None', }, 3003: { 'id': '2', 'description': 'Quoted field', 'data': 'Quoted data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 3, '#geometry': 'None', }, } wanted['log'] = [ 'Request 2 did not return any data', ] return wanted def test_027_filter_attributes(): wanted = {} wanted['uri'] = 'file://test.csv?geomType=none&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': 'None', 'description': 'Basic unquoted record', 'data': 'None', 'info': 'Some info', 'field_5': 'None', '#fid': 2, '#geometry': 'None', }, 3: { 'id': 'None', 'description': 'Quoted field', 'data': 'None', 'info': 'Unquoted', 'field_5': 'None', '#fid': 3, '#geometry': 'None', }, 4: { 'id': 'None', 'description': 'Escaped quotes', 'data': 'None', 'info': 'Unquoted', 'field_5': 'None', '#fid': 4, '#geometry': 'None', }, 5: { 'id': 'None', 'description': 'Quoted newlines', 'data': 'None', 'info': 'No data', 'field_5': 'None', '#fid': 5, '#geometry': 'None', }, 9: { 'id': 'None', 'description': 'Extra fields', 'data': 'None', 'info': 'info', 'field_5': 'None', '#fid': 9, '#geometry': 'None', }, 10: { 'id': 'None', 'description': 'Missing fields', 'data': 'None', 'info': 'NULL', 'field_5': 'None', '#fid': 10, '#geometry': 'None', }, 1009: { 'id': '5', 'description': 'Extra fields', 'data': 'data', 'info': 'info', 'field_5': 'message', '#fid': 9, '#geometry': 'None', }, 2009: { 'id': 'None', 'description': 'Extra fields', 'data': 'None', 'info': 'info', 'field_5': 'None', '#fid': 9, '#geometry': 'None', }, 3009: { 'id': 'None', 'description': 'Extra fields', 'data': 'None', 'info': 'info', 'field_5': 'None', '#fid': 9, '#geometry': 'None', }, 4009: { 'id': 'None', 'description': 'Extra fields', 'data': 'None', 'info': 'info', 'field_5': 'None', '#fid': 9, '#geometry': 'None', }, 5009: { 'id': 'None', 'description': 'None', 'data': 'None', 'info': 'None', 'field_5': 'None', '#fid': 9, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_028_substring_test(): wanted = {} wanted['uri'] = 'file://test.csv?geomType=none&type=csv&subset=id%20%25%202%20%3D%201' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Basic unquoted record', 'data': 'Some data', 'info': 'Some info', 'field_5': 'NULL', '#fid': 2, '#geometry': 'None', }, 4: { 'id': '3', 'description': 'Escaped quotes', 'data': 'Quoted "citation" data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 4, '#geometry': 'None', }, 9: { 'id': '5', 'description': 'Extra fields', 'data': 'data', 'info': 'info', 'field_5': 'message', '#fid': 9, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_029_file_watcher(): wanted = {} wanted['uri'] = 'file://file?geomType=none&type=csv&watchFile=yes' wanted['fieldTypes'] = ['integer', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 3: { 'id': '2', 'description': 'pooh', 'name': 'pooh', '#fid': 3, '#geometry': 'None', }, 1002: { 'id': '1', 'description': 'rabbit', 'name': 'rabbit', '#fid': 2, '#geometry': 'None', }, 1003: { 'id': '2', 'description': 'pooh', 'name': 'pooh', '#fid': 3, '#geometry': 'None', }, 4003: { 'id': '2', 'description': 'pooh', 'name': 'pooh', '#fid': 3, '#geometry': 'None', }, 5004: { 'id': '3', 'description': 'tiger', 'name': 'tiger', '#fid': 4, '#geometry': 'None', }, 6002: { 'id': '1', 'description': 'rabbit', 'name': 'rabbit', '#fid': 2, '#geometry': 'None', }, 6003: { 'id': '2', 'description': 'pooh', 'name': 'pooh', '#fid': 3, '#geometry': 'None', }, 6004: { 'id': '3', 'description': 'tiger', 'name': 'tiger', '#fid': 4, '#geometry': 'None', }, 9002: { 'id': '5', 'description': 'toad', 'name': 'toad', '#fid': 2, '#geometry': 'None', }, 10002: { 'id': '5', 'description': 'toad', 'name': 'toad', '#fid': 2, '#geometry': 'None', }, 10003: { 'id': '6', 'description': 'mole', 'name': 'mole', '#fid': 3, '#geometry': 'None', }, 10004: { 'id': '7', 'description': 'badger', 'name': 'badger', '#fid': 4, '#geometry': 'None', }, 16002: { 'id': '5', 'description': 'toad', 'name': 'toad', '#fid': 2, '#geometry': 'None', }, } wanted['log'] = [ 'Request 2 did not return any data', 'Request 7 did not return any data', 'Request 11 did not return any data', 'Request 13 did not return any data', 'Request 14 did not return any data', 'Errors in file temp_file', 'The file has been updated by another application - reloading', 'Errors in file temp_file', 'The file has been updated by another application - reloading', 'Errors in file temp_file', 'The file has been updated by another application - reloading', ] return wanted def test_030_filter_rect_xy_spatial_index(): wanted = {} wanted['uri'] = 'file://testextpt.txt?spatialIndex=Y&yField=y&delimiter=|&type=csv&xField=x' wanted['fieldTypes'] = ['integer', 'text', 'integer', 'integer'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': '1', 'description': 'Inside', 'x': '15', 'y': '35', '#fid': 2, '#geometry': 'Point (15 35)', }, 10: { 'id': '9', 'description': 'Inside 2', 'x': '25', 'y': '45', '#fid': 10, '#geometry': 'Point (25 45)', }, 1002: { 'id': '1', 'description': 'Inside', 'x': '15', 'y': '35', '#fid': 2, '#geometry': 'Point (15 35)', }, 1010: { 'id': '9', 'description': 'Inside 2', 'x': '25', 'y': '45', '#fid': 10, '#geometry': 'Point (25 45)', }, 3002: { 'id': '1', 'description': 'Inside', 'x': '15', 'y': '35', '#fid': 2, '#geometry': 'Point (15 35)', }, 3003: { 'id': '2', 'description': 'Outside 1', 'x': '5', 'y': '35', '#fid': 3, '#geometry': 'Point (5 35)', }, 3004: { 'id': '3', 'description': 'Outside 2', 'x': '5', 'y': '55', '#fid': 4, '#geometry': 'Point (5 55)', }, 3005: { 'id': '4', 'description': 'Outside 3', 'x': '15', 'y': '55', '#fid': 5, '#geometry': 'Point (15 55)', }, 3006: { 'id': '5', 'description': 'Outside 4', 'x': '35', 'y': '55', '#fid': 6, '#geometry': 'Point (35 55)', }, 3007: { 'id': '6', 'description': 'Outside 5', 'x': '35', 'y': '45', '#fid': 7, '#geometry': 'Point (35 45)', }, 3008: { 'id': '7', 'description': 'Outside 7', 'x': '35', 'y': '25', '#fid': 8, '#geometry': 'Point (35 25)', }, 3009: { 'id': '8', 'description': 'Outside 8', 'x': '15', 'y': '25', '#fid': 9, '#geometry': 'Point (15 25)', }, 3010: { 'id': '9', 'description': 'Inside 2', 'x': '25', 'y': '45', '#fid': 10, '#geometry': 'Point (25 45)', }, 4002: { 'id': '1', 'description': 'Inside', 'x': '15', 'y': '35', '#fid': 2, '#geometry': 'Point (15 35)', }, 4003: { 'id': '2', 'description': 'Outside 1', 'x': '5', 'y': '35', '#fid': 3, '#geometry': 'Point (5 35)', }, 4004: { 'id': '3', 'description': 'Outside 2', 'x': '5', 'y': '55', '#fid': 4, '#geometry': 'Point (5 55)', }, 4005: { 'id': '4', 'description': 'Outside 3', 'x': '15', 'y': '55', '#fid': 5, '#geometry': 'Point (15 55)', }, 4006: { 'id': '5', 'description': 'Outside 4', 'x': '35', 'y': '55', '#fid': 6, '#geometry': 'Point (35 55)', }, 4007: { 'id': '6', 'description': 'Outside 5', 'x': '35', 'y': '45', '#fid': 7, '#geometry': 'Point (35 45)', }, 4008: { 'id': '7', 'description': 'Outside 7', 'x': '35', 'y': '25', '#fid': 8, '#geometry': 'Point (35 25)', }, 4009: { 'id': '8', 'description': 'Outside 8', 'x': '15', 'y': '25', '#fid': 9, '#geometry': 'Point (15 25)', }, 4010: { 'id': '9', 'description': 'Inside 2', 'x': '25', 'y': '45', '#fid': 10, '#geometry': 'Point (25 45)', }, } wanted['log'] = [ 'Request 2 did not return any data', ] return wanted def test_031_filter_rect_wkt_spatial_index(): wanted = {} wanted['uri'] = 'file://testextw.txt?spatialIndex=Y&delimiter=|&type=csv&wktField=wkt' wanted['fieldTypes'] = ['integer', 'text'] wanted['geometryType'] = 1 wanted['data'] = { 2: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 4: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 5: { 'id': '4', 'description': 'Bounding box overlap', '#fid': 5, '#geometry': 'LineString (5 30, 5 55, 30 55)', }, 6: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 7: { 'id': '6', 'description': 'Bounding box overlap 2', '#fid': 7, '#geometry': 'LineString (28 29, 31 29, 31 33)', }, 1002: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 1004: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 1006: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 3002: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 3003: { 'id': '2', 'description': 'Outside', '#fid': 3, '#geometry': 'LineString (0 0, 0 10)', }, 3004: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 3005: { 'id': '4', 'description': 'Bounding box overlap', '#fid': 5, '#geometry': 'LineString (5 30, 5 55, 30 55)', }, 3006: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 3007: { 'id': '6', 'description': 'Bounding box overlap 2', '#fid': 7, '#geometry': 'LineString (28 29, 31 29, 31 33)', }, 4002: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 4003: { 'id': '2', 'description': 'Outside', '#fid': 3, '#geometry': 'LineString (0 0, 0 10)', }, 4004: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 4005: { 'id': '4', 'description': 'Bounding box overlap', '#fid': 5, '#geometry': 'LineString (5 30, 5 55, 30 55)', }, 4006: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 4007: { 'id': '6', 'description': 'Bounding box overlap 2', '#fid': 7, '#geometry': 'LineString (28 29, 31 29, 31 33)', }, } wanted['log'] = [ 'Request 2 did not return any data', ] return wanted def test_032_filter_rect_wkt_create_spatial_index(): wanted = {} wanted['uri'] = 'file://testextw.txt?delimiter=|&type=csv&wktField=wkt' wanted['fieldTypes'] = ['integer', 'text'] wanted['geometryType'] = 1 wanted['data'] = { 2: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 4: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 5: { 'id': '4', 'description': 'Bounding box overlap', '#fid': 5, '#geometry': 'LineString (5 30, 5 55, 30 55)', }, 6: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 7: { 'id': '6', 'description': 'Bounding box overlap 2', '#fid': 7, '#geometry': 'LineString (28 29, 31 29, 31 33)', }, 1002: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 1003: { 'id': '2', 'description': 'Outside', '#fid': 3, '#geometry': 'LineString (0 0, 0 10)', }, 1004: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 1005: { 'id': '4', 'description': 'Bounding box overlap', '#fid': 5, '#geometry': 'LineString (5 30, 5 55, 30 55)', }, 1006: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 1007: { 'id': '6', 'description': 'Bounding box overlap 2', '#fid': 7, '#geometry': 'LineString (28 29, 31 29, 31 33)', }, 3002: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 3004: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 3005: { 'id': '4', 'description': 'Bounding box overlap', '#fid': 5, '#geometry': 'LineString (5 30, 5 55, 30 55)', }, 3006: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 3007: { 'id': '6', 'description': 'Bounding box overlap 2', '#fid': 7, '#geometry': 'LineString (28 29, 31 29, 31 33)', }, 4002: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 4004: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 4006: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 6002: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 6003: { 'id': '2', 'description': 'Outside', '#fid': 3, '#geometry': 'LineString (0 0, 0 10)', }, 6004: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 6005: { 'id': '4', 'description': 'Bounding box overlap', '#fid': 5, '#geometry': 'LineString (5 30, 5 55, 30 55)', }, 6006: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 6007: { 'id': '6', 'description': 'Bounding box overlap 2', '#fid': 7, '#geometry': 'LineString (28 29, 31 29, 31 33)', }, 7002: { 'id': '1', 'description': 'Inside', '#fid': 2, '#geometry': 'LineString (12 32, 28 48)', }, 7003: { 'id': '2', 'description': 'Outside', '#fid': 3, '#geometry': 'LineString (0 0, 0 10)', }, 7004: { 'id': '3', 'description': 'Crossing', '#fid': 4, '#geometry': 'LineString (5 30, 30 55)', }, 7005: { 'id': '4', 'description': 'Bounding box overlap', '#fid': 5, '#geometry': 'LineString (5 30, 5 55, 30 55)', }, 7006: { 'id': '5', 'description': 'Crossing 2', '#fid': 6, '#geometry': 'LineString (25 35, 35 35)', }, 7007: { 'id': '6', 'description': 'Bounding box overlap 2', '#fid': 7, '#geometry': 'LineString (28 29, 31 29, 31 33)', }, } wanted['log'] = [ 'Request 5 did not return any data', ] return wanted def test_033_reset_subset_string(): wanted = {} wanted['uri'] = 'file://test.csv?geomType=none&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Basic unquoted record', 'data': 'Some data', 'info': 'Some info', 'field_5': 'NULL', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Quoted field', 'data': 'Quoted data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 3, '#geometry': 'None', }, 4: { 'id': '3', 'description': 'Escaped quotes', 'data': 'Quoted "citation" data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 4, '#geometry': 'None', }, 5: { 'id': '4', 'description': 'Quoted newlines', 'data': 'Line 1\nLine 2\n\nLine 4', 'info': 'No data', 'field_5': 'NULL', '#fid': 5, '#geometry': 'None', }, 9: { 'id': '5', 'description': 'Extra fields', 'data': 'data', 'info': 'info', 'field_5': 'message', '#fid': 9, '#geometry': 'None', }, 10: { 'id': '6', 'description': 'Missing fields', 'data': 'NULL', 'info': 'NULL', 'field_5': 'NULL', '#fid': 10, '#geometry': 'None', }, 2002: { 'id': '1', 'description': 'Basic unquoted record', 'data': 'Some data', 'info': 'Some info', 'field_5': 'NULL', '#fid': 2, '#geometry': 'None', }, 2004: { 'id': '3', 'description': 'Escaped quotes', 'data': 'Quoted "citation" data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 4, '#geometry': 'None', }, 2009: { 'id': '5', 'description': 'Extra fields', 'data': 'data', 'info': 'info', 'field_5': 'message', '#fid': 9, '#geometry': 'None', }, 4010: { 'id': '6', 'description': 'Missing fields', 'data': 'NULL', 'info': 'NULL', 'field_5': 'NULL', '#fid': 10, '#geometry': 'None', }, 6004: { 'id': '3', 'description': 'Escaped quotes', 'data': 'Quoted "citation" data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 4, '#geometry': 'None', }, 8002: { 'id': '1', 'description': 'Basic unquoted record', 'data': 'Some data', 'info': 'Some info', 'field_5': 'NULL', '#fid': 2, '#geometry': 'None', }, 8004: { 'id': '3', 'description': 'Escaped quotes', 'data': 'Quoted "citation" data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 4, '#geometry': 'None', }, 8009: { 'id': '5', 'description': 'Extra fields', 'data': 'data', 'info': 'info', 'field_5': 'message', '#fid': 9, '#geometry': 'None', }, 10003: { 'id': '2', 'description': 'Quoted field', 'data': 'Quoted data', 'info': 'Unquoted', 'field_5': 'NULL', '#fid': 3, '#geometry': 'None', }, 10005: { 'id': '4', 'description': 'Quoted newlines', 'data': 'Line 1\nLine 2\n\nLine 4', 'info': 'No data', 'field_5': 'NULL', '#fid': 5, '#geometry': 'None', }, 10010: { 'id': '6', 'description': 'Missing fields', 'data': 'NULL', 'info': 'NULL', 'field_5': 'NULL', '#fid': 10, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_034_csvt_file(): wanted = {} wanted['uri'] = 'file://testcsvt.csv?geomType=none&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'integer', 'double', 'text', 'text', 'text', 'text', 'text', 'text', 'longlong', 'longlong'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Test csvt 1', 'fint': '1', 'freal': '1.2', 'fstr': '1', 'fstr_1': 'text', 'fdatetime': '2015-03-02T12:30:00', 'fdate': '2014-12-30', 'ftime': '23:55', 'flong': '-456', 'flonglong': '-678', 'field_12': 'NULL', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Test csvt 2', 'fint': '3', 'freal': '1.5', 'fstr': '99', 'fstr_1': '23.5', 'fdatetime': '80', 'fdate': '2015-03-28', 'ftime': '2014-12-30', 'flong': '01:55', 'flonglong': '9189304972279762602', 'field_12': '-3123724580211819352', '#fid': 3, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_035_csvt_file2(): wanted = {} wanted['uri'] = 'file://testcsvt2.txt?geomType=none&delimiter=|&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'integer', 'double', 'integer', 'text', 'integer'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Test csvt 1', 'f1': '1', 'f2': '1.2', 'f3': '1', 'f4': 'text', 'f5': 'NULL', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Test csvt 2', 'f1': '3', 'f2': '1.5', 'f3': '99', 'f4': '23.5', 'f5': '80', '#fid': 3, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_036_csvt_file_invalid_types(): wanted = {} wanted['uri'] = 'file://testcsvt3.csv?geomType=none&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'integer', 'double', 'integer', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Test csvt 1', 'f1': '1', 'f2': '1.2', 'f3': '1', 'f4': 'text', 'f5': 'times', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Test csvt 2', 'f1': '3', 'f2': '1.5', 'f3': '99', 'f4': '23.5', 'f5': '80', '#fid': 3, '#geometry': 'None', }, } wanted['log'] = [ 'Errors in file testcsvt3.csv', 'File type string in testcsvt3.csvt is not correctly formatted', ] return wanted def test_037_csvt_file_invalid_file(): wanted = {} wanted['uri'] = 'file://testcsvt4.csv?geomType=none&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'integer', 'double', 'integer', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Test csvt 1', 'f1': '1', 'f2': '1.2', 'f3': '1', 'f4': 'text', 'f5': 'times', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Test csvt 2', 'f1': '3', 'f2': '1.5', 'f3': '99', 'f4': '23.5', 'f5': '80', '#fid': 3, '#geometry': 'None', }, } wanted['log'] = [] return wanted def test_038_type_inference(): wanted = {} wanted['uri'] = 'file://testtypes.csv?yField=lat&xField=lon&type=csv' wanted['fieldTypes'] = ['text', 'double', 'double', 'text', 'text', 'integer', 'longlong', 'double', 'text'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': 'line1', 'description': '1.0', 'lon': '1.0', 'lat': '1.0', 'empty': 'NULL', 'text': 'NULL', 'int': '0', 'longlong': '0', 'real': 'NULL', 'text2': '1', '#fid': 2, '#geometry': 'Point (1 1)', }, 3: { 'id': 'line2', 'description': '1.0', 'lon': '1.0', 'lat': '5.0', 'empty': 'NULL', 'text': '1', 'int': 'NULL', 'longlong': '9189304972279762602', 'real': '1.3', 'text2': '-4', '#fid': 3, '#geometry': 'Point (1 5)', }, 4: { 'id': 'line3', 'description': '5.0', 'lon': '5.0', 'lat': '5.0', 'empty': 'NULL', 'text': '1xx', 'int': '2', 'longlong': '345', 'real': '2.0', 'text2': '1x', '#fid': 4, '#geometry': 'Point (5 5)', }, 5: { 'id': 'line4', 'description': '5.0', 'lon': '5.0', 'lat': '1.0', 'empty': 'NULL', 'text': 'A string', 'int': '-3456', 'longlong': '-3123724580211819352', 'real': '-123.56', 'text2': 'NULL', '#fid': 5, '#geometry': 'Point (5 1)', }, 6: { 'id': 'line5', 'description': '3.0', 'lon': '3.0', 'lat': '1.0', 'empty': 'NULL', 'text': 'NULL', 'int': 'NULL', 'longlong': 'NULL', 'real': '0.00023', 'text2': '23', '#fid': 6, '#geometry': 'Point (3 1)', }, 7: { 'id': 'line6', 'description': '1.0', 'lon': '1.0', 'lat': '3.0', 'empty': 'NULL', 'text': '1.5', 'int': '9', 'longlong': '42', 'real': '99.0', 'text2': '0', '#fid': 7, '#geometry': 'Point (1 3)', }, } wanted['log'] = [] return wanted def test_039_issue_13749(): wanted = {} wanted['uri'] = 'file://test13749.csv?yField=geom_y&xField=geom_x&type=csv' wanted['fieldTypes'] = ['integer', 'text', 'double', 'double'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': '1', 'description': 'No geom', 'geom_x': 'NULL', 'geom_y': 'NULL', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Point1', 'geom_x': '11.0', 'geom_y': '22.0', '#fid': 3, '#geometry': 'Point (11 22)', }, 4: { 'id': '3', 'description': 'Point2', 'geom_x': '15.0', 'geom_y': '23.0', '#fid': 4, '#geometry': 'Point (15 23)', }, 5: { 'id': '4', 'description': 'Point3', 'geom_x': '13.0', 'geom_y': '23.0', '#fid': 5, '#geometry': 'Point (13 23)', }, } wanted['log'] = [ 'Errors in file test13749.csv', '1 records have missing geometry definitions', ] return wanted def test_040_issue_14666(): wanted = {} wanted['uri'] = 'file://test14666.csv?yField=y&xField=x&type=csv&delimiter=\\t' wanted['fieldTypes'] = ['integer', 'double', 'double'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': '1', 'description': '7.15417', 'x': '7.15417', 'y': '50.680622', '#fid': 2, '#geometry': 'Point (7.1541699999999997 50.68062199999999962)', }, 3: { 'id': '2', 'description': '7.119219', 'x': '7.119219', 'y': '50.739814', '#fid': 3, '#geometry': 'Point (7.11921900000000019 50.73981400000000264)', }, 4: { 'id': '3', 'description': 'NULL', 'x': 'NULL', 'y': 'NULL', '#fid': 4, '#geometry': 'None', }, 5: { 'id': '4', 'description': 'NULL', 'x': 'NULL', 'y': 'NULL', '#fid': 5, '#geometry': 'None', }, 6: { 'id': '5', 'description': '7.129229', 'x': '7.129229', 'y': '50.703692', '#fid': 6, '#geometry': 'Point (7.12922899999999959 50.70369199999999665)', }, } wanted['log'] = [ 'Errors in file test14666.csv', '2 records have missing geometry definitions', ] return wanted def test_041_no_detect_type(): wanted = {} wanted['uri'] = 'file://testtypes.csv?yField=lat&xField=lon&type=csv&detectTypes=no' wanted['fieldTypes'] = ['text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 0 wanted['data'] = { 2: { 'id': 'line1', 'description': '1.0', 'lon': '1.0', 'lat': '1.0', 'empty': 'NULL', 'text': 'NULL', 'int': '0', 'longlong': '0', 'real': 'NULL', 'text2': '1', '#fid': 2, '#geometry': 'Point (1 1)', }, 3: { 'id': 'line2', 'description': '1.0', 'lon': '1.0', 'lat': '5.0', 'empty': 'NULL', 'text': '1', 'int': 'NULL', 'longlong': '9189304972279762602', 'real': '1.3', 'text2': '-4', '#fid': 3, '#geometry': 'Point (1 5)', }, 4: { 'id': 'line3', 'description': '5.0', 'lon': '5.0', 'lat': '5.0', 'empty': 'NULL', 'text': '1xx', 'int': '2', 'longlong': '345', 'real': '2', 'text2': '1x', '#fid': 4, '#geometry': 'Point (5 5)', }, 5: { 'id': 'line4', 'description': '5.0', 'lon': '5.0', 'lat': '1.0', 'empty': 'NULL', 'text': 'A string', 'int': '-3456', 'longlong': '-3123724580211819352', 'real': '-123.56', 'text2': 'NULL', '#fid': 5, '#geometry': 'Point (5 1)', }, 6: { 'id': 'line5', 'description': '3.0', 'lon': '3.0', 'lat': '1.0', 'empty': 'NULL', 'text': 'NULL', 'int': 'NULL', 'longlong': 'NULL', 'real': '23e-5', 'text2': '23', '#fid': 6, '#geometry': 'Point (3 1)', }, 7: { 'id': 'line6', 'description': '1.0', 'lon': '1.0', 'lat': '3.0', 'empty': 'NULL', 'text': '1.5', 'int': '9', 'longlong': '42', 'real': '99', 'text2': '0', '#fid': 7, '#geometry': 'Point (1 3)', }, } wanted['log'] = [ ] return wanted def test_042_no_detect_types_csvt(): wanted = {} wanted['uri'] = 'file://testcsvt.csv?geomType=none&type=csv&detectTypes=no' wanted['fieldTypes'] = ['integer', 'text', 'integer', 'double', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text'] wanted['geometryType'] = 4 wanted['data'] = { 2: { 'id': '1', 'description': 'Test csvt 1', 'fint': '1', 'freal': '1.2', 'fstr': '1', 'fstr_1': 'text', 'fdatetime': '2015-03-02T12:30:00', 'fdate': '2014-12-30', 'ftime': '23:55', 'flong': '-456', 'flonglong': '-678', 'field_12': 'NULL', '#fid': 2, '#geometry': 'None', }, 3: { 'id': '2', 'description': 'Test csvt 2', 'fint': '3', 'freal': '1.5', 'fstr': '99', 'fstr_1': '23.5', 'fdatetime': '80', 'fdate': '2015-03-28', 'ftime': '2014-12-30', 'flong': '01:55', 'flonglong': '9189304972279762602', 'field_12': '-3123724580211819352', '#fid': 3, '#geometry': 'None', }, } wanted['log'] = [ ] return wanted
gpl-2.0
7,868,254,456,550,130,000
27.20703
139
0.376431
false
deepmind/acme
acme/agents/jax/dqn/losses.py
1
9923
# python3 # Copyright 2018 DeepMind Technologies Limited. 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. """DQN losses.""" from typing import Tuple from acme import types from acme.agents.jax.dqn import learning_lib from acme.jax import networks as networks_lib import dataclasses import jax import jax.numpy as jnp import reverb import rlax @dataclasses.dataclass class PrioritizedDoubleQLearning(learning_lib.LossFn): """Clipped double q learning with prioritization on TD error.""" discount: float = 0.99 importance_sampling_exponent: float = 0.2 max_abs_reward: float = 1. huber_loss_parameter: float = 1. def __call__( self, network: networks_lib.FeedForwardNetwork, params: networks_lib.Params, target_params: networks_lib.Params, batch: reverb.ReplaySample, key: networks_lib.PRNGKey, ) -> Tuple[jnp.DeviceArray, learning_lib.LossExtra]: """Calculate a loss on a single batch of data.""" del key transitions: types.Transition = batch.data keys, probs, *_ = batch.info # Forward pass. q_tm1 = network.apply(params, transitions.observation) q_t_value = network.apply(target_params, transitions.next_observation) q_t_selector = network.apply(params, transitions.next_observation) # Cast and clip rewards. d_t = (transitions.discount * self.discount).astype(jnp.float32) r_t = jnp.clip(transitions.reward, -self.max_abs_reward, self.max_abs_reward).astype(jnp.float32) # Compute double Q-learning n-step TD-error. batch_error = jax.vmap(rlax.double_q_learning) td_error = batch_error(q_tm1, transitions.action, r_t, d_t, q_t_value, q_t_selector) batch_loss = rlax.huber_loss(td_error, self.huber_loss_parameter) # Importance weighting. importance_weights = (1. / probs).astype(jnp.float32) importance_weights **= self.importance_sampling_exponent importance_weights /= jnp.max(importance_weights) # Reweight. loss = jnp.mean(importance_weights * batch_loss) # [] reverb_update = learning_lib.ReverbUpdate( keys=keys, priorities=jnp.abs(td_error).astype(jnp.float64)) extra = learning_lib.LossExtra(metrics={}, reverb_update=reverb_update) return loss, extra @dataclasses.dataclass class PrioritizedCategoricalDoubleQLearning(learning_lib.LossFn): """Categorical double q learning with prioritization on TD error.""" discount: float = 0.99 importance_sampling_exponent: float = 0.2 max_abs_reward: float = 1. def __call__( self, network: networks_lib.FeedForwardNetwork, params: networks_lib.Params, target_params: networks_lib.Params, batch: reverb.ReplaySample, key: networks_lib.PRNGKey, ) -> Tuple[jnp.DeviceArray, learning_lib.LossExtra]: """Calculate a loss on a single batch of data.""" del key transitions: types.Transition = batch.data keys, probs, *_ = batch.info # Forward pass. _, logits_tm1, atoms_tm1 = network.apply(params, transitions.observation) _, logits_t, atoms_t = network.apply(target_params, transitions.next_observation) q_t_selector, _, _ = network.apply(params, transitions.next_observation) # Cast and clip rewards. d_t = (transitions.discount * self.discount).astype(jnp.float32) r_t = jnp.clip(transitions.reward, -self.max_abs_reward, self.max_abs_reward).astype(jnp.float32) # Compute categorical double Q-learning loss. batch_loss_fn = jax.vmap( rlax.categorical_double_q_learning, in_axes=(None, 0, 0, 0, 0, None, 0, 0)) batch_loss = batch_loss_fn(atoms_tm1, logits_tm1, transitions.action, r_t, d_t, atoms_t, logits_t, q_t_selector) # Importance weighting. importance_weights = (1. / probs).astype(jnp.float32) importance_weights **= self.importance_sampling_exponent importance_weights /= jnp.max(importance_weights) # Reweight. loss = jnp.mean(importance_weights * batch_loss) # [] reverb_update = learning_lib.ReverbUpdate( keys=keys, priorities=jnp.abs(batch_loss).astype(jnp.float64)) extra = learning_lib.LossExtra(metrics={}, reverb_update=reverb_update) return loss, extra @dataclasses.dataclass class QLearning(learning_lib.LossFn): """Clipped q learning. This matches the original DQN loss: https://arxiv.org/abs/1312.5602. """ discount: float = 0.99 max_abs_reward: float = 1. huber_loss_parameter: float = 1. def __call__( self, network: networks_lib.FeedForwardNetwork, params: networks_lib.Params, target_params: networks_lib.Params, batch: reverb.ReplaySample, key: networks_lib.PRNGKey, ) -> Tuple[jnp.DeviceArray, learning_lib.LossExtra]: """Calculate a loss on a single batch of data.""" del key transitions: types.Transition = batch.data # Forward pass. q_tm1 = network.apply(params, transitions.observation) q_t = network.apply(target_params, transitions.next_observation) # Cast and clip rewards. d_t = (transitions.discount * self.discount).astype(jnp.float32) r_t = jnp.clip(transitions.reward, -self.max_abs_reward, self.max_abs_reward).astype(jnp.float32) # Compute Q-learning TD-error. batch_error = jax.vmap(rlax.q_learning) td_error = batch_error(q_tm1, transitions.action, r_t, d_t, q_t) batch_loss = rlax.huber_loss(td_error, self.huber_loss_parameter) loss = jnp.mean(batch_loss) extra = learning_lib.LossExtra(metrics={}) return loss, extra @dataclasses.dataclass class RegularizedQLearning(learning_lib.LossFn): """Regularized Q-learning. Implements DQNReg loss function: https://arxiv.org/abs/2101.03958. This is almost identical to QLearning except: 1) Adds a regularization term; 2) Uses vanilla TD error without huber loss. 3) No reward clipping. """ discount: float = 0.99 regularizer_coeff = 0.1 def __call__( self, network: networks_lib.FeedForwardNetwork, params: networks_lib.Params, target_params: networks_lib.Params, batch: reverb.ReplaySample, key: networks_lib.PRNGKey, ) -> Tuple[jnp.DeviceArray, learning_lib.LossExtra]: """Calculate a loss on a single batch of data.""" del key transitions: types.Transition = batch.data # Forward pass. q_tm1 = network.apply(params, transitions.observation) q_t = network.apply(target_params, transitions.next_observation) d_t = (transitions.discount * self.discount).astype(jnp.float32) # Compute Q-learning TD-error. batch_error = jax.vmap(rlax.q_learning) td_error = batch_error( q_tm1, transitions.action, transitions.reward, d_t, q_t) td_error = 0.5 * jnp.square(td_error) def select(qtm1, action): return qtm1[action] q_regularizer = jax.vmap(select)(q_tm1, transitions.action) loss = self.regularizer_coeff * jnp.mean(q_regularizer) + jnp.mean(td_error) extra = learning_lib.LossExtra(metrics={}) return loss, extra @dataclasses.dataclass class MunchausenQLearning(learning_lib.LossFn): """Munchausen q learning. Implements M-DQN: https://arxiv.org/abs/2007.14430. """ entropy_temperature: float = 0.03 # tau parameter munchausen_coefficient: float = 0.9 # alpha parameter clip_value_min: float = -1e3 discount: float = 0.99 max_abs_reward: float = 1. huber_loss_parameter: float = 1. def __call__( self, network: networks_lib.FeedForwardNetwork, params: networks_lib.Params, target_params: networks_lib.Params, batch: reverb.ReplaySample, key: networks_lib.PRNGKey, ) -> Tuple[jnp.DeviceArray, learning_lib.LossExtra]: """Calculate a loss on a single batch of data.""" del key transitions: types.Transition = batch.data # Forward pass. q_online_s = network.apply(params, transitions.observation) action_one_hot = jax.nn.one_hot(transitions.action, q_online_s.shape[-1]) q_online_sa = jnp.sum(action_one_hot * q_online_s, axis=-1) q_target_s = network.apply(target_params, transitions.observation) q_target_next = network.apply(target_params, transitions.next_observation) # Cast and clip rewards. d_t = (transitions.discount * self.discount).astype(jnp.float32) r_t = jnp.clip(transitions.reward, -self.max_abs_reward, self.max_abs_reward).astype(jnp.float32) # Munchausen term : tau * log_pi(a|s) munchausen_term = self.entropy_temperature * jax.nn.log_softmax( q_target_s / self.entropy_temperature, axis=-1) munchausen_term_a = jnp.sum(action_one_hot * munchausen_term, axis=-1) munchausen_term_a = jnp.clip(munchausen_term_a, a_min=self.clip_value_min, a_max=0.) # Soft Bellman operator applied to q next_v = self.entropy_temperature * jax.nn.logsumexp( q_target_next / self.entropy_temperature, axis=-1) target_q = jax.lax.stop_gradient(r_t + self.munchausen_coefficient * munchausen_term_a + d_t * next_v) batch_loss = rlax.huber_loss(target_q - q_online_sa, self.huber_loss_parameter) loss = jnp.mean(batch_loss) extra = learning_lib.LossExtra(metrics={}) return loss, extra
apache-2.0
4,293,536,317,619,817,500
35.616236
80
0.675904
false
not-na/peng3d
peng3d/version.py
1
1567
#!/usr/bin/env python # -*- coding: utf-8 -*- # # version.py # # Copyright 2016 notna <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # __all__ = ["VERSION", "RELEASE"] VERSION = "1.11.0" """ Full version number of format ``MAJOR.MINOR.BUGFIX`` where major is increased only on very major feature changes. Minor is changed if a new feature is introduced or an API change is made, while bugfix only changes if an important fix for a bug needs to be provided before the next release. Used to display the version in the title of the documentation. .. seealso:: See the `Distutils docs on version numbers <https://docs.python.org/2/distutils/setupscript.html#additional-meta-data>`_ for more information. """ RELEASE = "1.11.0" """ Currently the same as :py:data:`VERSION`\\ . Used to display the version on the top-right of the documentation. """
gpl-2.0
-3,167,285,708,186,949,600
33.822222
175
0.72559
false
Ryanglambert/pybrain
pybrain/tests/runtests.py
25
4375
#! /usr/bin/env python # -*- coding: utf-8 -*- """Script to run the pybrain testsuite.""" __author__ = 'Justin Bayer, [email protected]' __version__ = '$Id$' import doctest import logging import os import sys from copy import copy from unittest import TestLoader, TestSuite, TextTestRunner def setUpLogging(): logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s') def testImport(module_name): """Tell wether a module can be imported. This function has a cache, so modules are only tested once on importability. """ try: return testImport.cache[module_name] except KeyError: try: __import__(module_name) except ImportError: result = False else: result = True testImport.cache[module_name] = result return result testImport.cache = {} # Import checks are expensive, so cache results def missingDependencies(target_module): """Returns a list of dependencies of the module that the current interpreter cannot import. This does not inspect the code, but instead check for a list of strings called _dependencies in the target_module. This list should contain module names that the module depends on.""" dependencies = getattr(target_module, '_dependencies', []) return [i for i in dependencies if not testImport(i)] def getSubDirectories(testdir): """Recursively builds a list of all subdirectories in the test suite.""" subdirs = [os.path.join(testdir,d) for d in filter(os.path.isdir,[os.path.join(testdir,dd) for dd in os.listdir(testdir)])] for d in copy(subdirs): subdirs.extend(getSubDirectories(os.path.join(testdir,d))) return subdirs def make_test_suite(): """Load unittests placed in pybrain/tests/unittests, then return a TestSuite object of those.""" # [...]/pybrain/pybrain [cut] /tests/runtests.py path = os.path.abspath(__file__).rsplit(os.sep+'tests', 1)[0] sys.path.append(path.rstrip('pybrain')) top_testdir = os.path.join(path, 'tests', 'unittests') testdirs = getSubDirectories(top_testdir) # Initialize the testsuite to add to suite = TestSuite() optionflags = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.IGNORE_EXCEPTION_DETAIL for testdir in testdirs: # All unittest modules have to start with 'test_' and have to be, of # course, python files module_names = [f[:-3] for f in os.listdir(testdir) if f.startswith('test_') and f.endswith('.py')] if not module_names: logging.info('No tests found in %s' % testdir) continue # "Magically" import the tests package and its test-modules that we've # found test_package_path = 'pybrain.tests.unittests' sub_path = os.path.relpath(testdir, top_testdir).split(os.sep) test_package_path = '.'.join([test_package_path]+sub_path) test_package = __import__(test_package_path, fromlist=module_names) # Put the test modules in a list that can be passed to the testsuite modules = (getattr(test_package, n) for n in module_names) modules = [(m, missingDependencies(m)) for m in modules] untests = [(m, md) for m, md in modules if md] modules = [m for m, md in modules if not md] # print(out modules that are missing dependencies) for module, miss_dep in untests: # Mr Dep is not around, though logging.warning('Module %s is missing dependencies: %s' % ( module.__name__, ', '.join(miss_dep))) # print(out a list of tests that are found) for m in modules: logging.info('Tests found: %s' % m.__name__) # Build up the testsuite suite.addTests([TestLoader().loadTestsFromModule(m) for m in modules]) # Add doctests from the unittest modules to the suite for mod in modules: try: suite.addTest(doctest.DocTestSuite(mod, optionflags=optionflags)) except ValueError: # No tests found. pass return suite if __name__ == '__main__': setUpLogging() runner = TextTestRunner() runner.run(make_test_suite())
bsd-3-clause
4,843,262,056,212,950,000
33.179688
99
0.626057
false
couchbaselabs/couchbase-cli
xdcr.py
1
11327
""" Implementation for xdcr management """ import time import os import sys import socket import urllib from usage import usage import restclient import listservers import util_cli as util # Map of HTTP success code, success message and error message for # handling HTTP response properly class XDCR: def __init__(self): self.method = 'POST' self.debug = False self.cluster = '' self.server = '' self.port = '' self.user = '' self.password = '' self.remote_username = '' self.remote_password = '' self.remote_hostname = '' self.remote_cluster = '' self.replication_mode = '' self.cmd = 'create' self.replicator = '' self.params = {} self.output = 'standard' self.from_bucket = '' self.to_bucket = '' self.type = '' self.max_stream = '' self.checkpoint_interval = '' self.worker_batch_size = '' self.doc_batch_size = '' self.failure_restart_interval = '' self.optimistic_replication_threshold = '' # the rest commands and associated URIs for various node operations self.REST_CMDS = { 'xdcr-setup': '/pools/default/remoteClusters', 'xdcr-replicate': '/controller/createReplication', 'setting-xdcr': '/internalSettings' } # Map of operations and the HTTP methods used against the REST interface self.METHODS = { 'xdcr-setup': 'POST', 'xdcr-replicate': 'POST', 'setting-xdcr': 'POST', } def runCmd(self, cmd, server, port, user, password, opts): self.rest_cmd = self.REST_CMDS[cmd] self.method = self.METHODS[cmd] self.server = server self.port = int(port) self.user = user self.password = password self.processOpts(cmd, opts) if self.debug: print "INFO: servers %s" % servers if cmd == 'xdcr-setup': if self.cmd == 'create': self.setup_create() elif self.cmd == 'edit': self.setup_edit() elif self.cmd == 'delete': self.setup_delete() if cmd == 'xdcr-replicate': if self.cmd == 'create': self.replicate_start() elif self.cmd == 'delete': self.replicate_stop() if cmd == 'setting-xdcr': self.setting() def processOpts(self, cmd, opts): """ Set standard opts. note: use of a server key keeps optional args aligned with server. """ for o, a in opts: if o in ('-d', '--debug'): self.debug = True elif o == '--xdcr-cluster-name': self.remote_cluster = a elif o == '--xdcr-hostname': self.remote_hostname = a elif o == '--xdcr-username': self.remote_username = a elif o == '--xdcr-password': self.remote_password = a elif o == '--xdcr-from-bucket': self.from_bucket = a elif o == '--xdcr-to-bucket': self.to_bucket = a elif o == '--xdcr-type': self.type = a elif o == '--xdcr-replicator': self.replicator = a elif o == '--xdcr-replication-mode': self.replication_mode = a elif o == '--create': self.cmd = 'create' elif o == '--edit': self.cmd = 'edit' elif o == '--delete': self.cmd = 'delete' elif o == '--max-concurrent-reps': self.max_stream = int(a) elif o == '--checkpoint-interval': self.checkpoint_interval = int(a) elif o == '--worker-batch-size': self.worker_batch_size = int(a) elif o == '--doc-batch-size': self.doc_batch_size = int(a) elif o == '--failure-restart-interval': self.failure_restart_interval = int(a) elif o == '--optimistic-replication-threshold': self.optimistic_replication_threshold = int(a) def setup_create(self): rest = restclient.RestClient(self.server, self.port, {'debug':self.debug}) if self.remote_cluster: rest.setParam('name', self.remote_cluster) else: rest.setParam('name', 'remote cluster') if self.remote_hostname: rest.setParam('hostname', self.remote_hostname) else: print "Error: hostname (ip) is missing" return if self.remote_username: rest.setParam('username', self.remote_username) else: rest.setParam('username', "username") if self.remote_password: rest.setParam('password', self.remote_password) else: rest.setParam('password', "password") opts = { 'error_msg': "unable to set up xdcr remote site %s" % self.remote_cluster, 'success_msg': "init %s" % self.remote_cluster } output_result = rest.restCmd('POST', self.rest_cmd, self.user, self.password, opts) print output_result def setup_edit(self): rest = restclient.RestClient(self.server, self.port, {'debug':self.debug}) if self.remote_cluster: rest.setParam('name', self.remote_cluster) self.rest_cmd = self.rest_cmd + "/" + self.remote_cluster else: print "Error: Cluster name is needed to edit cluster connections" return if self.remote_hostname: rest.setParam('hostname', self.remote_hostname) else: print "Error: hostname (ip) is missing" return if self.remote_username: rest.setParam('username', self.remote_username) else: rest.setParam('username', "username") if self.remote_password: rest.setParam('password', self.remote_password) else: rest.setParam('password', "password") opts = { 'error_msg': "unable to edit xdcr remote site %s" % self.remote_cluster, 'success_msg': "edit cluster %s" % self.remote_cluster } output_result = rest.restCmd('POST', self.rest_cmd, self.user, self.password, opts) print output_result def setup_delete(self): rest = restclient.RestClient(self.server, self.port, {'debug':self.debug}) if self.remote_cluster: self.rest_cmd = self.rest_cmd + "/" + self.remote_cluster else: print "Error: Cluster name is needed to delete cluster connections" return opts = { 'error_msg': "unable to delete xdcr remote site %s" % self.server, 'success_msg': "delete %s" % self.remote_cluster } output_result = rest.restCmd('DELETE', self.rest_cmd, self.user, self.password, opts) print output_result def replicate_start(self): rest = restclient.RestClient(self.server, self.port, {'debug':self.debug}) if self.to_bucket: rest.setParam('toBucket', self.to_bucket) if self.remote_cluster: rest.setParam('toCluster', self.remote_cluster) if self.from_bucket: rest.setParam('fromBucket', self.from_bucket) if self.replication_mode: rest.setParam('type', self.replication_mode) rest.setParam('replicationType', 'continuous') opts = { 'error_msg': "unable to create replication", 'success_msg': "start replication" } output_result = rest.restCmd(self.method, self.rest_cmd, self.user, self.password, opts) print output_result def replicate_stop(self): rest = restclient.RestClient(self.server, self.port, {'debug':self.debug}) if self.replicator: self.rest_cmd = '/controller/cancelXCDR/' + urllib.quote_plus(self.replicator) else: print "Error: option --xdcr-replicator is needed to delete a replication" return opts = { 'error_msg': "unable to delete replication", 'success_msg': "delete replication" } output_result = rest.restCmd('DELETE', self.rest_cmd, self.user, self.password, opts) print output_result def setting(self): rest = restclient.RestClient(self.server, self.port, {'debug':self.debug}) opts = { 'error_msg': "unable to set xdcr internal settings", 'success_msg': "set xdcr settings" } if self.max_stream: rest.setParam('xdcrMaxConcurrentReps', self.max_stream) opts['success_msg'] += ' xdcrMaxConcurrentReps' if self.checkpoint_interval: rest.setParam('xdcrCheckpointInterval', self.checkpoint_interval) opts['success_msg'] += ' xdcrCheckpointInterval' if self.worker_batch_size: rest.setParam('xdcrWorkerBatchSize', self.worker_batch_size) opts['success_msg'] += ' xdcrWorkerBatchSize' if self.doc_batch_size: rest.setParam('xdcrDocBatchSizeKb', self.doc_batch_size) opts['success_msg'] += ' xdcrDocBatchSizeKb' if self.failure_restart_interval: rest.setParam('xdcrFailureRestartInterval', self.failure_restart_interval) opts['success_msg'] += ' xdcrFailureRestartInterval' if self.optimistic_replication_threshold: rest.setParam('xdcrOptimisticReplicationThreshold', self.optimistic_replication_threshold) opts['success_msg'] += ' xdcrOptimisticReplicationThreshold' output_result = rest.restCmd(self.method, self.rest_cmd, self.user, self.password, opts) print output_result
apache-2.0
468,932,708,434,218,200
34.731861
102
0.491745
false
EdPassos/fofix
src/core/Audio.py
3
6990
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä # # 2008 myfingershurt # # # # This program is free software; you can redistribute it and/or # # modify it under the terms of the GNU General Public License # # as published by the Free Software Foundation; either version 2 # # of the License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # # MA 02110-1301, USA. # ##################################################################### import pygame from util import Log from core.Task import Task from audio.MixStream import VorbisFileMixStream import numpy as np #stump: get around some strangeness in pygame when py2exe'd... if not hasattr(pygame.mixer, 'music'): import sys __import__('pygame.mixer_music') pygame.mixer.music = sys.modules['pygame.mixer_music'] class Audio: def pre_open(self, frequency = 22050, bits = 16, stereo = True, bufferSize = 1024): pygame.mixer.pre_init(frequency, -bits, stereo and 2 or 1, bufferSize) return True def open(self, frequency = 22050, bits = 16, stereo = True, bufferSize = 1024): try: pygame.mixer.quit() except: pass try: pygame.mixer.init(frequency, -bits, stereo and 2 or 1, bufferSize) except: Log.warn("Audio setup failed. Trying with default configuration.") pygame.mixer.init() Log.debug("Audio configuration: %s" % str(pygame.mixer.get_init())) #myfingershurt: ensuring we have enough audio channels! pygame.mixer.set_num_channels(10) return True #myfingershurt: def findChannel(self): return pygame.mixer.find_channel() def getChannelCount(self): return pygame.mixer.get_num_channels() def getChannel(self, n): return Channel(n) def close(self): try: pygame.mixer.quit() except: pass def pause(self): pygame.mixer.pause() def unpause(self): pygame.mixer.unpause() class Music(object): def __init__(self, fileName): pygame.mixer.music.load(fileName) @staticmethod def setEndEvent(event = None): if event: pygame.mixer.music.set_endevent(event) else: pygame.mixer.music.set_endevent() #MFH - to set NO event. def play(self, loops = -1, pos = 0.0): pygame.mixer.music.play(loops, pos) def stop(self): pygame.mixer.music.stop() def rewind(self): pygame.mixer.music.rewind() def pause(self): pygame.mixer.music.pause() def unpause(self): pygame.mixer.music.unpause() def setVolume(self, volume): pygame.mixer.music.set_volume(volume) def fadeout(self, time): pygame.mixer.music.fadeout(time) def isPlaying(self): return pygame.mixer.music.get_busy() def getPosition(self): return pygame.mixer.music.get_pos() class Channel(object): def __init__(self, id): self.channel = pygame.mixer.Channel(id) self.id = id def play(self, sound): self.channel.play(sound.sound) def stop(self): self.channel.stop() def setVolume(self, volume): self.channel.set_volume(volume) def fadeout(self, time): self.channel.fadeout(time) class Sound(object): def __init__(self, fileName): self.sound = pygame.mixer.Sound(fileName) def isPlaying(self): #MFH - adding function to check if sound is playing return self.sound.get_num_channels() def play(self, loops = 0): self.sound.play(loops) def stop(self): self.sound.stop() def setVolume(self, volume): self.sound.set_volume(volume) def fadeout(self, time): self.sound.fadeout(time) #stump: mic passthrough class MicrophonePassthroughStream(Sound, Task): def __init__(self, engine, mic): Task.__init__(self) self.engine = engine self.channel = None self.mic = mic self.playing = False self.volume = 1.0 def __del__(self): self.stop() def play(self): if not self.playing: self.engine.addTask(self, synchronized=False) self.playing = True def stop(self): if self.playing: self.channel.stop() self.engine.removeTask(self) self.playing = False def setVolume(self, vol): self.volume = vol def run(self, ticks): chunk = ''.join(self.mic.passthroughQueue) self.mic.passthroughQueue = [] if chunk == '': return data = np.frombuffer(chunk, dtype=np.float32) * 32767.0 playbuf = np.zeros((len(data), 2), dtype=np.int16) playbuf[:, 0] = data playbuf[:, 1] = data snd = pygame.mixer.Sound(buffer(playbuf)) if self.channel is None or not self.channel.get_busy(): self.channel = snd.play() else: self.channel.queue(snd) self.channel.set_volume(self.volume) class StreamingSound(object): def __init__(self, channel, fileName): self._mixstream = VorbisFileMixStream(fileName) self._channel = channel def play(self): self._mixstream.play(self._channel.id) def stop(self): self._mixstream.stop() self._channel.stop() def setVolume(self, volume): self._channel.setVolume(volume) def isPlaying(self): return self._mixstream.is_playing() def fadeout(self, time): # TODO self.stop() def getPosition(self): return self._mixstream.get_position() def setPosition(self, position): return self._mixstream.seek(position) def setPitchBendSemitones(self, semitones): self._mixstream.set_pitch_semitones(semitones) def setSpeed(self, factor): self._mixstream.set_speed(factor)
gpl-2.0
-8,926,700,898,826,511,000
29.25974
87
0.558941
false
formiano/enigma2
lib/python/Components/SelectionList.py
1
2700
from MenuList import MenuList from Tools.Directories import resolveFilename, SCOPE_ACTIVE_SKIN from enigma import eListboxPythonMultiContent, eListbox, gFont, RT_HALIGN_LEFT, RT_VALIGN_CENTER from Tools.LoadPixmap import LoadPixmap import skin selectionpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "skin_default/icons/lock_on.png")) selectiononpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "icons/lock_on.png")) selectionoffpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "icons/lock_off.png")) def SelectionEntryComponent(description, value, index, selected): dx, dy, dw, dh = skin.parameters.get("SelectionListDescr",(25, 3, 650, 30)) res = [ (description, value, index, selected), (eListboxPythonMultiContent.TYPE_TEXT, dx, dy, dw, dh, 0, RT_HALIGN_LEFT, description) ] if selected: ix, iy, iw, ih = skin.parameters.get("SelectionListLock",(0, 2, 25, 24)) res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, ix, iy, iw, ih, selectiononpng)) else: ix, iy, iw, ih = skin.parameters.get("SelectionListLockOff",(0, 2, 25, 24)) res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, ix, iy, iw, ih, selectionoffpng)) ix, iy, iw, ih = skin.parameters.get("SelectionListLock",(0, 2, 25, 24)) res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, ix, iy, iw, ih, selectiononpng)) return res class SelectionList(MenuList): def __init__(self, list = None, enableWrapAround = False): MenuList.__init__(self, list or [], enableWrapAround, content = eListboxPythonMultiContent) font = skin.fonts.get("SelectionList", ("Regular", 20, 30)) self.l.setFont(0, gFont(font[0], font[1])) self.l.setItemHeight(font[2]) def addSelection(self, description, value, index, selected = True): self.list.append(SelectionEntryComponent(description, value, index, selected)) self.setList(self.list) def toggleSelection(self): if len(self.list) > 0: idx = self.getSelectedIndex() item = self.list[idx][0] self.list[idx] = SelectionEntryComponent(item[0], item[1], item[2], not item[3]) self.setList(self.list) def getSelectionsList(self): return [ (item[0][0], item[0][1], item[0][2]) for item in self.list if item[0][3] ] def toggleAllSelection(self): for idx,item in enumerate(self.list): item = self.list[idx][0] self.list[idx] = SelectionEntryComponent(item[0], item[1], item[2], not item[3]) self.setList(self.list) def sort(self, sortType=False, flag=False): # sorting by sortType: # 0 - description # 1 - value # 2 - index # 3 - selected self.list.sort(key=lambda x: x[0][sortType],reverse=flag) self.setList(self.list)
gpl-2.0
-658,971,469,564,425,500
43.262295
113
0.722593
false
Alternhuman/marcopolo
marcopolo/marco/marcobinding.py
1
3335
from __future__ import absolute_import from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import socket, sys, json, logging, os from os import path from copy import copy import six from marcopolo.marco_conf import utils from marcopolo.marco import conf from marcopolo.marco.marco import Marco, MarcoException class MarcoBinding(DatagramProtocol): """ Twisted class for an asynchronous socket server """ def __init__(self): self.marco = Marco() #Own instance of Marco def __del__(self): del self.marco def graceful_shutdown(self): logging.info('Stopping service marcod') def startProtocol(self): reactor.addSystemEventTrigger('before', 'shutdown', self.graceful_shutdown) def marcoInThread(self, command, address): nodes = [] nodes = self.marco.marco(max_nodes=command.get("max_nodes", None), exclude=command.get("exclude", []), timeout=command.get("timeout", None), params=command.get("params", {}), group=command.get("group", conf.MULTICAST_ADDR) ) self.transport.write(json.dumps([{"Address":n.address, "Params": n.params} for n in nodes]).encode('utf-8'), address) def requestForInThread(self, command, address): nodes = self.marco.request_for(command["Params"], max_nodes=command.get("max_nodes", None), exclude=command.get("exclude", []), params=command.get("params", {}), timeout=command.get("timeout", None)) if len(nodes) > 0: self.transport.write(json.dumps( [{"Address": n.address, "Params": n.params} for n in nodes]).encode('utf-8'), address) else: self.transport.write(json.dumps([]).encode('utf-8'), address) def servicesInThread(self, command, address): services = self.marco.services(addr=command.get("node", None), timeout=command.get("timeout", 0) ) self.transport.write(json.dumps([service for service in services]).encode('utf-8'), address) def datagramReceived(self, data, address): try: command = json.loads(data.decode('utf-8')) except ValueError: return if command.get("Command", None) == None: self.transport.write(json.dumps({"Error": True}).encode('utf-8'), address) else: if command["Command"] == "Marco": reactor.callInThread(self.marcoInThread, command, address) elif command["Command"] == "Request-for" or command["Command"] == "Request-For": reactor.callInThread(self.requestForInThread, command, address) elif command["Command"] == "Services": reactor.callInThread(self.servicesInThread, command, address) else: self.transport.write(json.dumps({"Error": True}).encode('utf-8'), address)
mpl-2.0
7,090,213,677,321,602,000
36.897727
125
0.551724
false
jcnelson/syndicatemail
common/message.py
1
46039
#!/usr/bin/env python """ Copyright 2013 The Trustees of Princeton University Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import storage import network import contact import singleton import keys import syndicate.client.common.log as Log from syndicate.volume import Volume import collections import uuid import hashlib import pprint import os import pickle import base64 import time import math from Crypto.Hash import SHA256 as HashAlg from Crypto.Hash import HMAC from Crypto.PublicKey import RSA as CryptoKey from Crypto.Protocol.KDF import PBKDF2 from Crypto.Signature import PKCS1_PSS as CryptoSigner from Crypto import Random log = Log.get_logger() STORAGE_DIR = "/messages" ATTACHMENTS_DIR = storage.path_join( STORAGE_DIR, "attachments" ) INCOMING_DIR = storage.path_join( STORAGE_DIR, "incoming" ) FOLDERS_DIR = storage.path_join( STORAGE_DIR, "folders" ) INBOX_FOLDER = "Inbox" SENT_FOLDER = "Sent" DRAFTS_FOLDER = "Drafts" SPAM_FOLDER = "Spam" TRASH_FOLDER = "Trash" DEFAULT_FOLDERS = [ INBOX_FOLDER, SENT_FOLDER, DRAFTS_FOLDER, SPAM_FOLDER, TRASH_FOLDER ] # if we list one of these folders, check incoming as well CHECK_INCOMING_FOLDERS = [ INBOX_FOLDER, SPAM_FOLDER ] # for setup VOLUME_STORAGE_DIRS = [ STORAGE_DIR, ATTACHMENTS_DIR, INCOMING_DIR, FOLDERS_DIR ] + [storage.path_join(FOLDERS_DIR, x) for x in DEFAULT_FOLDERS] LOCAL_STORAGE_DIRS = [] # locally-produced message and attachment SyndicateMessage = collections.namedtuple( "SyndicateMessage", ["id", "sender_addr", "receiver_addrs", "cc_addrs", "subject", "body", "timestamp", "handle", "attachment_names", "attachment_signatures", "signature"] ) SyndicateAttachment = collections.namedtuple( "SyndicateAttachment", ["name", "data"] ) # locally-stored record for a message currently hosted on the sender's volume SyndicateIncomingMessage = collections.namedtuple( "SyndicateIncomingMessage", ["id", "sender_addr", "receiver_addrs", "cc_addrs", "subject", "timestamp", "handle", "attachment_names", "verified", "message_signature"] ) # incoming message record sent to the server EncryptedIncomingMessage = collections.namedtuple( "EncryptedIncomingMessage", ["incoming_message_ciphertext", "sender_addr", "receiver_addr", "signature"] ) # given back in a listing SyndicateMessageMetadata = collections.namedtuple( "SyndicateMessageMetadata", ["id", "sender_addr", "receiver_addrs", "cc_addrs", "subject", "timestamp", "handle", "has_attachments", "is_read"] ) #------------------------- def folder_dir_atroot( folder_name ): global FOLDERS_DIR return storage.path_join( FOLDERS_DIR, folder_name ) #------------------------- def folder_dir( folder_name ): global FOLDERS_DIR return storage.volume_path( folder_dir_atroot(folder_name) ) #------------------------- def incoming_dir(): global INCOMING_DIR return storage.volume_path( INCOMING_DIR ) #------------------------- def message_handle( message_timestamp, message_id ): return "%s-%s" % (str(message_timestamp), str(message_id)) #------------------------- def stored_message_path( sender_pubkey_str, folder, message_timestamp, message_id ): # message path for messages hosted on our own Volume sh = hashlib.sha256() sh.update( sender_pubkey_str ) sh.update( str(message_timestamp) ) sh.update( message_id ) tail = sh.hexdigest() return storage.path_join( folder_dir( folder ), message_handle( message_timestamp, message_id ) + "-" + tail ) #------------------------- def incoming_message_path( message_timestamp, message_id ): # message path for remotely-hosted messages that we know about from our server global INCOMING_DIR return storage.volume_path( INCOMING_DIR, message_handle(message_timestamp, message_id)) #------------------------- def timestamp_from_message_path( message_path ): mp = os.path.basename( message_path ) mp_parts = mp.split("-") if len(mp_parts) != 2: return -1 try: ts = int(mp_parts[0]) except: return -1 return ts #------------------------- def id_from_message_path( message_path ): mp = os.path.basename( message_path ) mp_parts = mp.split("-") if len(mp_parts) != 2: return None return mp_parts[1] #------------------------- def attachment_storage_name( message_timestamp, message_id, attachment ): m = hashlib.sha256() m.update( storage.PATH_SALT ) # defend against attacker knowing the hash of the content m.update( str(attachment) ) attachment_hash = m.hexdigest() full_name = "%s-%s-%s" % (str(message_timestamp), str(message_id), str(attachment_hash)) full_name_safe = storage.salt_string( full_name ) return full_name_safe #------------------------- def attachment_path( message_timestamp, message_id, attachment ): name = attachment_storage_name( message_timestamp, message_id, attachment ) return storage.volume_path( ATTACHMENTS_DIR, name ) #------------------------- def folder_cache_name( folder_name ): return ".cache.%s" % folder_name #------------------------- def create_folder( folder_name ): return storage.setup_dirs( [folder_dir_atroot( folder_name )] ) #------------------------- def delete_folder( folder_name ): global DEFAULT_FOLDERS if folder_name not in DEFAULT_FOLDERS: return storage.delete_dirs( [folder_dir_atroot( folder_name )] ) else: # can't delete built-in folder return False def serialize_ent( ent ): ret = "" if isinstance( ent, list ) or isinstance( ent, tuple ): ret = serialize_list( ent) elif isinstance( ent, dict ): ret = serialize_dict( ent ) else: ret = base64.b64encode( str(ent) ) return ret def serialize_list( ent ): ret = "" for e in ent: ret += serialize_ent( e ) return ret def serialize_dict( ent ): ret = "" for (k, v) in ent.items(): ret += serialize_ent( k ) ret += serialize_ent( v ) return ret #------------------------- def sign_message( privkey_str, msg_cls, message_attrs ): privkey = CryptoKey.importKey( privkey_str ) h = HashAlg.new() all_but_signature = list( set(msg_cls._fields) - set(["signature"]) ) all_but_signature.sort() for attr in all_but_signature: h.update( serialize_ent(message_attrs[attr]) ) signer = CryptoSigner.new(privkey) signature = signer.sign( h ) return base64.b64encode( signature ) #------------------------- def verify_message( pubkey_str, message_cls, message ): signature = base64.b64decode( message.signature ) pubkey = CryptoKey.importKey( pubkey_str ) h = HashAlg.new() all_but_signature = list( set(message_cls._fields) - set(["signature"]) ) all_but_signature.sort() for attr in all_but_signature: h.update( serialize_ent(getattr(message, attr)) ) verifier = CryptoSigner.new(pubkey) ret = verifier.verify( h, signature ) return ret #------------------------- def prepare_message_attachment_metadata( privkey_str, _attachments, msg_ts, msg_id ): attachment_paths = {} attachment_signatures = {} if _attachments is None: return attachment_paths, attachment_signatures for attachment_name, attachment_data in _attachments.items(): apath = attachment_path( msg_ts, msg_id, attachment_name ) attachment_paths[ attachment_name ] = apath for attachment_name, attachment_data in _attachments.items(): attachment_sig = base64.b64encode( keys.sign_data( privkey_str, attachment_data ) ) attachment_signatures[ attachment_name ] = attachment_sig return attachment_paths, attachment_signatures #------------------------- def store_message( receiver_pubkey_str, sender_privkey_str, folder, message, attachment_paths, attachment_data ): try: message_json = storage.tuple_to_json( message ) except Exception, e: log.error("Failed to serialize message") log.exception(e) return False # what files have been stored? stored = [] # store message mpath = stored_message_path( receiver_pubkey_str, folder, message.timestamp, message.id ) rc = storage.write_encrypted_file( receiver_pubkey_str, mpath, message_json, sender_privkey_pem=sender_privkey_str ) if not rc: log.error("Failed to store message") return False stored.append( mpath ) failed = False """ # FIXME: broken--send one attachment per sender, or one per receiver. for attachment_name in message.attachment_names: attachment_path = attachment_paths[attachment_name] attachment_data = attachment_data[attachment_name] rc = storage.write_encrypted_file( receiver_pubkey_str, attachment_path, attachment_data ) if not rc: failed = True break stored.append( attachment_path ) """ if failed: # roll back for path in stored: storage.delete_file( path ) return False else: storage.purge_cache( folder_cache_name( folder ) ) return True #------------------------- def read_stored_message( privkey_str, folder, msg_timestamp, msg_id, volume=None, receiver_pubkey_pem=None ): if receiver_pubkey_pem is None: pkey = CryptoKey.importKey( privkey_str ) receiver_pubkey_pem = pkey.publickey().exportKey() mpath = stored_message_path( receiver_pubkey_pem, folder, msg_timestamp, msg_id ) if not storage.path_exists( mpath, volume=volume ): log.error("No message at %s" % mpath ) return None msg_json = storage.read_encrypted_file( privkey_str, mpath, volume=volume ) if msg_json is None: log.error("Failed to read message") return None try: msg = storage.json_to_tuple( SyndicateMessage, msg_json ) except Exception, e: log.error("Failed to parse message") log.exception(e) return None return msg #------------------------- def delete_message( pubkey_str, folder, msg_timestamp, msg_id ): rc = storage.delete_file( stored_message_path( pubkey_str, folder, msg_timestamp, msg_id ) ) storage.purge_cache( folder_cache_name( folder ) ) return rc #------------------------- def make_outbound_message( pubkey_str, privkey_str, contact_rec, message ): # generate an incoming message to be sent to this contact's email server incoming_message = SyndicateIncomingMessage( id=message.id, sender_addr=message.sender_addr, receiver_addrs=message.receiver_addrs, cc_addrs=message.cc_addrs, subject=message.subject, timestamp=message.timestamp, handle=message.handle, attachment_names=message.attachment_names, message_signature=message.signature, verified=True ) # serialize outbound incoming message try: incoming_message_json = storage.tuple_to_json( incoming_message ) except Exception, e: log.exception(e) log.error("Failed to serialize outbound message to %s" % contact_rec.addr) return rc else: # encrypt outbound incoming message encrypted_incoming_message_json = storage.encrypt_data( privkey_str, contact_rec.pubkey_pem, incoming_message_json ) encrypted_incoming_message_attrs = { "incoming_message_ciphertext": encrypted_incoming_message_json, "sender_addr": message.sender_addr, "receiver_addr": contact_rec.addr, "signature": "" } # sign with our public key encrypted_incoming_message_sig = sign_message( privkey_str, EncryptedIncomingMessage, encrypted_incoming_message_attrs ) encrypted_incoming_message_attrs['signature'] = encrypted_incoming_message_sig # send it off encrypted_incoming_message = EncryptedIncomingMessage( **encrypted_incoming_message_attrs ) return encrypted_incoming_message #------------------------- def send_message( pubkey_str, privkey_str, sender_addr, receiver_addrs, cc_addrs, bcc_addrs, subject, body, attachments={}, folder=unicode(SENT_FOLDER), fake_time=None, fake_id=None, use_http=False ): now = int(time.time()) msg_id = uuid.uuid4().get_hex() if fake_time is not None: now = fake_time if fake_id is not None: msg_id = fake_id handle = message_handle( now, msg_id ) # sanity check... if receiver_addrs == None: receiver_addrs = [] if cc_addrs == None: cc_addrs = [] if bcc_addrs == None: bcc_addrs = [] subject = unicode(subject) body = unicode(body) folder = unicode(folder) assert isinstance( receiver_addrs, list ), "Invalid argument for receiver_addrs" assert isinstance( cc_addrs, list ), "Invalid argument for cc_addrs" assert isinstance( bcc_addrs, list ), "Invalid argument for bcc_addrs" assert isinstance( folder, unicode ), "Invalid argument for folder" for addr in [sender_addr] + receiver_addrs + cc_addrs + bcc_addrs: assert isinstance(addr, str) or isinstance(addr, unicode), "Invalid address '%s'" % addr # parse addresses sender_addr_parsed = contact.parse_addr( sender_addr ) parsed_addrs = {} contacts = [] new_contacts = [] missing = [] send_via_gateway = [] for (addr_bundle_name, addrs) in [("receipient address", receiver_addrs), ("CC address", cc_addrs), ("BCC address", bcc_addrs)]: if not parsed_addrs.has_key(addr_bundle_name): parsed_addrs[addr_bundle_name] = [] for addr in addrs: try: parsed_addr = contact.parse_addr( addr ) parsed_addrs[ addr_bundle_name ].append( parsed_addr ) except Exception, e: # not a SyndicateMail address. Is it an email address? if not contact.is_valid_email( addr ): # not a valid email address raise Exception("Invalid %s '%s'" % (addr_bundle_name, addr)) else: # send via gateway, since this isn't a syndicate address send_via_gateway.append( addr ) log.info("Send to %s via normal email" % addr) # if we got this far, they're all parsed # calculate attachment paths and signatures # FIXME: this is currently broken attachment_paths, attachment_signatures = prepare_message_attachment_metadata( privkey_str, attachments, now, msg_id ) # construct the message and sign it _message = SyndicateMessage( id=msg_id, sender_addr=sender_addr, receiver_addrs=receiver_addrs, cc_addrs=cc_addrs, subject=subject, body=body, timestamp=now, handle=handle, attachment_names=attachments.keys(), attachment_signatures=attachment_signatures, signature="" ) # generate the message with the attachment info msg_attrs = dict( [(field, getattr(_message, field)) for field in _message._fields] ) signature = sign_message( privkey_str, SyndicateMessage, msg_attrs ) msg_attrs['signature'] = signature message = SyndicateMessage( **msg_attrs ) # get contact public keys from Volume all_parsed_addrs = reduce( lambda x, y: x + y, parsed_addrs.values(), [] ) for addr in all_parsed_addrs: if contact.contact_exists( pubkey_str, addr.addr ): # get the contact public key contact_rec = contact.read_contact( pubkey_str, privkey_str, addr.addr ) if contact_rec is None: missing.append( addr ) else: # send to this contact contacts.append( contact_rec ) else: missing.append( addr ) log.debug("No public key for %s" % addr.addr) # get remaining contact public keys from the user's MS and store them for missing_addr in missing: # new contact... pubkey_pem = network.download_user_pubkey( missing_addr.addr ) if pubkey_pem is None: # not on Syndicate send_via_gateway.append( missing_addr ) log.debug("Send to %s via normal email" % missing_addr.addr ) else: missing_contact = contact.SyndicateContact( addr=missing_addr.addr, pubkey_pem=pubkey_pem, extras={} ) new_contacts.append( missing_contact ) log.debug("Saved new contact: %s" % missing_addr.addr ) failed = [] # tell recipients that they have mail for contact_rec in contacts + new_contacts: encrypted_outbound_message = make_outbound_message( pubkey_str, privkey_str, contact_rec, message ) if encrypted_outbound_message == False: log.error("Failed to create outbound message to %s" % contact_rec.addr ) failed.append( contact_rec.addr ) continue rc = network.post_message( privkey_str, encrypted_outbound_message, use_http=use_http ) if not rc: log.error("Failed to send message to %s" % contact_rec.addr ) failed.append( contact_rec.addr ) continue # store a copy for each recipient. for contact_rec in contacts + new_contacts: # now store the message for each one # NOTE: it's better to fail after sending a notification to the receiver's server, so # the receiver can at least know they were meant to have been contacted log.info("Send message to %s" % str(contact_rec.addr)) rc = store_message( contact_rec.pubkey_pem, privkey_str, SENT_FOLDER, message, attachment_paths, attachments ) if not rc: log.debug("Failed to send message to %s" % contact_rec.addr ) failed.append( contact_rec.addr ) log.info("Store message for ourselves") # also, one for ourselves rc = store_message( pubkey_str, privkey_str, SENT_FOLDER, message, attachment_paths, attachments ) if not rc: log.debug("Failed to store a sent copy for myself" ) # send the message to the all the non-Syndicate recipients for addr in send_via_gateway: rc = network.send_legacy_email( addr, message, attachments ) if not rc: failed.append( addr ) log.debug("Failed to send message to %s via legacy email" % addr ) if len(failed) > 0: # return failed list return False, failed return True, [] #------------------------- def validate_and_parse_incoming_message( pubkey_str, privkey_str, my_addr, encrypted_incoming_message ): if encrypted_incoming_message.receiver_addr != my_addr: log.error("Message is not for me") return False sender_addr = encrypted_incoming_message.sender_addr verified = False # do we have a contact? contact_rec = contact.read_contact( pubkey_str, privkey_str, sender_addr ) if contact_rec is None: # no contact log.warning("Message from %s could not be verified." % sender_addr ) raise Exception("FIXME: Get %s's public key here" % sender_addr ) verified = False else: # check signature verified = verify_message( contact_rec.pubkey_pem, EncryptedIncomingMessage, encrypted_incoming_message ) if not verified: raise Exception("Message is not authentically from %s" % contact_rec.addr) # attempt to decrypt incoming_message_json = storage.decrypt_data( contact_rec.pubkey_pem, privkey_str, encrypted_incoming_message.incoming_message_ciphertext ) if incoming_message_json is None: log.error("Failed to decrypt incoming message") return False # attempt to parse try: incoming_message = storage.json_to_tuple( SyndicateIncomingMessage, incoming_message_json ) except Exception, e: log.exception(e) log.error("Failed to unserialize message from %s" % sender_addr ) return False # verify addresses match if my_addr not in incoming_message.receiver_addrs and my_addr not in incoming_message.cc_addrs: log.error("Message from %s not addressed to me" % sender_addr) return False # set verified attrs = dict( [(attr, getattr(incoming_message, attr)) for attr in SyndicateIncomingMessage._fields] ) attrs['verified'] = verified return SyndicateIncomingMessage( **attrs ) #------------------------- def store_incoming_message( pubkey_str, message, volume=None ): try: message_json = storage.tuple_to_json( message ) except Exception, e: log.error("Failed to serialize incoming message") log.exception(e) return False # store incoming message mpath = incoming_message_path( message.timestamp, message.id ) rc = storage.write_encrypted_file( pubkey_str, mpath, message_json, volume=volume ) if not rc: log.error("Failed to store incoming message") return False return True #------------------------- def read_incoming_message( privkey_str, msg_timestamp, msg_id, volume=None ): mpath = incoming_message_path( msg_timestamp, msg_id ) msg_json = storage.read_encrypted_file( privkey_str, mpath, volume=volume ) if msg_json is None: log.error("Failed to read incoming message %s" % message_handle( msg_timestamp, msg_id )) return None try: msg = storage.json_to_tuple( SyndicateIncomingMessage, msg_json ) except Exception, e: log.error("Failed to parse incoming message") log.exception(e) return None return msg #------------------------- def read_message_from_volume( vol_inst, sender_pubkey_str, receiver_pubkey_str, receiver_privkey_str, incoming_message ): try: sender_addr_parsed = contact.parse_addr( incoming_message.sender_addr ) except Exception, e: log.exception(e) log.error("Could not parse email") return None log.info("Read message from %s" % (incoming_message.sender_addr)) try: msg_path = stored_message_path( receiver_pubkey_str, SENT_FOLDER, incoming_message.timestamp, incoming_message.id ) msg_json = storage.read_encrypted_file( receiver_privkey_str, msg_path, volume=vol_inst, sender_pubkey_pem=sender_pubkey_str ) except Exception, e: log.exception(e) log.error("Failed to read %s" % msg_path ) return None if msg_json is None: log.error("Failed to read message from Volume") return None # unserialize try: msg = storage.json_to_tuple( SyndicateMessage, msg_json ) except Exception, e: log.exception(e) log.error("Failed to parse %s" % msg_path ) return None return msg #------------------------- def sender_volume_from_incoming_message( incoming_message, gateway_privkey_pem, storage_root ): try: parsed_addr = contact.parse_addr( incoming_message.sender_addr ) except Exception, e: log.exception(e) log.error("Failed to parse %s" % incoming_message.sender_addr ) return None try: volume = Volume( volume_name=parsed_addr.volume, ms_url=parsed_addr.MS, my_key_pem=gateway_privkey_pem, storage_root=storage_root ) except Exception, e: log.exception(e) log.error("Failed to connect to %s's Volume" % incoming_message.sender_addr) return None return volume #------------------------- def read_message( receiver_vol_inst, pubkey_str, privkey_str, gateway_privkey_pem, folder, msg_timestamp, msg_id, sender_vol_inst=None, storage_root="/tmp/syndicate-unused" ): # is this an incoming message? mpath = incoming_message_path( msg_timestamp, msg_id ) if storage.path_exists( mpath, volume=receiver_vol_inst ): # get the incoming message record incoming_message = read_incoming_message( privkey_str, msg_timestamp, msg_id, volume=receiver_vol_inst ) if incoming_message is None: log.error("Failed to read incoming message %s" % message_handle( msg_timestamp, msg_id ) ) return None # open the volume, if need be if sender_vol_inst is None: sender_vol_inst = sender_volume_from_incoming_message( incoming_message, gateway_privkey_pem, storage_root ) if sender_vol_inst is None: log.error("Failed to open Volume") return None # get the sender's public key sender_contact = contact.read_contact( pubkey_str, privkey_str, incoming_message.sender_addr ) if sender_contact is None: log.error("No contact record for %s; cannot verify message authenticity" % incoming_message.sender_addr ) return None # get the corresponding message from the remote Volume msg = read_message_from_volume( sender_vol_inst, sender_contact.pubkey_pem, pubkey_str, privkey_str, incoming_message ) if msg is not None: # verify that it matches the incoming message if incoming_message.message_signature != msg.signature: log.error("Message signature mismatch") return None return msg else: log.error("Failed to read message from %s" % sender_contact.addr) return None else: # it's a stored message return read_stored_message( privkey_str, folder, msg_timestamp, msg_id, volume=receiver_vol_inst ) #------------------------- def list_messages( vol_inst, pubkey_str, privkey_str, folder_name, start_timestamp=None, end_timestamp=None, length=None ): global STORAGE_DIR, CHECK_INCOMING_FOLDERS cached_items = storage.get_cached_data( privkey_str, folder_cache_name( folder_name ) ) if cached_items == None: log.info("No cached data for %s" % folder_name) try: dir_ents = storage.listdir( folder_dir(folder_name) ) except Exception, oe: log.error("Failed to list folder %s" % folder_name) log.exception(oe) raise Exception("Internal error") # tag these dir entries as having come from the folder FROM_FOLDER = 1 FROM_INCOMING = 2 dir_ents = [(x, FROM_FOLDER) for x in dir_ents] if folder_name in CHECK_INCOMING_FOLDERS: # check incoming as well try: incoming_dir_ents = storage.listdir( incoming_dir(), volume=vol_inst ) except OSError, oe: log.error("Failed to list folder, errno = %s" % oe.errno) log.exception(oe) raise Exception("Internal error") # tag these dir entries as having come from incoming incoming_dir_ents = [(x, FROM_INCOMING) for x in incoming_dir_ents] dir_ents += incoming_dir_ents # will sort on dir_ents[i][0] dir_ents.sort() dir_ents.reverse() # get all messages between start and end timestamps if start_timestamp is None: start_timestamp = 0 if end_timestamp is None: end_timestamp = 0 start_idx = -1 end_idx = -1 if length is None: length = len(dir_ents) for i in xrange(0, len(dir_ents)): timestamp = timestamp_from_message_path( dir_ents[i][0] ) # too early? if timestamp < start_timestamp: continue # too late? if timestamp > end_timestamp and end_timestamp > 0: continue if start_idx == -1: start_idx = i end_idx = i + 1 if end_idx - start_idx > length: break wanted = dir_ents[start_idx: end_idx] ret = [] # generate a metadata record for each of these for (dir_ent, origin) in wanted: msg_data = None is_read = False if origin == FROM_FOLDER: msg_data = read_stored_message( privkey_str, folder_name, timestamp_from_message_path( dir_ent ), id_from_message_path( dir_ent ), volume=vol_inst ) is_read = True else: msg_data = read_incoming_message( privkey_str, timestamp_from_message_path( dir_ent ), id_from_message_path( dir_ent ), volume=vol_inst ) if msg_data == None: log.warning("Failed to read message") continue metadata = SyndicateMessageMetadata( id=msg_data.id, sender_addr=msg_data.sender_addr, receiver_addrs=msg_data.receiver_addrs, cc_addrs=msg_data.cc_addrs, subject=msg_data.subject, timestamp=msg_data.timestamp, handle=message_handle( msg_data.timestamp, msg_data.id ), has_attachments=(len(msg_data.attachment_names) > 0), is_read=is_read ) ret.append( metadata ) storage.cache_data( pubkey_str, folder_cache_name( folder_name ), ret ) return ret def stddev( data ): x_avg = 0.0 for x in data: x_avg += x x_avg /= len(data) val = 0.0 for x in data: val += (x - x_avg) * (x - x_avg) val /= len(data) val = math.sqrt( val ) return val if __name__ == "__main__": pubkey_str = """ -----BEGIN PUBLIC KEY----- MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxwhi2mh+f/Uxcx6RuO42 EuVpxDHuciTMguJygvAHEuGTM/0hEW04Im1LfXldfpKv772XrCq+M6oKfUiee3tl sVhTf+8SZfbTdR7Zz132kdP1grNafGrp57mkOwxjFRE3FA23T1bHXpIaEcdhBo0R rXyEnxpJmnLyNYHaLN8rTOig5WFbnmhIZD+xCNtG7hFy39hKt+vNTWK98kMCOMsY QPywYw8nJaax/kY5SEiUup32BeZWV9HRljjJYlB5kMdzeAXcjQKvn5y47qmluVmx L1LRX5T2v11KLSpArSDO4At5qPPnrXhbsH3C2Z5L4jqStdLYB5ZYZdaAsaRKcc8V WpsmzZaFExJ9Nj05sDS1YMFMvoINqaPEftS6Be+wgF8/klZoHFkuslUNLK9k2f65 A7d9Fn/B42n+dCDYx0SR6obABd89cR8/AASkZl3QKeCzW/wl9zrt5dL1iydOq2kw JtgiKSCt6m7Hwx2kwHBGI8zUfNMBlfIlFu5CP+4xLTOlRdnXqYPylT56JQcjA2CB hGBRJQFWVutrVtTXlbvT2OmUkRQT9+P5wr0c7fl+iOVXh2TwfaFeug9Fm8QWoGyP GuKX1KO5JLQjcNTnZ3h3y9LIWHsCTCf2ltycUBguq8Mwzb5df2EkOVgFeLTfWyR2 lPCia/UWfs9eeGgdGe+Wr4sCAwEAAQ== -----END PUBLIC KEY----- """.strip() privkey_str = """ -----BEGIN RSA PRIVATE KEY----- MIIJKQIBAAKCAgEAxwhi2mh+f/Uxcx6RuO42EuVpxDHuciTMguJygvAHEuGTM/0h EW04Im1LfXldfpKv772XrCq+M6oKfUiee3tlsVhTf+8SZfbTdR7Zz132kdP1grNa fGrp57mkOwxjFRE3FA23T1bHXpIaEcdhBo0RrXyEnxpJmnLyNYHaLN8rTOig5WFb nmhIZD+xCNtG7hFy39hKt+vNTWK98kMCOMsYQPywYw8nJaax/kY5SEiUup32BeZW V9HRljjJYlB5kMdzeAXcjQKvn5y47qmluVmxL1LRX5T2v11KLSpArSDO4At5qPPn rXhbsH3C2Z5L4jqStdLYB5ZYZdaAsaRKcc8VWpsmzZaFExJ9Nj05sDS1YMFMvoIN qaPEftS6Be+wgF8/klZoHFkuslUNLK9k2f65A7d9Fn/B42n+dCDYx0SR6obABd89 cR8/AASkZl3QKeCzW/wl9zrt5dL1iydOq2kwJtgiKSCt6m7Hwx2kwHBGI8zUfNMB lfIlFu5CP+4xLTOlRdnXqYPylT56JQcjA2CBhGBRJQFWVutrVtTXlbvT2OmUkRQT 9+P5wr0c7fl+iOVXh2TwfaFeug9Fm8QWoGyPGuKX1KO5JLQjcNTnZ3h3y9LIWHsC TCf2ltycUBguq8Mwzb5df2EkOVgFeLTfWyR2lPCia/UWfs9eeGgdGe+Wr4sCAwEA AQKCAgEAl1fvIzkWB+LAaVMzZ7XrdE7yL/fv4ufMgzIB9ULjfh39Oykd/gxZBQSq xIyG5XpRQjGepZIS82I3e7C+ohLg7wvE4qE+Ej6v6H0/DonatmTAaVRMWBNMLaJi GWx/40Ml6J/NZg0MqQLbw+0iAENAz/TBO+JXWZRSTRGif0Brwp2ZyxJPApM1iNVN nvhuZRTrjv7/Qf+SK2gMG62MgPceSDxdO9YH5H9vFXT8ldRrE8SNkUrnGPw5LMud hp6+8bJYQUnjvW3vcaVQklp55AkpzFxjTRUO09DyWImqiHtME91l820UHDpLLldS 1PujpDD54jyjfJF8QmPrlCjjWssm5ll8AYpZFn1mp3SDY6CQhKGdLXjmPlBvEaoR 7yfNa7JRuJAM8ntrfxj3fk0B8t2e5NMylZsBICtposCkVTXpBVJt50gs7hHjiR3/ Q/P7t19ywEMlHx5edy+E394q8UL94YRf7gYEF4VFCxT1k3BhYGw8m3Ov22HS7EZy 2vFqro+RMOR7VkQZXvGecsaZ/5xhL8YIOS+9S90P0tmMVYmuMgp7L+Lm6DZi0Od6 cwKxB7LYabzrpfHXSIfqE5JUgpkV5iTVo4kbmHsrBQB1ysNFR74E1PJFy5JuFfHZ Tpw0KDBCIXVRFFanQ19pCcbP85MucKWif/DhjOr6nE/js/8O6XECggEBAN0lhYmq cPH9TucoGnpoRv2o+GkA0aA4HMIXQq4u89LNxOH+zBiom47AAj2onWl+Zo3Dliyy jBSzKkKSVvBwsuxgz9xq7VNBDiaK+wj1rS6MPqa/0Iyz5Fhi0STp2Fm/elDonYJ8 Jp8MRIWDk0luMgaAh7DuKpIm9dsg45wQmm/4LAGJw6WbbbZ4TUGrT684qIRXk8Q5 1Z08hgSOKUIyDwmv4LqenV6n4XemTq3zs8R0abQiJm81YqSOXwsJppXXgZoUM8sg L/gxX5pXxCzAfC2QpLI94VJcVtRUNGBK5rMmrANd2uITg6h/wDCy9FxRKWG8f+p4 qAcxr/oXXXebI98CggEBAOZmppx+PoRWaZM547VebUrEDKuZ/lp10hXnr3gkDAKz 2av8jy3YdtCKq547LygpBbjd1i/zFNDZ/r4XT+w/PfnNRMuJR5td29T+lWMi3Hm3 ant/o8qAyVISgkRW1YQjTAhPwYbHc2Y24n/roCutrtIBG9WMLQNEbJUXjU5uNF/0 +ezKKNFIruCX/JafupBfXl1zAEVuT0IkqlHbmSL4oxYafhPorLzjIPLiJgjAB6Wb iIOVIUJt61O6vkmeBWOP+bj5x1be6h35MlhKT+p4rMimaUALvbGlGQBX+Bm54/cN Ih0Kqx/gsDoD5rribQhuY0RANo1wfXdkW/ajHZihCdUCggEABO01EGAPrBRskZG/ JUL1cek1v4EZKmyVl21VOvQo0mVrIW2/tjzrWj7EzgLXnuYF+tqEmfJQVJW5N0pz TV/1XHa7qrlnGBe27Pzjost2VDcjnitfxgKr75wj9KKRA07UtsC34ZRKd/iZ/i90 NIqT6rkqTLLBmAfuKjeNWoi0KBJrSI19Ik9YHlyHvBLI76pfdrNMw25WZ+5VPfy8 xpC+7QRSCVZHQziSOUwnLJDlTFcbk7u/B3M1A114mJJad7QZWwlgLgJFj03qR1H1 ONoA6jLyuFXQkzkjZg+KKysAALW310tb+PVeVX6jFXKnJvdX6Kl+YAbYF3Dv7q5e kq+OGQKCAQEAngEnoYqyNO9N17mLf4YSTYPFbKle1YqXWI5at3mBAxlz3Y6GYlpg oQN4TjsoS9JWKkF38coyLEhTeulh1hJI3lb3Jt4uTU5AxAETUblGmfI/BBK0sNtB NRecXmFubAAI1GpdvaBqc16QVkmwvkON8FbyT7Ch7euuy1Arh+3r3SKTgt/gviWq SDvy7Rj9SKUegdesB/FuSV37r8d5bZI1xaLFc8HNNHxOzEJq8vU+SUQwioxrErNu /yzB8pp795t1FnW1Ts3woD2VWRcdVx8K30/APjvPC1S9oI6zhnEE9Rf8nQ4D7QiZ 0i96vA8r1uxdByFCSB0s7gPVTX7vfQxzQQKCAQAnNWvIwXR1W40wS5kgKwNd9zyO +G9mWRvQgM3PptUXM6XV1kSPd+VofGvQ3ApYJ3I7f7VPPNTPVLI57vUkhOrKbBvh Td3OGzhV48behsSmOEsXkNcOiogtqQsACZzgzI+46akS87m+OHhP8H3KcdsvGUNM xwHi4nnnVSMQ+SWtSuCHgA+1gX5YlNKDjq3RLCRG//9XHIApfc9c52TJKZukLpfx chit4EZW1ws/JPkQ+Yer91mCQaSkPnIBn2crzce4yqm2dOeHlhsfo25Wr37uJtWY X8H/SaEdrJv+LaA61Fy4rJS/56Qg+LSy05lISwIHBu9SmhTuY1lBrr9jMa3Q -----END RSA PRIVATE KEY----- """.strip() import session fake_module = collections.namedtuple( "FakeModule", ["VOLUME_STORAGE_DIRS", "LOCAL_STORAGE_DIRS"] ) fake_vol = session.do_test_volume( "/tmp/storage-test/volume" ) fake_vol2 = session.do_test_volume( "/tmp/storage-test/volume2" ) fake_mod = fake_module( LOCAL_STORAGE_DIRS=LOCAL_STORAGE_DIRS + contact.LOCAL_STORAGE_DIRS, VOLUME_STORAGE_DIRS=VOLUME_STORAGE_DIRS + contact.VOLUME_STORAGE_DIRS ) singleton.set_volume( fake_vol ) assert storage.setup_storage( privkey_str, "/apps/syndicatemail/data", "/tmp/storage-test/local", [fake_mod] ), "setup_storage failed" pubkey_str2 = """-----BEGIN PUBLIC KEY----- MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA3wIape2VASiHYTgirZRz nzWd/QSK8HuRw3kqEKUGjLiRCb072usuwQ+ozez+6yj0gA/3otKEjm1KM2K+qnk2 JZW12YEodF02KoHVtwf3x7GPO5drnO4TPlEFCXBJjPqjI6/YVhfZu3QNdPnulJOW yKKP+0ij0sxJ4vuglq2FbuEfneptMEWdFQjFAa10Tc1F5LBNAUK+lxVszEBnpwRQ lcM11ro8RSuZrlulGK6tEaJsncUBvhqESRMTJ9sbngksxlmYbfhBTkRt2Lnu+F4X gp9nQ9qp3IU+/065Z4pACnDpmbZReypnHWsirptlxAqW5Va87QfGNMgtduBkuR0f 5wYlAI61dJzg6clXjXlyDbATXdweilr52J3Q9F2MHVTpUDBpXhWoko1kaqoMPgLq RvAenNeQWNEzlHgqOFAAL7ibq0bbkLlYQwP+v9udEaRkRJyxPbbafRzNJPPE8lUs pbK7f3xY7NHfp4pK+RsZ092S+gSUp8kN+SyOSnq7j0vnNQsW17DXqbH1Vy9rWhAJ 3km0KP/QAjOTROCadZdY1JoZ9dQU1MOBxTSTF72jsSe45kJwfNMkmIeYf+bdbvq1 uW1shmufG1hu3OcP891hvXDE0Qg3+Uev5JgdOSd+akPcXUPFE+OEJ8NTnACc4nfK e/VhFoqm9R1zxkmHfaxzLKsCAwEAAQ== -----END PUBLIC KEY----- """.strip() privkey_str2 = """ -----BEGIN RSA PRIVATE KEY----- MIIJKgIBAAKCAgEA3wIape2VASiHYTgirZRznzWd/QSK8HuRw3kqEKUGjLiRCb07 2usuwQ+ozez+6yj0gA/3otKEjm1KM2K+qnk2JZW12YEodF02KoHVtwf3x7GPO5dr nO4TPlEFCXBJjPqjI6/YVhfZu3QNdPnulJOWyKKP+0ij0sxJ4vuglq2FbuEfnept MEWdFQjFAa10Tc1F5LBNAUK+lxVszEBnpwRQlcM11ro8RSuZrlulGK6tEaJsncUB vhqESRMTJ9sbngksxlmYbfhBTkRt2Lnu+F4Xgp9nQ9qp3IU+/065Z4pACnDpmbZR eypnHWsirptlxAqW5Va87QfGNMgtduBkuR0f5wYlAI61dJzg6clXjXlyDbATXdwe ilr52J3Q9F2MHVTpUDBpXhWoko1kaqoMPgLqRvAenNeQWNEzlHgqOFAAL7ibq0bb kLlYQwP+v9udEaRkRJyxPbbafRzNJPPE8lUspbK7f3xY7NHfp4pK+RsZ092S+gSU p8kN+SyOSnq7j0vnNQsW17DXqbH1Vy9rWhAJ3km0KP/QAjOTROCadZdY1JoZ9dQU 1MOBxTSTF72jsSe45kJwfNMkmIeYf+bdbvq1uW1shmufG1hu3OcP891hvXDE0Qg3 +Uev5JgdOSd+akPcXUPFE+OEJ8NTnACc4nfKe/VhFoqm9R1zxkmHfaxzLKsCAwEA AQKCAgEAw9jiNERw7mJ8einFcrGD1RdOV00tA8NRoNyAz7tOBDl2zpnMvhZ6qfwp oCd5PGZsSyc6sFi3Jynd10Dp92aZ4eoXmRuvvnm5vxzk5mft+Ab8pjX1wQzoA3s9 tCtTvKbErOuaTwmFIvXpd4ijOQJgknUJg4IotVDJtriLMKjVHSpCDPo6yADq0fUw pqeBE26p6gvWpLvMC306XipVnTzR1KRqXNiTY5/FyHUdiY6l2W3Oe8PvItfAwzgo Q4FOQL0IAG3gyvsRxz2bRpELyD1B4mpBUzruoAa465hkhQTJ9yFwVZji+AqmIhTb kYJRnhg6qtBA/N0t+V6vZs3sRxHH2AUlrNpnqaG3nKsIHborUfck+jXl8Lbc8d51 PGOAg7fPVe4yo09UekQ2qWmGXKYBlclmRhfOQc6N21cN1OCviJciYnE4eUiS0OR8 ZeIm6nAMZ1yPoSkEilLY9kjZoknX7ZHSWkgVB7cKtFu74ExHbrVAEqEQOVHH7kih KHtqgRJpazUb3WEe71La1Zc/mbiHkHYs4uDAH3l9JIGy5vrq1hSWmRaIqWbka1Eo uTGMgnMocnrS/KJU2FfqOY78rxgXjjh7J0UbQej+uL0+UPQb4wp23SVXcQ02HnTM 9UuF7ru14dyguCgW1rfUqvRrKujSYpPeNTlBVRbIMIYY53/oWakCggEBAOkwXl1S WnqQ+XPOhXpgQuv0F3l1yfxj+rGWSdZpL4g+TA5uaXDQW/AwyrERqHSBu5MCcBbt 7dFsIZyxnz41lAYsKB0Vs9jGoPFFyDtPMdKD6CFkaPYa2s/HhPE4DcU0DvVO1GOv ma1awXCMQFYiT+BpnDERVEd0TEvpx79trnj1rsi7KiJSjZ7LLwSXBrmsNGWsu8WC 5ZVG5ov2EuaGsnD6erKSjzz0oHypF1Gmy6FGqWcVFTImOxEnghquoFLeMKHkFr6S MzkefradUzFmPk8nz18wKgR2FQCUITvu9QuPtbs1cq3Nashes1shTsEa9Awz9E/2 afJJJfr5aL419G8CggEBAPTSyO8WrYJ77VDJLiGttXVgX4RFfSvSpPqNDjzw7coF cqysO+5Ni/rbfJD5YeszKCzYbSYrhJWb13uk8/AtOw3ZbrsvRZS+qEWuWTTms8JH PECOdhtyioeKvwj4FSY6zZxPYNqrXOIeZQ46ceeKrxc1pvZ3JEKrhkamNG/T2O3n kTdvB1es+7i83ppQzh393mv8rQIQ8HhUAEn6iMQE1LGb2uqPdb9aIRqoXvu+9rjp rMPrPDGLXroYnROequign5cpV0BU/5++qypD0Ry5etwXvn3H4L+46odliU3rsFWY WwAR0j+9TLvsagk3xqIpYmMXHJUxg5NUwo33kynVQYUCggEBAOUblrtN3IOryMtV T6OKzHWTXzUA27FUcczlgipdMkxEGOnc5U/oB0yYQ61xUfcWN7sanBKLNiuad/PC OFkgvwzJeagJ2KfVj+89xpsvFh5lZz7XrqCOhgm7WAzALBdjLIcsKlS/BNhj4Ma5 pcR69cvhN4qmIg4KX6P+TzjvhIpnqJCkA6OxRF+N9eYmlH78iIaVDe/iybq+7Gj7 HlrMYKnMD50/jegv2TZh0/1vSYZtLKeQ+UBKe6JBFP0uMWr5zwJgXVBjyFwIcCrv q/tPH00aKg61/bJgagYlg/mkr7HqQn1q5/+HYbD4CnQw53WnC7yplxKxYiqgX+aU AatQy5UCggEAB6h4RJJPBx/dQoOof8ExReSn2DlcOvyx0GyNH3bh2UnmVmRk04V1 dXlcIiTK3VKSVSTH9UOzOALR8LouLzsa98nvXseRw59bICLeA3ub793Okq5iH2Wr 06WRaDRqZPG98L/C5dQqaaBNxO4rFfUOmQlCmb8MUVGQN7GHPmBADuEJd9RvRFzS 2up9hBI3AFUqmfIjb0ccXocyIx5FHOyRwqR/aormQgANvQm7PuCwUwRsNQysq1gS tHuEnlJ+QhyUIWRXqFmATXznWcEZT2612yCbAtA3xYeBPo78hoVy1JqZbh0gmIHR Xqd8gaFPA0+MFlFowXn1BazHES3HWq2jCQKCAQEArJc/J/F1KxpdTa4gdkEMGFtb mnZFKfRm/HEggWK0M1oBn1i+ILfrFSstKwte41jS61n3kxBMewCNBXmxzU/zdz2e EoVDB8tNpaSP/48TZCNNnp6sS82NdhVJC4d2rCDaKHT4vW17DIKEImhDRZ5SJ50J iGs/7A4Ti6bnl2qrvyYf1vKG/l6mze3UIyx1WAxKGRJ/lgVCquSGHiwa5Kmq4KTN 5YT22tp/ICBOVWbeMLc8hceKJQHnP5m1SwjgKdFwFM46TWfJIZWs7bTFbw6E0sPL zTnZ0cqW+ZP7aVhUx6fjxAriawcLvV4utLZmMDLDxjS12T98PbxfIsKa8UJ82w== -----END RSA PRIVATE KEY----- """.strip() print "---- create/delete folders ----" for folder in DEFAULT_FOLDERS: create_folder( folder ) assert create_folder( "sniff" ), "create_folder failed" assert delete_folder( "sniff" ), "delete_folder failed" print "---- store/load incoming message ----" msg_id1 = "a6322463ec5e4e4cb65ad88746aa832e" msg_ts1 = 1388897380 incoming_message = SyndicateIncomingMessage( msg_id1, "[email protected]", ["[email protected]"], [], "Hello world!", msg_ts1, message_handle( msg_ts1, msg_id1 ), [], True, "" ) assert store_incoming_message( pubkey_str, incoming_message, volume=fake_vol ), "store_incoming_message failed" incoming_message2 = read_incoming_message( privkey_str, msg_ts1, msg_id1, volume=fake_vol ) assert incoming_message2 == incoming_message, "Messages are unequal" # store some more, for the listing for i in xrange(0,10): msg_id = uuid.uuid4().get_hex() msg_ts = msg_ts1 + 3600 * i + 1 sm = SyndicateIncomingMessage( msg_id, "someone_%s.mail.syndicate.com@example%s.com" % (i, i), ["[email protected]"], ["[email protected]"], "Hello world %s" % i, msg_ts, message_handle( msg_ts, msg_id ), [], True, "" ) assert store_incoming_message( pubkey_str, sm, volume=fake_vol ), "store_incoming_message failed" """ print "---- store/load local message ----" msg_id2 = "8011d599ed984edb9115dd71b68402be" msg_ts2 = 1388897434 stored_message = SyndicateMessage( msg_id2, "[email protected]", ["[email protected]"], [], "Hello again!", "This is a message body", msg_ts2, message_handle( msg_ts2, msg_id2 ), [], [], "" ) assert store_message( pubkey_str, DRAFTS_FOLDER, stored_message, {"attachment1": "foocorp"} ), "store_message failed" stored_message2 = read_stored_message( privkey_str, DRAFTS_FOLDER, msg_ts2, msg_id2 ) for attr in ['id', 'sender_addr', 'receiver_addrs', 'cc_addrs', 'subject', 'body', 'timestamp', 'handle']: if getattr(stored_message, attr) != getattr(stored_message2, attr): raise Exception("Messages are unequal on %s: got %s, expected %s" % (attr, getattr(stored_message2, attr), getattr(stored_message, attr)) ) assert stored_message2.attachment_names == ['attachment1'], "Invalid attachments: %s" % stored_message2.attachment_names # store some more, for the listing for i in xrange(0,10): msg_id = uuid.uuid4().get_hex() msg_ts = msg_ts2 + 3600 * i + 1 sm = SyndicateMessage( msg_id, "someone_%s.mail.syndicate.com@example%s.com" % (i, i), ["[email protected]"], ["[email protected]"], "Hello world %s" % i, "This is message %s" % i, msg_ts, message_handle( msg_ts, msg_id ), [], [], "" ) assert store_message( pubkey_str, SENT_FOLDER, sm, {} ), "store_message failed" """ pp = pprint.PrettyPrinter() print "---- list messages ----" print "Drafts:" drafts_metadata = list_messages( fake_vol, pubkey_str, privkey_str, DRAFTS_FOLDER ) pp.pprint( drafts_metadata ) print "Sent:" sent_metadata = list_messages( fake_vol, pubkey_str, privkey_str, SENT_FOLDER ) pp.pprint( sent_metadata ) print "Inbox:" inbox_metadata = list_messages( fake_vol, pubkey_str, privkey_str, INBOX_FOLDER ) pp.pprint( inbox_metadata ) print "---- send message setup ----" #SyndicateContact = collections.namedtuple( "SyndicateMailContact", ["addr", "pubkey_pem", "extras"] ) alice = contact.SyndicateContact( addr="alice.mail.localhost:8080@localhost:33334", pubkey_pem = pubkey_str, extras = {"foo":"bar"} ) bob = contact.SyndicateContact( addr="bob.mail2.localhost:8080@localhost:33334", pubkey_pem = pubkey_str2, extras={"baz": "goo"} ) contact.write_contact( pubkey_str, alice ) contact.write_contact( pubkey_str, bob ) print "---- send message setup ----" def test_download_user_pubkey( addr ): return pubkey_str2 def test_post_message( privkey_pem, encrypted_incoming_message, use_http=False ): """ rc = network.post_message( privkey_pem, encrypted_incoming_message ) if not rc: return rc """ singleton.set_volume( fake_vol2 ) assert storage.setup_storage( privkey_str2, "/apps/syndicatemail/data", "/tmp/storage-test/local2", [fake_mod] ), "setup_storage 2 failed" contact.write_contact( pubkey_str2, alice ) contact.write_contact( pubkey_str2, bob ) incoming_message = validate_and_parse_incoming_message( pubkey_str2, privkey_str2, bob.addr, encrypted_incoming_message ) assert incoming_message is not False, "validate and parse incoming message failed" rc = store_incoming_message( bob.pubkey_pem, incoming_message, volume=fake_vol2 ) assert rc, "store_incoming_message failed" singleton.set_volume( fake_vol ) return True network.post_message = test_post_message network.download_user_pubkey = test_download_user_pubkey print "---- send message ----" # alice to bob msg_id3 = "4ae26634ccaf401fbd4114a252ffa2a5" msg_ts3 = 1389238627 subject = "a" * 128 body = "b" * 26000 num_tests = 10 times = [None] * num_tests for i in xrange(0,num_tests): start = time.time() rc, failed = send_message( pubkey_str, privkey_str, alice.addr, [bob.addr], [], [], subject, body, attachments={"poop": "poopie"}, fake_time=msg_ts3, fake_id=msg_id3, use_http=True ) end = time.time() assert rc, "send message failed for %s" % failed times[i] = end - start times.sort() avg = sum(times) / float(num_tests) median = times[num_tests/2] print "" print "send message avg: %s, median: %s, stddev: %s" % (avg, median, stddev(times)) print "" # bob from alice print "---- receive message setup ----" singleton.set_volume( fake_vol2 ) assert storage.setup_storage( privkey_str2, "/apps/syndicatemail/data", "/tmp/storage-test/local2", [fake_mod] ), "setup_storage 2 failed" print "---- receive message ----" times = [None] * num_tests for i in xrange(0,num_tests): start = time.time() rc = read_message( fake_vol2, pubkey_str2, privkey_str2, None, INBOX_FOLDER, msg_ts3, msg_id3, sender_vol_inst=fake_vol ) end = time.time() assert rc, "read message failed" times[i] = end - start times.sort() avg = sum(times) / float(num_tests) median = times[num_tests/2] print "" print "receive message avg: %s, median: %s, stddev: %s" % (avg, median, stddev(times)) print ""
apache-2.0
-7,225,676,625,747,135,000
36.644317
224
0.67786
false
sarvex/tensorflow
tensorflow/lite/experimental/microfrontend/python/ops/audio_microfrontend_op.py
23
5330
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """AudioMicrofrontend Op creates filterbanks from audio data.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.lite.experimental.microfrontend.ops import gen_audio_microfrontend_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import load_library from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.platform import resource_loader from tensorflow.python.util.tf_export import tf_export _audio_microfrontend_op = load_library.load_op_library( resource_loader.get_path_to_datafile("_audio_microfrontend_op.so")) @tf_export("lite.experimental.microfrontend.python.ops.audio_microfrontend") def audio_microfrontend(audio, sample_rate=16000, window_size=25, window_step=10, num_channels=32, upper_band_limit=7500.0, lower_band_limit=125.0, smoothing_bits=10, even_smoothing=0.025, odd_smoothing=0.06, min_signal_remaining=0.05, enable_pcan=True, pcan_strength=0.95, pcan_offset=80.0, gain_bits=21, enable_log=True, scale_shift=6, left_context=0, right_context=0, frame_stride=1, zero_padding=False, out_scale=1, out_type=dtypes.uint16): """Audio Microfrontend Op. This Op converts a sequence of audio data into one or more feature vectors containing filterbanks of the input. The conversion process uses a lightweight library to perform: 1. A slicing window function 2. Short-time FFTs 3. Filterbank calculations 4. Noise reduction 5. PCAN Auto Gain Control 6. Logarithmic scaling Args: audio: 1D Tensor, int16 audio data in temporal ordering. sample_rate: Integer, the sample rate of the audio in Hz. window_size: Integer, length of desired time frames in ms. window_step: Integer, length of step size for the next frame in ms. num_channels: Integer, the number of filterbank channels to use. upper_band_limit: Float, the highest frequency included in the filterbanks. lower_band_limit: Float, the lowest frequency included in the filterbanks. smoothing_bits: Int, scale up signal by 2^(smoothing_bits) before reduction. even_smoothing: Float, smoothing coefficient for even-numbered channels. odd_smoothing: Float, smoothing coefficient for odd-numbered channels. min_signal_remaining: Float, fraction of signal to preserve in smoothing. enable_pcan: Bool, enable PCAN auto gain control. pcan_strength: Float, gain normalization exponent. pcan_offset: Float, positive value added in the normalization denominator. gain_bits: Int, number of fractional bits in the gain. enable_log: Bool, enable logarithmic scaling of filterbanks. scale_shift: Integer, scale filterbanks by 2^(scale_shift). left_context: Integer, number of preceding frames to attach to each frame. right_context: Integer, number of preceding frames to attach to each frame. frame_stride: Integer, M frames to skip over, where output[n] = frame[n*M]. zero_padding: Bool, if left/right context is out-of-bounds, attach frame of zeroes. Otherwise, frame[0] or frame[size-1] will be copied. out_scale: Integer, divide all filterbanks by this number. out_type: DType, type of the output Tensor, defaults to UINT16. Returns: filterbanks: 2D Tensor, each row is a time frame, each column is a channel. Raises: ValueError: If the audio tensor is not explicitly a vector. """ audio_shape = audio.shape if audio_shape.ndims is None: raise ValueError("Input to `AudioMicrofrontend` should have known rank.") if len(audio_shape) > 1: audio = array_ops.reshape(audio, [-1]) return gen_audio_microfrontend_op.audio_microfrontend( audio, sample_rate, window_size, window_step, num_channels, upper_band_limit, lower_band_limit, smoothing_bits, even_smoothing, odd_smoothing, min_signal_remaining, enable_pcan, pcan_strength, pcan_offset, gain_bits, enable_log, scale_shift, left_context, right_context, frame_stride, zero_padding, out_scale, out_type) ops.NotDifferentiable("AudioMicrofrontend")
apache-2.0
7,204,958,978,835,760,000
44.948276
85
0.669606
false
pitunti/alfaPitunti
plugin.video.alfa/servers/vimeo.py
1
1163
# -*- coding: utf-8 -*- from core import httptools from core import scrapertools from platformcode import logger def get_video_url(page_url, premium=False, user="", password="", video_password=""): logger.info("(page_url='%s')" % page_url) video_urls = [] headers = [['User-Agent', 'Mozilla/5.0']] if "|" in page_url: page_url, referer = page_url.split("|", 1) headers.append(['Referer', referer]) if not page_url.endswith("/config"): page_url = scrapertools.find_single_match(page_url, ".*?video/[0-9]+") data = httptools.downloadpage(page_url, headers=headers).data patron = 'mime":"([^"]+)"' patron += '.*?url":"([^"]+)"' patron += '.*?quality":"([^"]+)"' match = scrapertools.find_multiple_matches(data, patron) for mime, media_url, calidad in match: title = "%s (%s) [vimeo]" % (mime.replace("video/", "."), calidad) video_urls.append([title, media_url, int(calidad.replace("p", ""))]) video_urls.sort(key=lambda x: x[2]) for video_url in video_urls: video_url[2] = 0 logger.info("%s - %s" % (video_url[0], video_url[1])) return video_urls
gpl-3.0
7,060,998,366,256,293,000
35.34375
84
0.587274
false
solashirai/edx-platform
common/djangoapps/student/models.py
3
78980
""" Models for User Information (students, staff, etc) Migration Notes If you make changes to this model, be sure to create an appropriate migration file and check it in at the same time as your model changes. To do that, 1. Go to the edx-platform dir 2. ./manage.py lms schemamigration student --auto description_of_your_change 3. Add the migration file created in edx-platform/common/djangoapps/student/migrations/ """ from collections import defaultdict, OrderedDict from datetime import datetime, timedelta from functools import total_ordering import hashlib from importlib import import_module import json import logging from pytz import UTC from urllib import urlencode import uuid import analytics from config_models.models import ConfigurationModel from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils import timezone from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password from django.contrib.auth.signals import user_logged_in, user_logged_out from django.db import models, IntegrityError, transaction from django.db.models import Count from django.db.models.signals import pre_save, post_save from django.dispatch import receiver, Signal from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext_noop from django.core.cache import cache from django_countries.fields import CountryField import dogstats_wrapper as dog_stats_api from eventtracking import tracker from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locations import SlashSeparatedCourseKey from simple_history.models import HistoricalRecords from track import contexts from xmodule_django.models import CourseKeyField, NoneToEmptyManager from certificates.models import GeneratedCertificate from course_modes.models import CourseMode from enrollment.api import _default_course_mode from microsite_configuration import microsite import lms.lib.comment_client as cc from openedx.core.djangoapps.commerce.utils import ecommerce_api_client, ECOMMERCE_DATE_FORMAT from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from util.model_utils import emit_field_changed_events, get_changed_fields_dict from util.query import use_read_replica_if_available from util.milestones_helpers import is_entrance_exams_enabled UNENROLL_DONE = Signal(providing_args=["course_enrollment", "skip_refund"]) log = logging.getLogger(__name__) AUDIT_LOG = logging.getLogger("audit") SessionStore = import_module(settings.SESSION_ENGINE).SessionStore # pylint: disable=invalid-name UNENROLLED_TO_ALLOWEDTOENROLL = 'from unenrolled to allowed to enroll' ALLOWEDTOENROLL_TO_ENROLLED = 'from allowed to enroll to enrolled' ENROLLED_TO_ENROLLED = 'from enrolled to enrolled' ENROLLED_TO_UNENROLLED = 'from enrolled to unenrolled' UNENROLLED_TO_ENROLLED = 'from unenrolled to enrolled' ALLOWEDTOENROLL_TO_UNENROLLED = 'from allowed to enroll to enrolled' UNENROLLED_TO_UNENROLLED = 'from unenrolled to unenrolled' DEFAULT_TRANSITION_STATE = 'N/A' TRANSITION_STATES = ( (UNENROLLED_TO_ALLOWEDTOENROLL, UNENROLLED_TO_ALLOWEDTOENROLL), (ALLOWEDTOENROLL_TO_ENROLLED, ALLOWEDTOENROLL_TO_ENROLLED), (ENROLLED_TO_ENROLLED, ENROLLED_TO_ENROLLED), (ENROLLED_TO_UNENROLLED, ENROLLED_TO_UNENROLLED), (UNENROLLED_TO_ENROLLED, UNENROLLED_TO_ENROLLED), (ALLOWEDTOENROLL_TO_UNENROLLED, ALLOWEDTOENROLL_TO_UNENROLLED), (UNENROLLED_TO_UNENROLLED, UNENROLLED_TO_UNENROLLED), (DEFAULT_TRANSITION_STATE, DEFAULT_TRANSITION_STATE) ) class AnonymousUserId(models.Model): """ This table contains user, course_Id and anonymous_user_id Purpose of this table is to provide user by anonymous_user_id. We generate anonymous_user_id using md5 algorithm, and use result in hex form, so its length is equal to 32 bytes. """ objects = NoneToEmptyManager() user = models.ForeignKey(User, db_index=True) anonymous_user_id = models.CharField(unique=True, max_length=32) course_id = CourseKeyField(db_index=True, max_length=255, blank=True) unique_together = (user, course_id) def anonymous_id_for_user(user, course_id, save=True): """ Return a unique id for a (user, course) pair, suitable for inserting into e.g. personalized survey links. If user is an `AnonymousUser`, returns `None` Keyword arguments: save -- Whether the id should be saved in an AnonymousUserId object. """ # This part is for ability to get xblock instance in xblock_noauth handlers, where user is unauthenticated. if user.is_anonymous(): return None cached_id = getattr(user, '_anonymous_id', {}).get(course_id) if cached_id is not None: return cached_id # include the secret key as a salt, and to make the ids unique across different LMS installs. hasher = hashlib.md5() hasher.update(settings.SECRET_KEY) hasher.update(unicode(user.id)) if course_id: hasher.update(course_id.to_deprecated_string().encode('utf-8')) digest = hasher.hexdigest() if not hasattr(user, '_anonymous_id'): user._anonymous_id = {} # pylint: disable=protected-access user._anonymous_id[course_id] = digest # pylint: disable=protected-access if save is False: return digest try: anonymous_user_id, __ = AnonymousUserId.objects.get_or_create( defaults={'anonymous_user_id': digest}, user=user, course_id=course_id ) if anonymous_user_id.anonymous_user_id != digest: log.error( u"Stored anonymous user id %r for user %r " u"in course %r doesn't match computed id %r", user, course_id, anonymous_user_id.anonymous_user_id, digest ) except IntegrityError: # Another thread has already created this entry, so # continue pass return digest def user_by_anonymous_id(uid): """ Return user by anonymous_user_id using AnonymousUserId lookup table. Do not raise `django.ObjectDoesNotExist` exception, if there is no user for anonymous_student_id, because this function will be used inside xmodule w/o django access. """ if uid is None: return None try: return User.objects.get(anonymoususerid__anonymous_user_id=uid) except ObjectDoesNotExist: return None class UserStanding(models.Model): """ This table contains a student's account's status. Currently, we're only disabling accounts; in the future we can imagine taking away more specific privileges, like forums access, or adding more specific karma levels or probationary stages. """ ACCOUNT_DISABLED = "disabled" ACCOUNT_ENABLED = "enabled" USER_STANDING_CHOICES = ( (ACCOUNT_DISABLED, u"Account Disabled"), (ACCOUNT_ENABLED, u"Account Enabled"), ) user = models.OneToOneField(User, db_index=True, related_name='standing') account_status = models.CharField( blank=True, max_length=31, choices=USER_STANDING_CHOICES ) changed_by = models.ForeignKey(User, blank=True) standing_last_changed_at = models.DateTimeField(auto_now=True) class UserProfile(models.Model): """This is where we store all the user demographic fields. We have a separate table for this rather than extending the built-in Django auth_user. Notes: * Some fields are legacy ones from the first run of 6.002, from which we imported many users. * Fields like name and address are intentionally open ended, to account for international variations. An unfortunate side-effect is that we cannot efficiently sort on last names for instance. Replication: * Only the Portal servers should ever modify this information. * All fields are replicated into relevant Course databases Some of the fields are legacy ones that were captured during the initial MITx fall prototype. """ # cache key format e.g user.<user_id>.profile.country = 'SG' PROFILE_COUNTRY_CACHE_KEY = u"user.{user_id}.profile.country" class Meta(object): db_table = "auth_userprofile" # CRITICAL TODO/SECURITY # Sanitize all fields. # This is not visible to other users, but could introduce holes later user = models.OneToOneField(User, unique=True, db_index=True, related_name='profile') name = models.CharField(blank=True, max_length=255, db_index=True) meta = models.TextField(blank=True) # JSON dictionary for future expansion courseware = models.CharField(blank=True, max_length=255, default='course.xml') # Location is no longer used, but is held here for backwards compatibility # for users imported from our first class. language = models.CharField(blank=True, max_length=255, db_index=True) location = models.CharField(blank=True, max_length=255, db_index=True) # Optional demographic data we started capturing from Fall 2012 this_year = datetime.now(UTC).year VALID_YEARS = range(this_year, this_year - 120, -1) year_of_birth = models.IntegerField(blank=True, null=True, db_index=True) GENDER_CHOICES = ( ('m', ugettext_noop('Male')), ('f', ugettext_noop('Female')), # Translators: 'Other' refers to the student's gender ('o', ugettext_noop('Other/Prefer Not to Say')) ) gender = models.CharField( blank=True, null=True, max_length=6, db_index=True, choices=GENDER_CHOICES ) # [03/21/2013] removed these, but leaving comment since there'll still be # p_se and p_oth in the existing data in db. # ('p_se', 'Doctorate in science or engineering'), # ('p_oth', 'Doctorate in another field'), LEVEL_OF_EDUCATION_CHOICES = ( ('p', ugettext_noop('Doctorate')), ('m', ugettext_noop("Master's or professional degree")), ('b', ugettext_noop("Bachelor's degree")), ('a', ugettext_noop("Associate degree")), ('hs', ugettext_noop("Secondary/high school")), ('jhs', ugettext_noop("Junior secondary/junior high/middle school")), ('el', ugettext_noop("Elementary/primary school")), # Translators: 'None' refers to the student's level of education ('none', ugettext_noop("No Formal Education")), # Translators: 'Other' refers to the student's level of education ('other', ugettext_noop("Other Education")) ) level_of_education = models.CharField( blank=True, null=True, max_length=6, db_index=True, choices=LEVEL_OF_EDUCATION_CHOICES ) mailing_address = models.TextField(blank=True, null=True) city = models.TextField(blank=True, null=True) country = CountryField(blank=True, null=True) goals = models.TextField(blank=True, null=True) allow_certificate = models.BooleanField(default=1) bio = models.CharField(blank=True, null=True, max_length=3000, db_index=False) profile_image_uploaded_at = models.DateTimeField(null=True) @property def has_profile_image(self): """ Convenience method that returns a boolean indicating whether or not this user has uploaded a profile image. """ return self.profile_image_uploaded_at is not None @property def age(self): """ Convenience method that returns the age given a year_of_birth. """ year_of_birth = self.year_of_birth year = datetime.now(UTC).year if year_of_birth is not None: return self._calculate_age(year, year_of_birth) @property def level_of_education_display(self): """ Convenience method that returns the human readable level of education. """ if self.level_of_education: return self.__enumerable_to_display(self.LEVEL_OF_EDUCATION_CHOICES, self.level_of_education) @property def gender_display(self): """ Convenience method that returns the human readable gender. """ if self.gender: return self.__enumerable_to_display(self.GENDER_CHOICES, self.gender) def get_meta(self): # pylint: disable=missing-docstring js_str = self.meta if not js_str: js_str = dict() else: js_str = json.loads(self.meta) return js_str def set_meta(self, meta_json): # pylint: disable=missing-docstring self.meta = json.dumps(meta_json) def set_login_session(self, session_id=None): """ Sets the current session id for the logged-in user. If session_id doesn't match the existing session, deletes the old session object. """ meta = self.get_meta() old_login = meta.get('session_id', None) if old_login: SessionStore(session_key=old_login).delete() meta['session_id'] = session_id self.set_meta(meta) self.save() def requires_parental_consent(self, date=None, age_limit=None, default_requires_consent=True): """Returns true if this user requires parental consent. Args: date (Date): The date for which consent needs to be tested (defaults to now). age_limit (int): The age limit at which parental consent is no longer required. This defaults to the value of the setting 'PARENTAL_CONTROL_AGE_LIMIT'. default_requires_consent (bool): True if users require parental consent if they have no specified year of birth (default is True). Returns: True if the user requires parental consent. """ if age_limit is None: age_limit = getattr(settings, 'PARENTAL_CONSENT_AGE_LIMIT', None) if age_limit is None: return False # Return True if either: # a) The user has a year of birth specified and that year is fewer years in the past than the limit. # b) The user has no year of birth specified and the default is to require consent. # # Note: we have to be conservative using the user's year of birth as their birth date could be # December 31st. This means that if the number of years since their birth year is exactly equal # to the age limit then we have to assume that they might still not be old enough. year_of_birth = self.year_of_birth if year_of_birth is None: return default_requires_consent if date is None: age = self.age else: age = self._calculate_age(date.year, year_of_birth) return age < age_limit def __enumerable_to_display(self, enumerables, enum_value): """ Get the human readable value from an enumerable list of key-value pairs. """ return dict(enumerables)[enum_value] def _calculate_age(self, year, year_of_birth): """Calculate the youngest age for a user with a given year of birth. :param year: year :param year_of_birth: year of birth :return: youngest age a user could be for the given year """ # There are legal implications regarding how we can contact users and what information we can make public # based on their age, so we must take the most conservative estimate. return year - year_of_birth - 1 @classmethod def country_cache_key_name(cls, user_id): """Return cache key name to be used to cache current country. Args: user_id(int): Id of user. Returns: Unicode cache key """ return cls.PROFILE_COUNTRY_CACHE_KEY.format(user_id=user_id) @receiver(models.signals.post_save, sender=UserProfile) def invalidate_user_profile_country_cache(sender, instance, **kwargs): # pylint: disable=unused-argument, invalid-name """Invalidate the cache of country in UserProfile model. """ changed_fields = getattr(instance, '_changed_fields', {}) if 'country' in changed_fields: cache_key = UserProfile.country_cache_key_name(instance.user_id) cache.delete(cache_key) log.info("Country changed in UserProfile for %s, cache deleted", instance.user_id) @receiver(pre_save, sender=UserProfile) def user_profile_pre_save_callback(sender, **kwargs): """ Ensure consistency of a user profile before saving it. """ user_profile = kwargs['instance'] # Remove profile images for users who require parental consent if user_profile.requires_parental_consent() and user_profile.has_profile_image: user_profile.profile_image_uploaded_at = None # Cache "old" field values on the model instance so that they can be # retrieved in the post_save callback when we emit an event with new and # old field values. user_profile._changed_fields = get_changed_fields_dict(user_profile, sender) @receiver(post_save, sender=UserProfile) def user_profile_post_save_callback(sender, **kwargs): """ Emit analytics events after saving the UserProfile. """ user_profile = kwargs['instance'] # pylint: disable=protected-access emit_field_changed_events( user_profile, user_profile.user, sender._meta.db_table, excluded_fields=['meta'] ) @receiver(pre_save, sender=User) def user_pre_save_callback(sender, **kwargs): """ Capture old fields on the user instance before save and cache them as a private field on the current model for use in the post_save callback. """ user = kwargs['instance'] user._changed_fields = get_changed_fields_dict(user, sender) @receiver(post_save, sender=User) def user_post_save_callback(sender, **kwargs): """ Emit analytics events after saving the User. """ user = kwargs['instance'] # pylint: disable=protected-access emit_field_changed_events( user, user, sender._meta.db_table, excluded_fields=['last_login', 'first_name', 'last_name'], hidden_fields=['password'] ) class UserSignupSource(models.Model): """ This table contains information about users registering via Micro-Sites """ user = models.ForeignKey(User, db_index=True) site = models.CharField(max_length=255, db_index=True) def unique_id_for_user(user, save=True): """ Return a unique id for a user, suitable for inserting into e.g. personalized survey links. Keyword arguments: save -- Whether the id should be saved in an AnonymousUserId object. """ # Setting course_id to '' makes it not affect the generated hash, # and thus produce the old per-student anonymous id return anonymous_id_for_user(user, None, save=save) # TODO: Should be renamed to generic UserGroup, and possibly # Given an optional field for type of group class UserTestGroup(models.Model): users = models.ManyToManyField(User, db_index=True) name = models.CharField(blank=False, max_length=32, db_index=True) description = models.TextField(blank=True) class Registration(models.Model): ''' Allows us to wait for e-mail before user is registered. A registration profile is created when the user creates an account, but that account is inactive. Once the user clicks on the activation key, it becomes active. ''' class Meta(object): db_table = "auth_registration" user = models.OneToOneField(User) activation_key = models.CharField(('activation key'), max_length=32, unique=True, db_index=True) def register(self, user): # MINOR TODO: Switch to crypto-secure key self.activation_key = uuid.uuid4().hex self.user = user self.save() def activate(self): self.user.is_active = True self._track_activation() self.user.save() def _track_activation(self): """ Update the isActive flag in mailchimp for activated users.""" has_segment_key = getattr(settings, 'LMS_SEGMENT_KEY', None) has_mailchimp_id = hasattr(settings, 'MAILCHIMP_NEW_USER_LIST_ID') if has_segment_key and has_mailchimp_id: identity_args = [ self.user.id, # pylint: disable=no-member { 'email': self.user.email, 'username': self.user.username, 'activated': 1, }, { "MailChimp": { "listId": settings.MAILCHIMP_NEW_USER_LIST_ID } } ] analytics.identify(*identity_args) class PendingNameChange(models.Model): user = models.OneToOneField(User, unique=True, db_index=True) new_name = models.CharField(blank=True, max_length=255) rationale = models.CharField(blank=True, max_length=1024) class PendingEmailChange(models.Model): user = models.OneToOneField(User, unique=True, db_index=True) new_email = models.CharField(blank=True, max_length=255, db_index=True) activation_key = models.CharField(('activation key'), max_length=32, unique=True, db_index=True) def request_change(self, email): """Request a change to a user's email. Implicitly saves the pending email change record. Arguments: email (unicode): The proposed new email for the user. Returns: unicode: The activation code to confirm the change. """ self.new_email = email self.activation_key = uuid.uuid4().hex self.save() return self.activation_key EVENT_NAME_ENROLLMENT_ACTIVATED = 'edx.course.enrollment.activated' EVENT_NAME_ENROLLMENT_DEACTIVATED = 'edx.course.enrollment.deactivated' EVENT_NAME_ENROLLMENT_MODE_CHANGED = 'edx.course.enrollment.mode_changed' class PasswordHistory(models.Model): """ This model will keep track of past passwords that a user has used as well as providing contraints (e.g. can't reuse passwords) """ user = models.ForeignKey(User) password = models.CharField(max_length=128) time_set = models.DateTimeField(default=timezone.now) def create(self, user): """ This will copy over the current password, if any of the configuration has been turned on """ if not (PasswordHistory.is_student_password_reuse_restricted() or PasswordHistory.is_staff_password_reuse_restricted() or PasswordHistory.is_password_reset_frequency_restricted() or PasswordHistory.is_staff_forced_password_reset_enabled() or PasswordHistory.is_student_forced_password_reset_enabled()): return self.user = user self.password = user.password self.save() @classmethod def is_student_password_reuse_restricted(cls): """ Returns whether the configuration which limits password reuse has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_diff_pw = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_DIFFERENT_STUDENT_PASSWORDS_BEFORE_REUSE', 0 ) return min_diff_pw > 0 @classmethod def is_staff_password_reuse_restricted(cls): """ Returns whether the configuration which limits password reuse has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_diff_pw = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_DIFFERENT_STAFF_PASSWORDS_BEFORE_REUSE', 0 ) return min_diff_pw > 0 @classmethod def is_password_reset_frequency_restricted(cls): """ Returns whether the configuration which limits the password reset frequency has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_days_between_reset = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_TIME_IN_DAYS_BETWEEN_ALLOWED_RESETS' ) return min_days_between_reset @classmethod def is_staff_forced_password_reset_enabled(cls): """ Returns whether the configuration which forces password resets to occur has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_days_between_reset = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_DAYS_FOR_STAFF_ACCOUNTS_PASSWORD_RESETS' ) return min_days_between_reset @classmethod def is_student_forced_password_reset_enabled(cls): """ Returns whether the configuration which forces password resets to occur has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_days_pw_reset = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_DAYS_FOR_STUDENT_ACCOUNTS_PASSWORD_RESETS' ) return min_days_pw_reset @classmethod def should_user_reset_password_now(cls, user): """ Returns whether a password has 'expired' and should be reset. Note there are two different expiry policies for staff and students """ if not settings.FEATURES['ADVANCED_SECURITY']: return False days_before_password_reset = None if user.is_staff: if cls.is_staff_forced_password_reset_enabled(): days_before_password_reset = \ settings.ADVANCED_SECURITY_CONFIG['MIN_DAYS_FOR_STAFF_ACCOUNTS_PASSWORD_RESETS'] elif cls.is_student_forced_password_reset_enabled(): days_before_password_reset = \ settings.ADVANCED_SECURITY_CONFIG['MIN_DAYS_FOR_STUDENT_ACCOUNTS_PASSWORD_RESETS'] if days_before_password_reset: history = PasswordHistory.objects.filter(user=user).order_by('-time_set') time_last_reset = None if history: # first element should be the last time we reset password time_last_reset = history[0].time_set else: # no history, then let's take the date the user joined time_last_reset = user.date_joined now = timezone.now() delta = now - time_last_reset return delta.days >= days_before_password_reset return False @classmethod def is_password_reset_too_soon(cls, user): """ Verifies that the password is not getting reset too frequently """ if not cls.is_password_reset_frequency_restricted(): return False history = PasswordHistory.objects.filter(user=user).order_by('-time_set') if not history: return False now = timezone.now() delta = now - history[0].time_set return delta.days < settings.ADVANCED_SECURITY_CONFIG['MIN_TIME_IN_DAYS_BETWEEN_ALLOWED_RESETS'] @classmethod def is_allowable_password_reuse(cls, user, new_password): """ Verifies that the password adheres to the reuse policies """ if not settings.FEATURES['ADVANCED_SECURITY']: return True if user.is_staff and cls.is_staff_password_reuse_restricted(): min_diff_passwords_required = \ settings.ADVANCED_SECURITY_CONFIG['MIN_DIFFERENT_STAFF_PASSWORDS_BEFORE_REUSE'] elif cls.is_student_password_reuse_restricted(): min_diff_passwords_required = \ settings.ADVANCED_SECURITY_CONFIG['MIN_DIFFERENT_STUDENT_PASSWORDS_BEFORE_REUSE'] else: min_diff_passwords_required = 0 # just limit the result set to the number of different # password we need history = PasswordHistory.objects.filter(user=user).order_by('-time_set')[:min_diff_passwords_required] for entry in history: # be sure to re-use the same salt # NOTE, how the salt is serialized in the password field is dependent on the algorithm # in pbkdf2_sha256 [LMS] it's the 3rd element, in sha1 [unit tests] it's the 2nd element hash_elements = entry.password.split('$') algorithm = hash_elements[0] if algorithm == 'pbkdf2_sha256': hashed_password = make_password(new_password, hash_elements[2]) elif algorithm == 'sha1': hashed_password = make_password(new_password, hash_elements[1]) else: # This means we got something unexpected. We don't want to throw an exception, but # log as an error and basically allow any password reuse AUDIT_LOG.error(''' Unknown password hashing algorithm "{0}" found in existing password hash, password reuse policy will not be enforced!!! '''.format(algorithm)) return True if entry.password == hashed_password: return False return True class LoginFailures(models.Model): """ This model will keep track of failed login attempts """ user = models.ForeignKey(User) failure_count = models.IntegerField(default=0) lockout_until = models.DateTimeField(null=True) @classmethod def _get_record_for_user(cls, user): """ Gets a user's record, and fixes any duplicates that may have arisen due to get_or_create race conditions. See https://code.djangoproject.com/ticket/13906 for details. Use this method in place of `LoginFailures.objects.get(user=user)` """ records = LoginFailures.objects.filter(user=user).order_by('-lockout_until') for extra_record in records[1:]: extra_record.delete() return records.get() @classmethod def is_feature_enabled(cls): """ Returns whether the feature flag around this functionality has been set """ return settings.FEATURES['ENABLE_MAX_FAILED_LOGIN_ATTEMPTS'] @classmethod def is_user_locked_out(cls, user): """ Static method to return in a given user has his/her account locked out """ try: record = cls._get_record_for_user(user) if not record.lockout_until: return False now = datetime.now(UTC) until = record.lockout_until is_locked_out = until and now < until return is_locked_out except ObjectDoesNotExist: return False @classmethod def increment_lockout_counter(cls, user): """ Ticks the failed attempt counter """ record, _ = LoginFailures.objects.get_or_create(user=user) record.failure_count = record.failure_count + 1 max_failures_allowed = settings.MAX_FAILED_LOGIN_ATTEMPTS_ALLOWED # did we go over the limit in attempts if record.failure_count >= max_failures_allowed: # yes, then store when this account is locked out until lockout_period_secs = settings.MAX_FAILED_LOGIN_ATTEMPTS_LOCKOUT_PERIOD_SECS record.lockout_until = datetime.now(UTC) + timedelta(seconds=lockout_period_secs) record.save() @classmethod def clear_lockout_counter(cls, user): """ Removes the lockout counters (normally called after a successful login) """ try: entry = cls._get_record_for_user(user) entry.delete() except ObjectDoesNotExist: return class CourseEnrollmentException(Exception): pass class NonExistentCourseError(CourseEnrollmentException): pass class EnrollmentClosedError(CourseEnrollmentException): pass class CourseFullError(CourseEnrollmentException): pass class AlreadyEnrolledError(CourseEnrollmentException): pass class CourseEnrollmentManager(models.Manager): """ Custom manager for CourseEnrollment with Table-level filter methods. """ def num_enrolled_in(self, course_id): """ Returns the count of active enrollments in a course. 'course_id' is the course_id to return enrollments """ enrollment_number = super(CourseEnrollmentManager, self).get_queryset().filter( course_id=course_id, is_active=1 ).count() return enrollment_number def is_course_full(self, course): """ Returns a boolean value regarding whether a course has already reached it's max enrollment capacity """ is_course_full = False if course.max_student_enrollments_allowed is not None: is_course_full = self.num_enrolled_in(course.id) >= course.max_student_enrollments_allowed return is_course_full def users_enrolled_in(self, course_id): """Return a queryset of User for every user enrolled in the course.""" return User.objects.filter( courseenrollment__course_id=course_id, courseenrollment__is_active=True ) def enrollment_counts(self, course_id): """ Returns a dictionary that stores the total enrollment count for a course, as well as the enrollment count for each individual mode. """ # Unfortunately, Django's "group by"-style queries look super-awkward query = use_read_replica_if_available( super(CourseEnrollmentManager, self).get_queryset().filter(course_id=course_id, is_active=True).values( 'mode').order_by().annotate(Count('mode'))) total = 0 enroll_dict = defaultdict(int) for item in query: enroll_dict[item['mode']] = item['mode__count'] total += item['mode__count'] enroll_dict['total'] = total return enroll_dict def enrolled_and_dropped_out_users(self, course_id): """Return a queryset of Users in the course.""" return User.objects.filter( courseenrollment__course_id=course_id ) class CourseEnrollment(models.Model): """ Represents a Student's Enrollment record for a single Course. You should generally not manipulate CourseEnrollment objects directly, but use the classmethods provided to enroll, unenroll, or check on the enrollment status of a given student. We're starting to consolidate course enrollment logic in this class, but more should be brought in (such as checking against CourseEnrollmentAllowed, checking course dates, user permissions, etc.) This logic is currently scattered across our views. """ MODEL_TAGS = ['course_id', 'is_active', 'mode'] user = models.ForeignKey(User) course_id = CourseKeyField(max_length=255, db_index=True) created = models.DateTimeField(auto_now_add=True, null=True, db_index=True) # If is_active is False, then the student is not considered to be enrolled # in the course (is_enrolled() will return False) is_active = models.BooleanField(default=True) # Represents the modes that are possible. We'll update this later with a # list of possible values. mode = models.CharField(default=CourseMode.DEFAULT_MODE_SLUG, max_length=100) objects = CourseEnrollmentManager() # Maintain a history of requirement status updates for auditing purposes history = HistoricalRecords() # cache key format e.g enrollment.<username>.<course_key>.mode = 'honor' COURSE_ENROLLMENT_CACHE_KEY = u"enrollment.{}.{}.mode" class Meta(object): unique_together = (('user', 'course_id'),) ordering = ('user', 'course_id') def __init__(self, *args, **kwargs): super(CourseEnrollment, self).__init__(*args, **kwargs) # Private variable for storing course_overview to minimize calls to the database. # When the property .course_overview is accessed for the first time, this variable will be set. self._course_overview = None def __unicode__(self): return ( "[CourseEnrollment] {}: {} ({}); active: ({})" ).format(self.user, self.course_id, self.created, self.is_active) @classmethod @transaction.atomic def get_or_create_enrollment(cls, user, course_key): """ Create an enrollment for a user in a class. By default *this enrollment is not active*. This is useful for when an enrollment needs to go through some sort of approval process before being activated. If you don't need this functionality, just call `enroll()` instead. Returns a CoursewareEnrollment object. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) It is expected that this method is called from a method which has already verified the user authentication and access. """ # If we're passing in a newly constructed (i.e. not yet persisted) User, # save it to the database so that it can have an ID that we can throw # into our CourseEnrollment object. Otherwise, we'll get an # IntegrityError for having a null user_id. assert isinstance(course_key, CourseKey) if user.id is None: user.save() enrollment, created = cls.objects.get_or_create( user=user, course_id=course_key, ) # If we *did* just create a new enrollment, set some defaults if created: enrollment.mode = CourseMode.DEFAULT_MODE_SLUG enrollment.is_active = False enrollment.save() return enrollment @classmethod def get_enrollment(cls, user, course_key): """Returns a CoursewareEnrollment object. Args: user (User): The user associated with the enrollment. course_id (CourseKey): The key of the course associated with the enrollment. Returns: Course enrollment object or None """ try: return cls.objects.get( user=user, course_id=course_key ) except cls.DoesNotExist: return None @classmethod def is_enrollment_closed(cls, user, course): """ Returns a boolean value regarding whether the user has access to enroll in the course. Returns False if the enrollment has been closed. """ # Disable the pylint error here, as per ormsbee. This local import was previously # in CourseEnrollment.enroll from courseware.access import has_access # pylint: disable=import-error return not has_access(user, 'enroll', course) def update_enrollment(self, mode=None, is_active=None, skip_refund=False): """ Updates an enrollment for a user in a class. This includes options like changing the mode, toggling is_active True/False, etc. Also emits relevant events for analytics purposes. This saves immediately. """ activation_changed = False # if is_active is None, then the call to update_enrollment didn't specify # any value, so just leave is_active as it is if self.is_active != is_active and is_active is not None: self.is_active = is_active activation_changed = True mode_changed = False # if mode is None, the call to update_enrollment didn't specify a new # mode, so leave as-is if self.mode != mode and mode is not None: self.mode = mode mode_changed = True if activation_changed or mode_changed: self.save() if activation_changed: if self.is_active: self.emit_event(EVENT_NAME_ENROLLMENT_ACTIVATED) dog_stats_api.increment( "common.student.enrollment", tags=[u"org:{}".format(self.course_id.org), u"offering:{}".format(self.course_id.offering), u"mode:{}".format(self.mode)] ) else: UNENROLL_DONE.send(sender=None, course_enrollment=self, skip_refund=skip_refund) self.emit_event(EVENT_NAME_ENROLLMENT_DEACTIVATED) dog_stats_api.increment( "common.student.unenrollment", tags=[u"org:{}".format(self.course_id.org), u"offering:{}".format(self.course_id.offering), u"mode:{}".format(self.mode)] ) if mode_changed: # Only emit mode change events when the user's enrollment # mode has changed from its previous setting self.emit_event(EVENT_NAME_ENROLLMENT_MODE_CHANGED) def emit_event(self, event_name): """ Emits an event to explicitly track course enrollment and unenrollment. """ try: context = contexts.course_context_from_course_id(self.course_id) assert isinstance(self.course_id, CourseKey) data = { 'user_id': self.user.id, 'course_id': self.course_id.to_deprecated_string(), 'mode': self.mode, } with tracker.get_tracker().context(event_name, context): tracker.emit(event_name, data) if hasattr(settings, 'LMS_SEGMENT_KEY') and settings.LMS_SEGMENT_KEY: tracking_context = tracker.get_tracker().resolve_context() analytics.track(self.user_id, event_name, { 'category': 'conversion', 'label': self.course_id.to_deprecated_string(), 'org': self.course_id.org, 'course': self.course_id.course, 'run': self.course_id.run, 'mode': self.mode, }, context={ 'ip': tracking_context.get('ip'), 'Google Analytics': { 'clientId': tracking_context.get('client_id') } }) except: # pylint: disable=bare-except if event_name and self.course_id: log.exception( u'Unable to emit event %s for user %s and course %s', event_name, self.user.username, self.course_id, ) @classmethod def enroll(cls, user, course_key, mode=None, check_access=False): """ Enroll a user in a course. This saves immediately. Returns a CoursewareEnrollment object. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_key` is our usual course_id string (e.g. "edX/Test101/2013_Fall) `mode` is a string specifying what kind of enrollment this is. The default is the default course mode, 'audit'. Other options include 'professional', 'verified', 'honor', 'no-id-professional' and 'credit'. See CourseMode in common/djangoapps/course_modes/models.py. `check_access`: if True, we check that an accessible course actually exists for the given course_key before we enroll the student. The default is set to False to avoid breaking legacy code or code with non-standard flows (ex. beta tester invitations), but for any standard enrollment flow you probably want this to be True. Exceptions that can be raised: NonExistentCourseError, EnrollmentClosedError, CourseFullError, AlreadyEnrolledError. All these are subclasses of CourseEnrollmentException if you want to catch all of them in the same way. It is expected that this method is called from a method which has already verified the user authentication. Also emits relevant events for analytics purposes. """ if mode is None: mode = _default_course_mode(unicode(course_key)) # All the server-side checks for whether a user is allowed to enroll. try: course = CourseOverview.get_from_id(course_key) except CourseOverview.DoesNotExist: # This is here to preserve legacy behavior which allowed enrollment in courses # announced before the start of content creation. if check_access: log.warning(u"User %s failed to enroll in non-existent course %s", user.username, unicode(course_key)) raise NonExistentCourseError if check_access: if cls.is_enrollment_closed(user, course): log.warning( u"User %s failed to enroll in course %s because enrollment is closed", user.username, course_key.to_deprecated_string() ) raise EnrollmentClosedError if cls.objects.is_course_full(course): log.warning( u"Course %s has reached its maximum enrollment of %d learners. User %s failed to enroll.", course_key.to_deprecated_string(), course.max_student_enrollments_allowed, user.username, ) raise CourseFullError if cls.is_enrolled(user, course_key): log.warning( u"User %s attempted to enroll in %s, but they were already enrolled", user.username, course_key.to_deprecated_string() ) if check_access: raise AlreadyEnrolledError # User is allowed to enroll if they've reached this point. enrollment = cls.get_or_create_enrollment(user, course_key) enrollment.update_enrollment(is_active=True, mode=mode) return enrollment @classmethod def enroll_by_email(cls, email, course_id, mode=None, ignore_errors=True): """ Enroll a user in a course given their email. This saves immediately. Note that enrolling by email is generally done in big batches and the error rate is high. For that reason, we supress User lookup errors by default. Returns a CoursewareEnrollment object. If the User does not exist and `ignore_errors` is set to `True`, it will return None. `email` Email address of the User to add to enroll in the course. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) `mode` is a string specifying what kind of enrollment this is. The default is the default course mode, 'audit'. Other options include 'professional', 'verified', 'honor', 'no-id-professional' and 'credit'. See CourseMode in common/djangoapps/course_modes/models.py. `ignore_errors` is a boolean indicating whether we should suppress `User.DoesNotExist` errors (returning None) or let it bubble up. It is expected that this method is called from a method which has already verified the user authentication and access. """ try: user = User.objects.get(email=email) return cls.enroll(user, course_id, mode) except User.DoesNotExist: err_msg = u"Tried to enroll email {} into course {}, but user not found" log.error(err_msg.format(email, course_id)) if ignore_errors: return None raise @classmethod def unenroll(cls, user, course_id, skip_refund=False): """ Remove the user from a given course. If the relevant `CourseEnrollment` object doesn't exist, we log an error but don't throw an exception. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) `skip_refund` can be set to True to avoid the refund process. """ try: record = cls.objects.get(user=user, course_id=course_id) record.update_enrollment(is_active=False, skip_refund=skip_refund) except cls.DoesNotExist: log.error( u"Tried to unenroll student %s from %s but they were not enrolled", user, course_id ) @classmethod def unenroll_by_email(cls, email, course_id): """ Unenroll a user from a course given their email. This saves immediately. User lookup errors are logged but will not throw an exception. `email` Email address of the User to unenroll from the course. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) """ try: user = User.objects.get(email=email) return cls.unenroll(user, course_id) except User.DoesNotExist: log.error( u"Tried to unenroll email %s from course %s, but user not found", email, course_id ) @classmethod def is_enrolled(cls, user, course_key): """ Returns True if the user is enrolled in the course (the entry must exist and it must have `is_active=True`). Otherwise, returns False. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) """ if not user.is_authenticated(): return False try: record = cls.objects.get(user=user, course_id=course_key) return record.is_active except cls.DoesNotExist: return False @classmethod def is_enrolled_by_partial(cls, user, course_id_partial): """ Returns `True` if the user is enrolled in a course that starts with `course_id_partial`. Otherwise, returns False. Can be used to determine whether a student is enrolled in a course whose run name is unknown. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_id_partial` (CourseKey) is missing the run component """ assert isinstance(course_id_partial, CourseKey) assert not course_id_partial.run # None or empty string course_key = SlashSeparatedCourseKey(course_id_partial.org, course_id_partial.course, '') querystring = unicode(course_key.to_deprecated_string()) try: return cls.objects.filter( user=user, course_id__startswith=querystring, is_active=1 ).exists() except cls.DoesNotExist: return False @classmethod def enrollment_mode_for_user(cls, user, course_id): """ Returns the enrollment mode for the given user for the given course `user` is a Django User object `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) Returns (mode, is_active) where mode is the enrollment mode of the student and is_active is whether the enrollment is active. Returns (None, None) if the courseenrollment record does not exist. """ try: record = cls.objects.get(user=user, course_id=course_id) return (record.mode, record.is_active) except cls.DoesNotExist: return (None, None) @classmethod def enrollments_for_user(cls, user): return cls.objects.filter(user=user, is_active=1) def is_paid_course(self): """ Returns True, if course is paid """ paid_course = CourseMode.is_white_label(self.course_id) if paid_course or CourseMode.is_professional_slug(self.mode): return True return False def activate(self): """Makes this `CourseEnrollment` record active. Saves immediately.""" self.update_enrollment(is_active=True) def deactivate(self): """Makes this `CourseEnrollment` record inactive. Saves immediately. An inactive record means that the student is not enrolled in this course. """ self.update_enrollment(is_active=False) def change_mode(self, mode): """Changes this `CourseEnrollment` record's mode to `mode`. Saves immediately.""" self.update_enrollment(mode=mode) def refundable(self): """ For paid/verified certificates, students may receive a refund if they have a verified certificate and the deadline for refunds has not yet passed. """ # In order to support manual refunds past the deadline, set can_refund on this object. # On unenrolling, the "UNENROLL_DONE" signal calls CertificateItem.refund_cert_callback(), # which calls this method to determine whether to refund the order. # This can't be set directly because refunds currently happen as a side-effect of unenrolling. # (side-effects are bad) if getattr(self, 'can_refund', None) is not None: return True # If the student has already been given a certificate they should not be refunded if GeneratedCertificate.certificate_for_student(self.user, self.course_id) is not None: return False # If it is after the refundable cutoff date they should not be refunded. refund_cutoff_date = self.refund_cutoff_date() if refund_cutoff_date and datetime.now(UTC) > refund_cutoff_date: return False course_mode = CourseMode.mode_for_course(self.course_id, 'verified') if course_mode is None: return False else: return True def refund_cutoff_date(self): """ Calculate and return the refund window end date. """ try: attribute = self.attributes.get(namespace='order', name='order_number') except ObjectDoesNotExist: return None order_number = attribute.value order = ecommerce_api_client(self.user).orders(order_number).get() refund_window_start_date = max( datetime.strptime(order['date_placed'], ECOMMERCE_DATE_FORMAT), self.course_overview.start.replace(tzinfo=None) ) return refund_window_start_date.replace(tzinfo=UTC) + EnrollmentRefundConfiguration.current().refund_window @property def username(self): return self.user.username @property def course(self): # Deprecated. Please use the `course_overview` property instead. return self.course_overview @property def course_overview(self): """ Returns a CourseOverview of the course to which this enrollment refers. Returns None if an error occurred while trying to load the course. Note: If the course is re-published within the lifetime of this CourseEnrollment object, then the value of this property will become stale. """ if not self._course_overview: try: self._course_overview = CourseOverview.get_from_id(self.course_id) except (CourseOverview.DoesNotExist, IOError): self._course_overview = None return self._course_overview def is_verified_enrollment(self): """ Check the course enrollment mode is verified or not """ return CourseMode.is_verified_slug(self.mode) def is_professional_enrollment(self): """ Check the course enrollment mode is professional or not """ return CourseMode.is_professional_slug(self.mode) @classmethod def is_enrolled_as_verified(cls, user, course_key): """ Check whether the course enrollment is for a verified mode. Arguments: user (User): The user object. course_key (CourseKey): The identifier for the course. Returns: bool """ enrollment = cls.get_enrollment(user, course_key) return ( enrollment is not None and enrollment.is_active and enrollment.is_verified_enrollment() ) @classmethod def cache_key_name(cls, user_id, course_key): """Return cache key name to be used to cache current configuration. Args: user_id(int): Id of user. course_key(unicode): Unicode of course key Returns: Unicode cache key """ return cls.COURSE_ENROLLMENT_CACHE_KEY.format(user_id, unicode(course_key)) @receiver(models.signals.post_save, sender=CourseEnrollment) @receiver(models.signals.post_delete, sender=CourseEnrollment) def invalidate_enrollment_mode_cache(sender, instance, **kwargs): # pylint: disable=unused-argument, invalid-name """Invalidate the cache of CourseEnrollment model. """ cache_key = CourseEnrollment.cache_key_name( instance.user.id, unicode(instance.course_id) ) cache.delete(cache_key) class ManualEnrollmentAudit(models.Model): """ Table for tracking which enrollments were performed through manual enrollment. """ enrollment = models.ForeignKey(CourseEnrollment, null=True) enrolled_by = models.ForeignKey(User, null=True) enrolled_email = models.CharField(max_length=255, db_index=True) time_stamp = models.DateTimeField(auto_now_add=True, null=True) state_transition = models.CharField(max_length=255, choices=TRANSITION_STATES) reason = models.TextField(null=True) @classmethod def create_manual_enrollment_audit(cls, user, email, state_transition, reason, enrollment=None): """ saves the student manual enrollment information """ return cls.objects.create( enrolled_by=user, enrolled_email=email, state_transition=state_transition, reason=reason, enrollment=enrollment ) @classmethod def get_manual_enrollment_by_email(cls, email): """ if matches returns the most recent entry in the table filtered by email else returns None. """ try: manual_enrollment = cls.objects.filter(enrolled_email=email).latest('time_stamp') except cls.DoesNotExist: manual_enrollment = None return manual_enrollment @classmethod def get_manual_enrollment(cls, enrollment): """ if matches returns the most recent entry in the table filtered by enrollment else returns None, """ try: manual_enrollment = cls.objects.filter(enrollment=enrollment).latest('time_stamp') except cls.DoesNotExist: manual_enrollment = None return manual_enrollment class CourseEnrollmentAllowed(models.Model): """ Table of users (specified by email address strings) who are allowed to enroll in a specified course. The user may or may not (yet) exist. Enrollment by users listed in this table is allowed even if the enrollment time window is past. """ email = models.CharField(max_length=255, db_index=True) course_id = CourseKeyField(max_length=255, db_index=True) auto_enroll = models.BooleanField(default=0) created = models.DateTimeField(auto_now_add=True, null=True, db_index=True) class Meta(object): unique_together = (('email', 'course_id'),) def __unicode__(self): return "[CourseEnrollmentAllowed] %s: %s (%s)" % (self.email, self.course_id, self.created) @classmethod def may_enroll_and_unenrolled(cls, course_id): """ Return QuerySet of students who are allowed to enroll in a course. Result excludes students who have already enrolled in the course. `course_id` identifies the course for which to compute the QuerySet. """ enrolled = CourseEnrollment.objects.users_enrolled_in(course_id=course_id).values_list('email', flat=True) return CourseEnrollmentAllowed.objects.filter(course_id=course_id).exclude(email__in=enrolled) @total_ordering class CourseAccessRole(models.Model): """ Maps users to org, courses, and roles. Used by student.roles.CourseRole and OrgRole. To establish a user as having a specific role over all courses in the org, create an entry without a course_id. """ objects = NoneToEmptyManager() user = models.ForeignKey(User) # blank org is for global group based roles such as course creator (may be deprecated) org = models.CharField(max_length=64, db_index=True, blank=True) # blank course_id implies org wide role course_id = CourseKeyField(max_length=255, db_index=True, blank=True) role = models.CharField(max_length=64, db_index=True) class Meta(object): unique_together = ('user', 'org', 'course_id', 'role') @property def _key(self): """ convenience function to make eq overrides easier and clearer. arbitrary decision that role is primary, followed by org, course, and then user """ return (self.role, self.org, self.course_id, self.user_id) def __eq__(self, other): """ Overriding eq b/c the django impl relies on the primary key which requires fetch. sometimes we just want to compare roles w/o doing another fetch. """ return type(self) == type(other) and self._key == other._key # pylint: disable=protected-access def __hash__(self): return hash(self._key) def __lt__(self, other): """ Lexigraphic sort """ return self._key < other._key # pylint: disable=protected-access def __unicode__(self): return "[CourseAccessRole] user: {} role: {} org: {} course: {}".format(self.user.username, self.role, self.org, self.course_id) #### Helper methods for use from python manage.py shell and other classes. def get_user_by_username_or_email(username_or_email): """ Return a User object, looking up by email if username_or_email contains a '@', otherwise by username. Raises: User.DoesNotExist is lookup fails. """ if '@' in username_or_email: return User.objects.get(email=username_or_email) else: return User.objects.get(username=username_or_email) def get_user(email): user = User.objects.get(email=email) u_prof = UserProfile.objects.get(user=user) return user, u_prof def user_info(email): user, u_prof = get_user(email) print "User id", user.id print "Username", user.username print "E-mail", user.email print "Name", u_prof.name print "Location", u_prof.location print "Language", u_prof.language return user, u_prof def change_email(old_email, new_email): user = User.objects.get(email=old_email) user.email = new_email user.save() def change_name(email, new_name): _user, u_prof = get_user(email) u_prof.name = new_name u_prof.save() def user_count(): print "All users", User.objects.all().count() print "Active users", User.objects.filter(is_active=True).count() return User.objects.all().count() def active_user_count(): return User.objects.filter(is_active=True).count() def create_group(name, description): utg = UserTestGroup() utg.name = name utg.description = description utg.save() def add_user_to_group(user, group): utg = UserTestGroup.objects.get(name=group) utg.users.add(User.objects.get(username=user)) utg.save() def remove_user_from_group(user, group): utg = UserTestGroup.objects.get(name=group) utg.users.remove(User.objects.get(username=user)) utg.save() DEFAULT_GROUPS = { 'email_future_courses': 'Receive e-mails about future MITx courses', 'email_helpers': 'Receive e-mails about how to help with MITx', 'mitx_unenroll': 'Fully unenrolled -- no further communications', '6002x_unenroll': 'Took and dropped 6002x' } def add_user_to_default_group(user, group): try: utg = UserTestGroup.objects.get(name=group) except UserTestGroup.DoesNotExist: utg = UserTestGroup() utg.name = group utg.description = DEFAULT_GROUPS[group] utg.save() utg.users.add(User.objects.get(username=user)) utg.save() def create_comments_service_user(user): if not settings.FEATURES['ENABLE_DISCUSSION_SERVICE']: # Don't try--it won't work, and it will fill the logs with lots of errors return try: cc_user = cc.User.from_django_user(user) cc_user.save() except Exception: # pylint: disable=broad-except log = logging.getLogger("edx.discussion") # pylint: disable=redefined-outer-name log.error( "Could not create comments service user with id {}".format(user.id), exc_info=True ) # Define login and logout handlers here in the models file, instead of the views file, # so that they are more likely to be loaded when a Studio user brings up the Studio admin # page to login. These are currently the only signals available, so we need to continue # identifying and logging failures separately (in views). @receiver(user_logged_in) def log_successful_login(sender, request, user, **kwargs): # pylint: disable=unused-argument """Handler to log when logins have occurred successfully.""" if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.info(u"Login success - user.id: {0}".format(user.id)) else: AUDIT_LOG.info(u"Login success - {0} ({1})".format(user.username, user.email)) @receiver(user_logged_out) def log_successful_logout(sender, request, user, **kwargs): # pylint: disable=unused-argument """Handler to log when logouts have occurred successfully.""" if hasattr(request, 'user'): if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.info(u"Logout - user.id: {0}".format(request.user.id)) # pylint: disable=logging-format-interpolation else: AUDIT_LOG.info(u"Logout - {0}".format(request.user)) # pylint: disable=logging-format-interpolation @receiver(user_logged_in) @receiver(user_logged_out) def enforce_single_login(sender, request, user, signal, **kwargs): # pylint: disable=unused-argument """ Sets the current session id in the user profile, to prevent concurrent logins. """ if settings.FEATURES.get('PREVENT_CONCURRENT_LOGINS', False): if signal == user_logged_in: key = request.session.session_key else: key = None if user: user.profile.set_login_session(key) class DashboardConfiguration(ConfigurationModel): """Dashboard Configuration settings. Includes configuration options for the dashboard, which impact behavior and rendering for the application. """ recent_enrollment_time_delta = models.PositiveIntegerField( default=0, help_text="The number of seconds in which a new enrollment is considered 'recent'. " "Used to display notifications." ) @property def recent_enrollment_seconds(self): return self.recent_enrollment_time_delta class LinkedInAddToProfileConfiguration(ConfigurationModel): """ LinkedIn Add to Profile Configuration This configuration enables the "Add to Profile" LinkedIn button on the student dashboard. The button appears when users have a certificate available; when clicked, users are sent to the LinkedIn site with a pre-filled form allowing them to add the certificate to their LinkedIn profile. """ MODE_TO_CERT_NAME = { "honor": _(u"{platform_name} Honor Code Certificate for {course_name}"), "verified": _(u"{platform_name} Verified Certificate for {course_name}"), "professional": _(u"{platform_name} Professional Certificate for {course_name}"), "no-id-professional": _( u"{platform_name} Professional Certificate for {course_name}" ), } company_identifier = models.TextField( help_text=_( u"The company identifier for the LinkedIn Add-to-Profile button " u"e.g 0_0dPSPyS070e0HsE9HNz_13_d11_" ) ) # Deprecated dashboard_tracking_code = models.TextField(default="", blank=True) trk_partner_name = models.CharField( max_length=10, default="", blank=True, help_text=_( u"Short identifier for the LinkedIn partner used in the tracking code. " u"(Example: 'edx') " u"If no value is provided, tracking codes will not be sent to LinkedIn." ) ) def add_to_profile_url(self, course_key, course_name, cert_mode, cert_url, source="o", target="dashboard"): """Construct the URL for the "add to profile" button. Arguments: course_key (CourseKey): The identifier for the course. course_name (unicode): The display name of the course. cert_mode (str): The course mode of the user's certificate (e.g. "verified", "honor", "professional") cert_url (str): The download URL for the certificate. Keyword Arguments: source (str): Either "o" (for onsite/UI), "e" (for emails), or "m" (for mobile) target (str): An identifier for the occurrance of the button. """ company_identifier = microsite.get_value('LINKEDIN_COMPANY_ID', self.company_identifier) params = OrderedDict([ ('_ed', company_identifier), ('pfCertificationName', self._cert_name(course_name, cert_mode).encode('utf-8')), ('pfCertificationUrl', cert_url), ('source', source) ]) tracking_code = self._tracking_code(course_key, cert_mode, target) if tracking_code is not None: params['trk'] = tracking_code return u'http://www.linkedin.com/profile/add?{params}'.format( params=urlencode(params) ) def _cert_name(self, course_name, cert_mode): """Name of the certification, for display on LinkedIn. """ return self.MODE_TO_CERT_NAME.get( cert_mode, _(u"{platform_name} Certificate for {course_name}") ).format( platform_name=microsite.get_value('platform_name', settings.PLATFORM_NAME), course_name=course_name ) def _tracking_code(self, course_key, cert_mode, target): """Create a tracking code for the button. Tracking codes are used by LinkedIn to collect analytics about certifications users are adding to their profiles. The tracking code format is: &trk=[partner name]-[certificate type]-[date]-[target field] In our case, we're sending: &trk=edx-{COURSE ID}_{COURSE MODE}-{TARGET} If no partner code is configured, then this will return None, indicating that tracking codes are disabled. Arguments: course_key (CourseKey): The identifier for the course. cert_mode (str): The enrollment mode for the course. target (str): Identifier for where the button is located. Returns: unicode or None """ return ( u"{partner}-{course_key}_{cert_mode}-{target}".format( partner=self.trk_partner_name, course_key=unicode(course_key), cert_mode=cert_mode, target=target ) if self.trk_partner_name else None ) class EntranceExamConfiguration(models.Model): """ Represents a Student's entrance exam specific data for a single Course """ user = models.ForeignKey(User, db_index=True) course_id = CourseKeyField(max_length=255, db_index=True) created = models.DateTimeField(auto_now_add=True, null=True, db_index=True) updated = models.DateTimeField(auto_now=True, db_index=True) # if skip_entrance_exam is True, then student can skip entrance exam # for the course skip_entrance_exam = models.BooleanField(default=True) class Meta(object): unique_together = (('user', 'course_id'), ) def __unicode__(self): return "[EntranceExamConfiguration] %s: %s (%s) = %s" % ( self.user, self.course_id, self.created, self.skip_entrance_exam ) @classmethod def user_can_skip_entrance_exam(cls, user, course_key): """ Return True if given user can skip entrance exam for given course otherwise False. """ can_skip = False if is_entrance_exams_enabled(): try: record = EntranceExamConfiguration.objects.get(user=user, course_id=course_key) can_skip = record.skip_entrance_exam except EntranceExamConfiguration.DoesNotExist: can_skip = False return can_skip class LanguageField(models.CharField): """Represents a language from the ISO 639-1 language set.""" def __init__(self, *args, **kwargs): """Creates a LanguageField. Accepts all the same kwargs as a CharField, except for max_length and choices. help_text defaults to a description of the ISO 639-1 set. """ kwargs.pop('max_length', None) kwargs.pop('choices', None) help_text = kwargs.pop( 'help_text', _("The ISO 639-1 language code for this language."), ) super(LanguageField, self).__init__( max_length=16, choices=settings.ALL_LANGUAGES, help_text=help_text, *args, **kwargs ) class LanguageProficiency(models.Model): """ Represents a user's language proficiency. Note that we have not found a way to emit analytics change events by using signals directly on this model or on UserProfile. Therefore if you are changing LanguageProficiency values, it is important to go through the accounts API (AccountsView) defined in /edx-platform/openedx/core/djangoapps/user_api/accounts/views.py or its associated api method (update_account_settings) so that the events are emitted. """ class Meta(object): unique_together = (('code', 'user_profile'),) user_profile = models.ForeignKey(UserProfile, db_index=True, related_name='language_proficiencies') code = models.CharField( max_length=16, blank=False, choices=settings.ALL_LANGUAGES, help_text=_("The ISO 639-1 language code for this language.") ) class CourseEnrollmentAttribute(models.Model): """ Provide additional information about the user's enrollment. """ enrollment = models.ForeignKey(CourseEnrollment, related_name="attributes") namespace = models.CharField( max_length=255, help_text=_("Namespace of enrollment attribute") ) name = models.CharField( max_length=255, help_text=_("Name of the enrollment attribute") ) value = models.CharField( max_length=255, help_text=_("Value of the enrollment attribute") ) def __unicode__(self): """Unicode representation of the attribute. """ return u"{namespace}:{name}, {value}".format( namespace=self.namespace, name=self.name, value=self.value, ) @classmethod def add_enrollment_attr(cls, enrollment, data_list): """Delete all the enrollment attributes for the given enrollment and add new attributes. Args: enrollment(CourseEnrollment): 'CourseEnrollment' for which attribute is to be added data(list): list of dictionaries containing data to save """ cls.objects.filter(enrollment=enrollment).delete() attributes = [ cls(enrollment=enrollment, namespace=data['namespace'], name=data['name'], value=data['value']) for data in data_list ] cls.objects.bulk_create(attributes) @classmethod def get_enrollment_attributes(cls, enrollment): """Retrieve list of all enrollment attributes. Args: enrollment(CourseEnrollment): 'CourseEnrollment' for which list is to retrieve Returns: list Example: >>> CourseEnrollmentAttribute.get_enrollment_attributes(CourseEnrollment) [ { "namespace": "credit", "name": "provider_id", "value": "hogwarts", }, ] """ return [ { "namespace": attribute.namespace, "name": attribute.name, "value": attribute.value, } for attribute in cls.objects.filter(enrollment=enrollment) ] class EnrollmentRefundConfiguration(ConfigurationModel): """ Configuration for course enrollment refunds. """ # TODO: Django 1.8 introduces a DurationField # (https://docs.djangoproject.com/en/1.8/ref/models/fields/#durationfield) # for storing timedeltas which uses MySQL's bigint for backing # storage. After we've completed the Django upgrade we should be # able to replace this field with a DurationField named # `refund_window` without having to run a migration or change # other code. refund_window_microseconds = models.BigIntegerField( default=1209600000000, help_text=_( "The window of time after enrolling during which users can be granted" " a refund, represented in microseconds. The default is 14 days." ) ) @property def refund_window(self): """Return the configured refund window as a `datetime.timedelta`.""" return timedelta(microseconds=self.refund_window_microseconds) @refund_window.setter def refund_window(self, refund_window): """Set the current refund window to the given timedelta.""" self.refund_window_microseconds = int(refund_window.total_seconds() * 1000000)
agpl-3.0
-1,044,764,249,354,505,000
36.307511
142
0.63806
false
matthew-humphrey/treater
Lib/treater/__main__.py
1
1400
#!/usr/bin/python # treater/__main__.py """Main (module) entry point for Treater, a Raspberry Pi-based remotely accessible pet feeder""" from datetime import datetime from twisted.internet import reactor from website import TreatWeb, TreatWebConfig from machine import TreatMachine, TreatMachineConfig from camera import TreatCam, TreatCamConfig from argparse import ArgumentParser from ConfigParser import SafeConfigParser def initializeLogging(configFile): from logging.config import fileConfig from twisted.python.log import PythonLoggingObserver fileConfig(configFile) observer = PythonLoggingObserver() observer.start() if __name__ == "__main__": parser = ArgumentParser(description = "Service for Raspberry Pi powered pet treat feeder") parser.add_argument("-C") args = parser.parse_args() config = SafeConfigParser() config.read(args.C) initializeLogging(args.C) from logging import getLogger LOGGER = getLogger("main") camera = TreatCam(reactor, TreatCamConfig(config)) machine = TreatMachine(reactor, TreatMachineConfig(config)) machine.start() web = TreatWeb(reactor, machine, camera, TreatWebConfig(config)) def shutdown(): machine.stop() machine.close() LOGGER.info("Treater exiting") reactor.addSystemEventTrigger('before', 'shutdown', shutdown) reactor.run()
mit
-5,590,136,520,256,911,000
27.571429
96
0.727857
false
mganeva/mantid
scripts/test/TOFTOF/TOFTOFScriptElementTest.py
1
11288
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + from __future__ import (absolute_import, division, print_function) from reduction_gui.reduction.toftof.toftof_reduction import TOFTOFScriptElement, OptionalFloat import testhelpers import unittest import sys try: unicode('test for unicode type') except NameError: unicode = str class TOFTOFScriptElementTest(unittest.TestCase): @staticmethod def setMinimumValidInputs(scriptElement): scriptElement.reset() scriptElement.facility_name = 'MLZ' scriptElement.instrument_name = 'TOFTOF' # prefix of (some) workspace names scriptElement.prefix = 'ws' # data files are here scriptElement.dataDir = '/Somepath/somewhere/' # vanadium runs & comment scriptElement.vanRuns = '' scriptElement.vanCmnt = '' scriptElement.vanTemp = OptionalFloat(None) # empty can runs, comment, and factor scriptElement.ecRuns = '' scriptElement.ecTemp = OptionalFloat(None) scriptElement.ecFactor = 1 # data runs: [(runs,comment, temperature), ...] scriptElement.dataRuns = [[unicode('0:5'), unicode('Comment for Run 0:5'), OptionalFloat(None)]] # additional parameters scriptElement.binEon = False scriptElement.binEstart = 0.0 scriptElement.binEstep = 0.0 scriptElement.binEend = 0.0 scriptElement.binQon = False scriptElement.binQstart = 0.0 scriptElement.binQstep = 0.0 scriptElement.binQend = 0.0 scriptElement.maskDetectors = '' # options scriptElement.subtractECVan = False scriptElement.normalise = TOFTOFScriptElement.NORM_NONE scriptElement.correctTof = TOFTOFScriptElement.CORR_TOF_NONE scriptElement.replaceNaNs = False scriptElement.createDiff = False scriptElement.keepSteps = False # save data scriptElement.saveDir = '' scriptElement.saveSofTWNxspe = False scriptElement.saveSofTWNexus = False scriptElement.saveSofTWAscii = False scriptElement.saveSofQWNexus = False scriptElement.saveSofQWAscii = False @staticmethod def setValidInputs(scriptElement): scriptElement.reset() scriptElement.facility_name = 'MLZ' scriptElement.instrument_name = 'TOFTOF' # prefix of (some) workspace names scriptElement.prefix = 'ws' # data files are here scriptElement.dataDir = '/Somepath/somewhere/' # vanadium runs & comment scriptElement.vanRuns = '1:3' scriptElement.vanCmnt = 'vanadium comment' scriptElement.vanTemp = OptionalFloat(None) # empty can runs, comment, and factor scriptElement.ecRuns = '' scriptElement.ecTemp = OptionalFloat(None) scriptElement.ecFactor = 1 # data runs: [(runs,comment, temperature), ...] scriptElement.dataRuns = [[unicode('0:5'), unicode('Comment for Run 0:5'), OptionalFloat(None)]] # additional parameters scriptElement.binEon = True scriptElement.binEstart = 0.0 scriptElement.binEstep = 0.1 scriptElement.binEend = 1.0 scriptElement.binQon = True scriptElement.binQstart = 0.0 scriptElement.binQstep = 0.1 scriptElement.binQend = 1.0 scriptElement.maskDetectors = '' # options scriptElement.subtractECVan = False scriptElement.normalise = TOFTOFScriptElement.NORM_NONE scriptElement.correctTof = TOFTOFScriptElement.CORR_TOF_NONE scriptElement.replaceNaNs = False scriptElement.createDiff = False scriptElement.keepSteps = False # save data scriptElement.saveDir = '' scriptElement.saveSofTWNxspe = False scriptElement.saveSofTWNexus = False scriptElement.saveSofTWAscii = False scriptElement.saveSofQWNexus = False scriptElement.saveSofQWAscii = False def setUp(self): self.scriptElement = TOFTOFScriptElement() self.setValidInputs(self.scriptElement) def tearDown(self): self.scriptElement = None #done def test_that_inputs_saved_and_loaded_correctly(self): scriptElement2 = TOFTOFScriptElement() scriptElement2.from_xml(self.scriptElement.to_xml()) scriptElement2.facility_name = 'MLZ' scriptElement2.instrument_name = 'TOFTOF' for name in dir(self.scriptElement): if not name.startswith('__') and not hasattr(getattr(self.scriptElement, name), '__call__'): self.assertEqual(getattr(self.scriptElement, name), getattr(scriptElement2, name)) # due to an issue with 'exec()' in functtions with nested functions in python 2.7 (2.7.8 and earlier), # this function has to stay outside of 'test_that_script_is_executable_in_mantid()'. # see https://bugs.python.org/issue21591 # cannot be a @staticmethod for the same reasons def execScript(self, script): exec(script, dict(), dict()) def test_that_script_is_executable_in_mantid(self): # data files are here self.scriptElement.dataDir = '' # vanadium runs & comment self.scriptElement.vanRuns = 'TOFTOFTestdata.nxs' # empty can runs, comment, and factor self.scriptElement.ecRuns = 'TOFTOFTestdata.nxs' self.scriptElement.ecTemp = OptionalFloat(21.0) self.scriptElement.ecFactor = 0.9 # data runs: [(runs,comment, temperature), ...] self.scriptElement.dataRuns = [ [unicode('TOFTOFTestdata.nxs'), unicode('H2O 21C'), OptionalFloat(None)], [unicode('TOFTOFTestdata.nxs'), unicode('H2O 34C'), OptionalFloat(34.0)] ] self.scriptElement.maskDetectors = '1,2' # options self.scriptElement.subtractECVan = True self.scriptElement.normalise = TOFTOFScriptElement.NORM_MONITOR self.scriptElement.correctTof = TOFTOFScriptElement.CORR_TOF_VAN self.scriptElement.replaceNaNs = True self.scriptElement.createDiff = True self.scriptElement.keepSteps = True testhelpers.assertRaisesNothing(self, self.execScript, self.scriptElement.to_script().replace('import matplotlib.pyplot as plt', '')) def test_that_script_has_correct_syntax(self): self.scriptElement.binEon = False self.scriptElement.binQon = False self.scriptElement.dataRuns = [('0:5', 'Comment for Run 0:5', None)] script = self.scriptElement.to_script() HasNullBytesError = TypeError if sys.version_info >= (3, 5): HasNullBytesError = ValueError try: compiledScript = compile(script, '<string>', 'exec') except SyntaxError as e: self.fail("generated script has a syntax error: '{}'".format(e)) except HasNullBytesError as e: self.fail("generated script has null bytes: '{}'".format(e)) self.assertIsNotNone(compiledScript) def test_that_inputs_are_validated_correctly(self): try: self.scriptElement.validate_inputs() except RuntimeError as e: self.fail(e) # some handy aliases: OptFloat = OptionalFloat # [(inputDict, causesException=True), ...] modifiedValues = [ ({}, False), ({'correctTof': TOFTOFScriptElement.CORR_TOF_VAN}, True), ({'correctTof': TOFTOFScriptElement.CORR_TOF_VAN, 'vanRuns': '0:2', 'vanCmnt': 'vanComment'}, False), ({'subtractECVan': True, 'vanRuns': '', 'vanCmnt': 'vanComment', 'ecRuns': '3:5'}, True), ({'subtractECVan': True, 'vanRuns': '', 'vanCmnt': '', 'ecRuns': '3:5'}, True), ({'subtractECVan': True, 'vanRuns': '0:2', 'vanCmnt': 'vanComment', 'ecRuns': ''}, True), ({'subtractECVan': True, 'vanRuns': '0:2', 'vanCmnt': 'vanComment', 'ecRuns': '3:5'}, False), ({}, False), ({'binEon': True, 'binEstart': 1.0, 'binEstep': 0.1, 'binEend': 1.0}, True), ({'binEon': True, 'binEstart': 0.0, 'binEstep': 2.0, 'binEend': 1.0}, True), ({'binEon': True, 'binEstart': 0.0, 'binEstep': 0.0, 'binEend': 1.0}, True), ({'binEon': True, 'binEstart': 0.0, 'binEstep':-0.1, 'binEend': 1.0}, True), ({'binEon': False, 'binEstart': 0.0, 'binEstep':-0.1, 'binEend': 1.0}, False), ({'binQon': True, 'binQstart': 1.0, 'binQstep': 0.1, 'binQend': 1.0}, True), ({'binQon': True, 'binQstart': 0.0, 'binQstep': 2.0, 'binQend': 1.0}, True), ({'binQon': True, 'binQstart': 0.0, 'binQstep': 0.0, 'binQend': 1.0}, True), ({'binQon': True, 'binQstart': 0.0, 'binQstep':-0.1, 'binQend': 1.0}, True), ({'binQon': False, 'binQstart': 1.0, 'binQstep': 0.1, 'binQend': 1.0}, False), ({'dataRuns' : []}, True), ({'dataRuns' : [[unicode('0:5'), unicode(''), OptFloat(None)]]}, True), ({'dataRuns' : [ [unicode('0:5'), unicode('Comment for Run 0:5'), OptFloat(None)], [unicode('6:7'), unicode(''), OptFloat(None)] ]}, True), ({'dataRuns' : [ [unicode('0:5'), unicode(''), OptFloat(None)], [unicode('6:7'), unicode('Comment for Run 6:7'), OptFloat(None)] ]}, True), ({'vanRuns': '0:2', 'vanCmnt': ''}, True), ({'vanRuns': '0:2', 'vanCmnt': 'Comment for Vanadium'}, False), ({'saveSofTWNxspe': True, 'saveSofTWAscii': True, 'saveDir': ''}, True), ({'saveSofTWNexus': True, 'saveSofQWNexus': False, 'saveDir': ''}, True), ({'saveSofQWNexus': True, 'saveSofQWAscii': True, 'saveDir': '/some/SaveDir/'}, False), ] def executeSubTest(inputs, shouldThrow): self.setMinimumValidInputs(self.scriptElement) for name, value in inputs.items(): setattr(self.scriptElement, name, value) try: self.scriptElement.validate_inputs() except RuntimeError as e: if not shouldThrow: self.fail("Valid input did cause an exception: '{}'.\nThe input was: {}".format(e, inputs)) else: if shouldThrow: self.fail("Invalid input did NOT cause an exception!\nThe input was: {}".format(inputs)) for inputs, shouldThrow in modifiedValues: if hasattr(self, 'subTest'): with self.subTest(): executeSubTest(inputs, shouldThrow) else: executeSubTest(inputs, shouldThrow) if __name__ == '__main__': unittest.main()
gpl-3.0
-3,606,713,197,239,949,300
39.314286
118
0.594171
false
Usherwood/usherwood_ds
usherwood_ds/nlp/distinctive_words.py
1
8319
#!/usr/bin/env python """Finds distinctive word between two corpuses""" import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer __author__ = "Peter J Usherwood" __python_version__ = "3.5" class DistinctiveWords: """Parent class for finding the distinctive words between two corpuses of text""" def __init__(self, raw_text, max_features=10000): """ :param raw_text: A 2 element list with each corpus as a string occupying 1 element :param max_features: The maximum number of features to analyse """ self.raw_text = raw_text self.keyness = pd.DataFrame(None) cv = CountVectorizer(max_features=max_features) self.wfm = cv.fit_transform(self.raw_text) self.vocab = np.array(cv.get_feature_names()) self.rates = np.asarray(1000*self.wfm / np.sum(self.wfm, axis=1)) def unique_words(self, drop_uniques=True): """ Returns a dataframe of the words that are unique to one of the corpuses. It is recommended these are removed from subsequent analysis as they are trivial cases that will dominate. :param drop_uniques: Boolean, drop the unique words from the wfm and recalculate rates :return: Dataframe of the words that are unique to one of the corpuses """ a_rates = np.asarray(self.rates[0]) b_rates = np.asarray(self.rates[1]) distinctive_indices = (a_rates*b_rates) == 0 joint_average_rates = a_rates[distinctive_indices] + b_rates[distinctive_indices] ab_distincts = pd.DataFrame(np.array([self.vocab[distinctive_indices], joint_average_rates]).T, columns=['Vocab', 'Rates']).sort_values(by=['Rates'], ascending=False) if drop_uniques: self.wfm = self.wfm[:, np.invert(distinctive_indices)] self.rates = self.rates[:, np.invert(distinctive_indices)] self.vocab = self.vocab[np.invert(distinctive_indices)] return ab_distincts def basic_rate_differences(self): """ Populates the keyness dataframe with 3 columns: - Mean Avergae Rate, the average rate the word appears in both corpuses - Average Rate Difference, the difference in the average rates between the two corpuses, a simple measure of distinctiveness, however frequent words will dominate - Normalized Average Rate Difference The Average Rate Difference / Mean Avergae Rate, this is to normalize so that frequent words do not dominate, however now rare words come through more than they should """ a_rates = np.asarray(self.rates[0]) b_rates = np.asarray(self.rates[1]) keyness_arr = np.abs(a_rates - b_rates) if self.keyness.empty: self.keyness = pd.DataFrame(np.array([self.vocab, keyness_arr]).T, columns=['Vocab', 'Average Rate Difference']) self.keyness['Mean Average Rate'] = np.mean(self.rates, axis=0) self.keyness['Average Rate Difference'] = self.keyness['Average Rate Difference'].astype(float) self.keyness['Mean Average Rate'].astype(np.float) self.keyness['Normalized Average Rate Difference'] = self.keyness['Average Rate Difference'] /\ self.keyness['Mean Average Rate'] return True def bayesian_group_comparison(self): """ https://de.dariah.eu/tatom/feature_selection.html Populates the keyness dataframe with a column Keyness, this is defined through Bayesian group comparison, where we model each words rate in a corpus as a normal distribution, seperated by a half distance that we will use as a measure of whether the means are the same or not. We split the means of the distributions into the average mean rate, and this half distance, and set priors for these along with the standard deviation. We then use Gibbs samplung to estimate the half distance. The hyperparameters on the priors are hard coded into this class but can be fined tuned if necessary. """ a_rates = np.asarray(self.rates[0]) b_rates = np.asarray(self.rates[1]) keyness_arr = [] for index, word in enumerate(self.vocab): keyness_arr.append(delta_confidence(word, a_rates, b_rates, self.vocab, smax=200, mu0=3, tau20=1.5 ** 2, nu0=1, sigma20=1, delta0=0, gamma20=1.5 ** 2)) if self.keyness.empty: self.keyness = pd.DataFrame(np.array([self.vocab, keyness_arr]).T, columns=['Vocab', 'Keyness']) else: self.keyness['Keyness'] = keyness_arr return True def sample_posterior(y1, y2, mu0, sigma20, nu0, delta0, gamma20, tau20, smax): """ Draw samples from posterior distribution using Gibbs sampling Parameters :param y1: Rate of the word in the first corpus :param y2: Rate of the word in the second corpus :param mu0: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param sigma20: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param nu0: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param delta0: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param gamma20: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param tau20: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param smax: int - Number of samples :return: chains - dict of array. Dictionary has keys: 'mu', 'delta', and 'sigma2'. """ """ ---------- `S` is the number of samples Returns ------- chains : dict of array Dictionary has keys: 'mu', 'delta', and 'sigma2'. """ n1, n2 = len(y1), len(y2) mu = (np.mean(y1) + np.mean(y2)) / 2 delta = (np.mean(y1) - np.mean(y2)) / 2 bay_vars = ['mu', 'delta', 'sigma2'] chains = {key: np.empty(smax) for key in bay_vars} for s in range(smax): a = (nu0 + n1 + n2) / 2 b = (nu0 * sigma20 + np.sum((y1 - mu - delta) ** 2) + np.sum((y2 - mu + delta) ** 2)) / 2 sigma2 = 1 / np.random.gamma(a, 1 / b) mu_var = 1 / (1 / gamma20 + (n1 + n2) / sigma2) mu_mean = mu_var * (mu0 / gamma20 + np.sum(y1 - delta) / sigma2 + np.sum(y2 + delta) / sigma2) mu = np.random.normal(mu_mean, np.sqrt(mu_var)) delta_var = 1 / (1 / tau20 + (n1 + n2) / sigma2) delta_mean = delta_var * (delta0 / tau20 + np.sum(y1 - mu) / sigma2 - np.sum(y2 - mu) / sigma2) delta = np.random.normal(delta_mean, np.sqrt(delta_var)) chains['mu'][s] = mu chains['delta'][s] = delta chains['sigma2'][s] = sigma2 return chains def delta_confidence(word, a_rates, b_rates, vocab, smax=200, mu0=3, tau20=1.5 ** 2, nu0=1, sigma20=1, delta0=0, gamma20=1.5 ** 2): """ Calculate the difference in mean rates using Gibbs sampling for a given word. :param word: String, the word to sample :param a_rates: wfm for the first corpus :param b_rates: wfm for the second corpus :param vocab: Array of strings, the vocabulary used in the wfm defining a_rates and b_rates :param mu0: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param sigma20: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param nu0: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param delta0: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param gamma20: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param tau20: Hyperparameter, see https://de.dariah.eu/tatom/feature_selection.html :param smax: int - Number of samples :return: The maximum half distance measure, as we only care about distance the positivity is not important """ y1, y2 = a_rates[vocab == word], b_rates[vocab == word] chains = sample_posterior(y1, y2, mu0, sigma20, nu0, delta0, gamma20, tau20, smax) delta = chains['delta'] return np.max([np.mean(delta < 0), np.mean(delta > 0)])
bsd-2-clause
2,659,791,577,478,884,000
43.486631
119
0.638298
false
ishay2b/tensorflow
tensorflow/python/ops/variable_scope.py
1
76088
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A class to store named variables and a scope operator to manage sharing.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections as collections_lib import copy import functools import traceback import six from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.estimator import util as estimator_util from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import tf_contextlib __all__ = ["VariableScope", "get_variable_scope", "get_variable", "get_local_variable", "variable_scope", "variable_op_scope", "no_regularizer"] class _PartitionInfo(object): """Holds partition info used by initializer functions. """ def __init__(self, full_shape, var_offset): """Constructor. Args: full_shape: Tuple or list of `int` indicating the full combined shape of the partitioned variables. var_offset: Tuple or list of `int` specifying offset of this partition with respect to the full variable for each dimension. Raises: TypeError: If `full_shape` or `var_offset` is not a sequence. ValueError: If `full_shape` or `var_offset` differ in length. If `var_offset` exceeds `full_shape` in any dimension. """ if not isinstance(full_shape, collections_lib.Sequence) or isinstance( full_shape, six.string_types): raise TypeError( "`full_shape` must be a sequence (like tuple or list) instead of " + type(full_shape).__name__) if not isinstance(var_offset, collections_lib.Sequence) or isinstance( var_offset, six.string_types): raise TypeError( "`var_offset` must be a sequence (like tuple or list) instead of " + type(var_offset).__name__) if len(var_offset) != len(full_shape): raise ValueError( "Expected equal length, but `var_offset` is of length {} while " "full_shape is of length {}.".format( len(var_offset), len(full_shape))) for i in xrange(len(full_shape)): offset = var_offset[i] shape = full_shape[i] if offset < 0 or offset >= shape: raise ValueError( "Expected 0 <= offset < shape but found offset={}, shape={} for " "var_offset={}, full_shape={}".format(offset, shape, var_offset, full_shape)) self._full_shape = full_shape self._var_offset = var_offset @property def full_shape(self): return self._full_shape @property def var_offset(self): return self._var_offset def single_offset(self, shape): """Returns the offset when the variable is partitioned in at most one dim. Args: shape: Tuple or list of `int` indicating the shape of one specific variable partition. Returns: `int` representing the offset in the dimension along which the variable is partitioned. Returns 0 if the variable is not being partitioned. Raises: ValueError: Depending on self.single_slice_dim(). """ single_slice_dim = self.single_slice_dim(shape) # If this variable is not being partitioned at all, single_slice_dim() could # return None. if single_slice_dim is None: return 0 return self.var_offset[single_slice_dim] def single_slice_dim(self, shape): """Returns the slice dim when the variable is partitioned only in one dim. Args: shape: Tuple or list of `int` indicating the shape of one specific variable partition. Returns: `int` representing the dimension that the variable is partitioned in, or `None` if the variable doesn't seem to be partitioned at all. Raises: TypeError: If `shape` is not a sequence. ValueError: If `shape` is not the same length as `self.full_shape`. If the variable is partitioned in more than one dimension. """ if not isinstance(shape, collections_lib.Sequence) or isinstance( shape, six.string_types): raise TypeError( "`shape` must be a sequence (like tuple or list) instead of " + type(shape).__name__) if len(shape) != len(self.full_shape): raise ValueError( "Expected equal length, but received shape={} of length {} while " "self.full_shape={} is of length {}.".format(shape, len( shape), self.full_shape, len(self.full_shape))) for i in xrange(len(shape)): if self.var_offset[i] + shape[i] > self.full_shape[i]: raise ValueError( "With self.var_offset={}, a partition of shape={} would exceed " "self.full_shape={} in dimension {}.".format( self.var_offset, shape, self.full_shape, i)) slice_dim = None for i in xrange(len(shape)): if shape[i] == self.full_shape[i]: continue if slice_dim is not None: raise ValueError( "Cannot use single_slice_dim() with shape={} and " "self.full_shape={} since slice dim could be either dimension {} " "or {}.".format(shape, self.full_shape, i, slice_dim)) slice_dim = i return slice_dim class _VariableStore(object): """Variable store that carries a number of named Variables. New variable names and new variables can be created; all stored variables are initialized with the initializer passed to __init__. Attributes: vars: a dictionary with string names (same as passed in GetVar) as keys and the corresponding TensorFlow Variables as values. """ def __init__(self): """Create a variable store.""" self._vars = {} # A dictionary of the stored TensorFlow variables. self._partitioned_vars = {} # A dict of the stored PartitionedVariables. self.variable_scopes_count = {} # Count re-used variable scopes. def open_variable_scope(self, scope_name): if scope_name in self.variable_scopes_count: self.variable_scopes_count[scope_name] += 1 else: self.variable_scopes_count[scope_name] = 1 def close_variable_subscopes(self, scope_name): for k in self.variable_scopes_count: if not scope_name or k.startswith(scope_name + "/"): self.variable_scopes_count[k] = 0 def variable_scope_count(self, scope_name): return self.variable_scopes_count.get(scope_name, 0) def get_variable(self, name, shape=None, dtype=dtypes.float32, initializer=None, regularizer=None, reuse=None, trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, custom_getter=None, constraint=None): """Gets an existing variable with these parameters or create a new one. If a variable with the given name is already stored, we return the stored variable. Otherwise, we create a new one. Set `reuse` to `True` when you only want to reuse existing Variables. Set `reuse` to `False` when you only want to create new Variables. If `reuse` is `None` (the default), both new and existing variables are returned. If initializer is `None` (the default), the default initializer passed in the constructor is used. If that one is `None` too, we use a new `glorot_uniform_initializer`. If initializer is a Tensor, we use it as a value and derive the shape from the initializer. If a partitioner is provided, a `PartitionedVariable` is returned. Accessing this object as a `Tensor` returns the shards concatenated along the partition axis. Some useful partitioners are available. See, e.g., `variable_axis_size_partitioner` and `min_max_variable_partitioner`. Args: name: The name of the new or existing variable. shape: Shape of the new or existing variable. dtype: Type of the new or existing variable (defaults to `DT_FLOAT`). initializer: Initializer for the variable. regularizer: A (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. reuse: a Boolean or `None`. Controls reuse or creation of variables. trainable: If `True` also add the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). collections: List of graph collections keys to add the `Variable` to. Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`). caching_device: Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the `Variable` reside, to deduplicate copying through `Switch` and other conditional statements. partitioner: Optional callable that accepts a fully defined `TensorShape` and dtype of the `Variable` to be created, and returns a list of partitions for each axis (currently only one axis can be partitioned). validate_shape: If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial_value must be known. use_resource: If False, creates a regular Variable. If True, creates instead an experimental ResourceVariable which has well-defined semantics. Defaults to False (will later change to True). custom_getter: Callable that takes as a first argument the true getter, and allows overwriting the internal get_variable method. The signature of `custom_getter` should match that of this method, but the most future-proof version will allow for changes: `def custom_getter(getter, *args, **kwargs)`. Direct access to all `get_variable` parameters is also allowed: `def custom_getter(getter, name, *args, **kwargs)`. A simple identity custom getter that simply creates variables with modified names is: ```python def custom_getter(getter, name, *args, **kwargs): return getter(name + '_suffix', *args, **kwargs) ``` constraint: An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. Returns: The created or existing `Variable` (or `PartitionedVariable`, if a partitioner was used). Raises: ValueError: when creating a new variable and shape is not declared, when reusing a variable and specifying a conflicting shape, or when violating reuse during variable creation. """ if custom_getter is not None and not callable(custom_getter): raise ValueError( "Passed a custom_getter which is not callable: %s" % custom_getter) # If a *_ref type is passed in an error would be triggered further down the # stack. We prevent this using base_dtype to get a non-ref version of the # type, before doing anything else. When _ref types are removed in favor of # resources, this line can be removed. try: dtype = dtype.base_dtype except AttributeError: # .base_dtype not existing means that we will try and use the raw dtype # which was passed in - this might be a NumPy type which is valid. pass # This is the main logic of get_variable. However, custom_getter # may override this logic. So we save it as a callable and pass # it to custom_getter. # Note: the parameters of _true_getter, and their documentation, match # *exactly* item-for-item with the docstring of this method. def _true_getter(name, shape=None, dtype=dtypes.float32, # pylint: disable=missing-docstring initializer=None, regularizer=None, reuse=None, trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, constraint=None): is_scalar = (shape is not None and isinstance(shape, collections_lib.Sequence) and not shape) # Partitioned variable case if partitioner is not None and not is_scalar: if not callable(partitioner): raise ValueError( "Partitioner must be callable, but received: %s" % partitioner) with ops.name_scope(None): return self._get_partitioned_variable(name=name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, reuse=reuse, trainable=trainable, collections=collections, caching_device=caching_device, partitioner=partitioner, validate_shape=validate_shape, use_resource=use_resource, constraint=constraint) # Special case for partitioned variable to allow reuse without having to # specify partitioner. if (reuse is True and partitioner is None and name in self._partitioned_vars): return self._get_partitioned_variable(name=name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, reuse=reuse, trainable=trainable, collections=collections, caching_device=caching_device, partitioner=None, validate_shape=validate_shape, use_resource=use_resource, constraint=constraint) # Single variable case if "%s/part_0" % name in self._vars: raise ValueError( "No partitioner was provided, but a partitioned version of the " "variable was found: %s/part_0. Perhaps a variable of the same " "name was already created with partitioning?" % name) return self._get_single_variable( name=name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, reuse=reuse, trainable=trainable, collections=collections, caching_device=caching_device, validate_shape=validate_shape, use_resource=use_resource, constraint=constraint) if custom_getter is not None: # Handle backwards compatibility with getter arguments that were added # to the API after users started writing custom getters. custom_getter_kwargs = { "getter": _true_getter, "name": name, "shape": shape, "dtype": dtype, "initializer": initializer, "regularizer": regularizer, "reuse": reuse, "trainable": trainable, "collections": collections, "caching_device": caching_device, "partitioner": partitioner, "validate_shape": validate_shape, "use_resource": use_resource, } # `fn_args` can handle functions, `functools.partial`, `lambda`. if "constraint" in estimator_util.fn_args(custom_getter): custom_getter_kwargs["constraint"] = constraint return custom_getter(**custom_getter_kwargs) else: return _true_getter( name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, reuse=reuse, trainable=trainable, collections=collections, caching_device=caching_device, partitioner=partitioner, validate_shape=validate_shape, use_resource=use_resource, constraint=constraint) def _get_partitioned_variable( self, name, partitioner, shape=None, dtype=dtypes.float32, initializer=None, regularizer=None, reuse=None, trainable=True, collections=None, caching_device=None, validate_shape=True, use_resource=None, constraint=None): """Gets or creates a sharded variable list with these parameters. The `partitioner` must be a callable that accepts a fully defined `TensorShape` and returns a sequence of integers (the `partitions`). These integers describe how to partition the given sharded `Variable` along the given dimension. That is, `partitions[1] = 3` means split the `Variable` into 3 shards along dimension 1. Currently, sharding along only one axis is supported. If the list of variables with the given name (prefix) is already stored, we return the stored variables. Otherwise, we create a new one. Set `reuse` to `True` when you only want to reuse existing Variables. Set `reuse` to `False` when you only want to create new Variables. If `reuse` is `None` (the default), both new and existing variables are returned. If initializer is `None` (the default), the default initializer passed in the constructor is used. If that one is `None` too, we use a new `glorot_uniform_initializer`. If initializer is a Tensor, we use it as a value and derive the shape from the initializer. If the initializer is a callable, then it will be called for each shard. Otherwise the initializer should match the shape of the entire sharded Variable, and it will be sliced accordingly for each shard. Some useful partitioners are available. See, e.g., `variable_axis_size_partitioner` and `min_max_variable_partitioner`. Args: name: the name of the new or existing sharded variable. partitioner: Optional callable that accepts a fully defined `TensorShape` and `dtype` of the Variable to be created, and returns a list of partitions for each axis (currently only one axis can be partitioned). shape: shape of the new or existing sharded variable. dtype: type of the new or existing sharded variable (defaults to `DT_FLOAT`). initializer: initializer for the sharded variable. regularizer: a (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. reuse: a Boolean or `None`. Controls reuse or creation of variables. trainable: If `True` also add the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). collections: List of graph collections keys to add the Variable to. Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`). caching_device: Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements. validate_shape: If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial_value must be known. use_resource: If False, creates a regular Variable. If True, creates an experimental ResourceVariable which has well-defined semantics. Defaults to False (will later change to True). constraint: An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. Returns: A `PartitionedVariable` object. Raises: ValueError: when creating a new variable and shape is not declared, when reusing a variable and specifying a conflicting shape, when violating reuse during variable creation, or if an existing sharded variable exists for the given name but with different sharding. """ initializing_from_value = initializer is not None and isinstance( initializer, ops.Tensor) reuse_without_partition = reuse is True and partitioner is None if name in self._vars: raise ValueError( "A partitioner was provided, but an unpartitioned version of the " "variable was found: %s. Perhaps a variable of the same name was " "already created without partitioning?" % name) shape = tensor_shape.as_shape(shape) if initializing_from_value: shape = shape.merge_with(initializer.get_shape()) if not reuse_without_partition: if not shape.is_fully_defined(): raise ValueError("Shape of a new partitioned variable (%s) must be " "fully defined, but instead was %s." % (name, shape)) if shape.ndims < 1: raise ValueError("A partitioned Variable must have rank at least 1, " "shape: %s" % shape) partitions = partitioner(shape=shape, dtype=dtype) if not isinstance(partitions, collections_lib.Sequence): raise ValueError("Partitioner must return a sequence, but saw: %s" % partitions) if len(partitions) != shape.ndims: raise ValueError( "Partitioner returned a partition list that does not match the " "Variable's rank: %s vs. %s" % (partitions, shape)) if any([p < 1 for p in partitions]): raise ValueError( "Partitioner returned zero partitions for some axes: %s" % partitions) should_check = reuse is not None if name in self._partitioned_vars: if should_check and not reuse: raise ValueError( "Partitioned variable with name %s already exists. Did you mean to " "set reuse=True in VarScope?" % name) existing_var = self._partitioned_vars[name] if not shape.is_compatible_with(existing_var.get_shape()): raise ValueError( "Trying to reuse partitioned variable %s, but specified shape %s " "and found shape %s." % (name, shape, existing_var.get_shape())) if not dtype.is_compatible_with(existing_var.dtype): raise ValueError( "Trying to reuse partitioned variable %s, but specified dtype %s " "and found dtype %s." % (name, dtype.name, existing_var.dtype.name)) # pylint: disable=protected-access if (not reuse_without_partition and existing_var._get_partitions() != partitions): raise ValueError( "Trying to reuse partitioned variable %s, but specified partitions " "%s and found partitions %s." % (name, partitions, existing_var._get_partitions())) # pylint: enable=protected-access return existing_var if should_check and reuse: raise ValueError("PartitionedVariable %s does not exist, or was not " "created with tf.get_variable(). Did you mean to set " "reuse=None in VarScope?" % name) slice_dim, slice_shape = _compute_slice_dim_and_shape( shape.as_list(), partitions) vs = [] num_slices = partitions[slice_dim] num_slices_with_excess = shape[slice_dim].value % num_slices slice_offset = [0] * shape.ndims if "%s/part_0" % name in self._vars: if "%s/part_%d" % (name, num_slices - 1) not in self._vars: raise ValueError( "Partitioner returned a different partitioning than what was " "already found. Partitioner returned %d shards, and shard " "%s/part_0 was found, but %s/part_%d was not." % (num_slices, name, name, num_slices - 1)) if "%s/part_%d" % (name, num_slices) in self._vars: raise ValueError( "Partitioner returned a different partitioning than what was " "already found. Partitioner returned %d shards, and shard " "%s/part_0 was found, but so was the extra shard %s/part_%d." % (num_slices, name, name, num_slices)) for i in xrange(num_slices): var_shape = slice_shape[:] var_offset = slice_offset[:] partition_info = _PartitionInfo( full_shape=shape.as_list(), var_offset=var_offset) if i < num_slices_with_excess: var_shape[slice_dim] += 1 slice_offset[slice_dim] += var_shape[slice_dim] var_full_name = "%s/part_%d" % (name, i) with ops.name_scope(var_full_name + "/PartitionedInitializer"): # Create the tensor to initialize the variable with default value. if initializer is None: init, initializing_from_value = self._get_default_initializer( name=name, shape=shape, dtype=dtype) if initializing_from_value: init_shape = None else: init_shape = var_shape elif callable(initializer): init = initializer init_shape = var_shape elif isinstance(initializer, ops.Tensor): init = array_ops.slice(initializer, var_offset, var_shape) # Use the dtype of the given tensor. dtype = init.dtype.base_dtype init_shape = None else: init = ops.convert_to_tensor(initializer, dtype=dtype) init = array_ops.slice(init, var_offset, var_shape) init_shape = None with ops.name_scope(None): var = self._get_single_variable( name=var_full_name, shape=init_shape, dtype=dtype, initializer=init, partition_info=partition_info, regularizer=regularizer, reuse=reuse, trainable=trainable, collections=collections, caching_device=caching_device, validate_shape=validate_shape, use_resource=use_resource, constraint=constraint) # pylint: disable=protected-access var._set_save_slice_info(variables.Variable.SaveSliceInfo( name, shape.as_list(), var_offset, var_shape)) vs.append(var) # pylint: enable=protected-access # pylint: disable=protected-access partitioned_var = variables.PartitionedVariable(name=name, shape=shape, dtype=dtype, variable_list=vs, partitions=partitions) # pylint: enable=protected-access self._partitioned_vars[name] = partitioned_var return partitioned_var def _get_single_variable(self, name, shape=None, dtype=dtypes.float32, initializer=None, regularizer=None, partition_info=None, reuse=None, trainable=True, collections=None, caching_device=None, validate_shape=True, use_resource=None, constraint=None): """Get or create a single Variable (e.g. a shard or entire variable). See the documentation of get_variable above (ignore partitioning components) for details. Args: name: see get_variable. shape: see get_variable. dtype: see get_variable. initializer: see get_variable. regularizer: see get_variable. partition_info: _PartitionInfo object. reuse: see get_variable. trainable: see get_variable. collections: see get_variable. caching_device: see get_variable. validate_shape: see get_variable. use_resource: see get_variable. constraint: see get_variable. Returns: A Variable. See documentation of get_variable above. Raises: ValueError: See documentation of get_variable above. """ # Set to true if initializer is a constant. initializing_from_value = False if initializer is not None and not callable(initializer): initializing_from_value = True if shape is not None and initializing_from_value: raise ValueError("If initializer is a constant, do not specify shape.") should_check = reuse is not None dtype = dtypes.as_dtype(dtype) shape = tensor_shape.as_shape(shape) if name in self._vars: # Here we handle the case when returning an existing variable. if should_check and not reuse: tb = self._vars[name].op.traceback[::-1] # Throw away internal tf entries and only take a few lines. tb = [x for x in tb if "tensorflow/python" not in x[0]][:3] raise ValueError("Variable %s already exists, disallowed." " Did you mean to set reuse=True in VarScope? " "Originally defined at:\n\n%s" % ( name, "".join(traceback.format_list(tb)))) found_var = self._vars[name] if not shape.is_compatible_with(found_var.get_shape()): raise ValueError("Trying to share variable %s, but specified shape %s" " and found shape %s." % (name, shape, found_var.get_shape())) if not dtype.is_compatible_with(found_var.dtype): dtype_str = dtype.name found_type_str = found_var.dtype.name raise ValueError("Trying to share variable %s, but specified dtype %s" " and found dtype %s." % (name, dtype_str, found_type_str)) return found_var # The code below handles only the case of creating a new variable. if should_check and reuse: raise ValueError("Variable %s does not exist, or was not created with " "tf.get_variable(). Did you mean to set reuse=None in " "VarScope?" % name) if not shape.is_fully_defined() and not initializing_from_value: raise ValueError("Shape of a new variable (%s) must be fully defined, " "but instead was %s." % (name, shape)) # Create the tensor to initialize the variable with default value. if initializer is None: initializer, initializing_from_value = self._get_default_initializer( name=name, shape=shape, dtype=dtype) # Clear control dependencies while creating the initializer. with ops.control_dependencies(None): if initializing_from_value: init_val = initializer variable_dtype = None else: # Instantiate initializer if provided initializer is a type object. if isinstance(initializer, type(init_ops.Initializer)): initializer = initializer(dtype=dtype) init_val = lambda: initializer( # pylint: disable=g-long-lambda shape.as_list(), dtype=dtype, partition_info=partition_info) variable_dtype = dtype.base_dtype # Create the variable. if use_resource is None: # Set the default value if unspecified. use_resource = False if use_resource: v = resource_variable_ops.ResourceVariable( initial_value=init_val, name=name, trainable=trainable, collections=collections, caching_device=caching_device, dtype=variable_dtype, validate_shape=validate_shape, constraint=constraint) else: v = variables.Variable( initial_value=init_val, name=name, trainable=trainable, collections=collections, caching_device=caching_device, dtype=variable_dtype, validate_shape=validate_shape, constraint=constraint) self._vars[name] = v logging.vlog(1, "Created variable %s with shape %s and init %s", v.name, format(shape), initializer) # Run the regularizer if requested and save the resulting loss. if regularizer: with ops.colocate_with(v.op): with ops.name_scope(name + "/Regularizer/"): loss = regularizer(v) if loss is not None: logging.vlog(1, "Applied regularizer to %s and added the result %s " "to REGULARIZATION_LOSSES.", v.name, loss.name) ops.add_to_collection(ops.GraphKeys.REGULARIZATION_LOSSES, loss) return v # Initialize variable when no initializer provided def _get_default_initializer(self, name, shape=None, dtype=dtypes.float32): """Provide a default initializer and a corresponding value. Args: name: see get_variable. shape: see get_variable. dtype: see get_variable. Returns: initializer and initializing_from_value. See get_variable above. Raises: ValueError: When giving unsupported dtype. """ # If dtype is DT_FLOAT, provide a uniform unit scaling initializer if dtype.is_floating: initializer = init_ops.glorot_uniform_initializer() initializing_from_value = False # If dtype is DT_INT/DT_UINT, provide a default value `zero` # If dtype is DT_BOOL, provide a default value `FALSE` elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool: initializer = init_ops.zeros_initializer()( shape=shape, dtype=dtype.base_dtype) initializing_from_value = True # NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here? else: raise ValueError("An initializer for variable %s of %s is required" % (name, dtype.base_dtype)) return initializer, initializing_from_value # To stop regularization, use this regularizer def no_regularizer(_): """Use this function to prevent regularization of variables.""" return None class VariableScope(object): """Variable scope object to carry defaults to provide to `get_variable`. Many of the arguments we need for `get_variable` in a variable store are most easily handled with a context. This object is used for the defaults. Attributes: name: name of the current scope, used as prefix in get_variable. initializer: default initializer passed to get_variable. regularizer: default regularizer passed to get_variable. reuse: Boolean or None, setting the reuse in get_variable. caching_device: string, callable, or None: the caching device passed to get_variable. partitioner: callable or `None`: the partitioner passed to `get_variable`. custom_getter: default custom getter passed to get_variable. name_scope: The name passed to `tf.name_scope`. dtype: default type passed to get_variable (defaults to DT_FLOAT). use_resource: if False, create a normal Variable; if True create an experimental ResourceVariable with well-defined semantics. Defaults to False (will later change to True). constraint: An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. """ def __init__(self, reuse, name="", initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, name_scope="", dtype=dtypes.float32, use_resource=None, constraint=None): """Creates a new VariableScope with the given properties.""" self._name = name self._initializer = initializer self._regularizer = regularizer self._reuse = reuse self._caching_device = caching_device self._partitioner = partitioner self._custom_getter = custom_getter self._name_scope = name_scope self._dtype = dtype self._use_resource = use_resource self._constraint = constraint @property def name(self): return self._name @property def original_name_scope(self): return self._name_scope @property def reuse(self): return self._reuse @property def initializer(self): return self._initializer @property def dtype(self): return self._dtype @property def use_resource(self): return self._use_resource @property def regularizer(self): return self._regularizer @property def caching_device(self): return self._caching_device @property def partitioner(self): return self._partitioner @property def custom_getter(self): return self._custom_getter @property def constraint(self): return self._constraint def reuse_variables(self): """Reuse variables in this scope.""" self._reuse = True def set_initializer(self, initializer): """Set initializer for this scope.""" self._initializer = initializer def set_dtype(self, dtype): """Set data type for this scope.""" self._dtype = dtype def set_use_resource(self, use_resource): """Sets whether to use ResourceVariables for this scope.""" self._use_resource = use_resource def set_regularizer(self, regularizer): """Set regularizer for this scope.""" self._regularizer = regularizer def set_caching_device(self, caching_device): """Set caching_device for this scope.""" self._caching_device = caching_device def set_partitioner(self, partitioner): """Set partitioner for this scope.""" self._partitioner = partitioner def set_custom_getter(self, custom_getter): """Set custom getter for this scope.""" self._custom_getter = custom_getter def get_collection(self, name): """Get this scope's variables.""" scope = self._name + "/" if self._name else "" return ops.get_collection(name, scope) def trainable_variables(self): """Get this scope's trainable variables.""" return self.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) def global_variables(self): """Get this scope's global variables.""" return self.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) def get_variable(self, var_store, name, shape=None, dtype=None, initializer=None, regularizer=None, reuse=None, trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, custom_getter=None, constraint=None): """Gets an existing variable with this name or create a new one.""" if regularizer is None: regularizer = self._regularizer if caching_device is None: caching_device = self._caching_device if partitioner is None: partitioner = self._partitioner if custom_getter is None: custom_getter = self._custom_getter if reuse is None: reuse = self._reuse full_name = self.name + "/" + name if self.name else name # Variable names only depend on variable_scope (full_name here), # not name_scope, so we reset it below for the time of variable creation. with ops.name_scope(None): # Check that `initializer` dtype and `dtype` are consistent before # replacing them with defaults. if (dtype is not None and initializer is not None and not callable(initializer)): init_dtype = ops.convert_to_tensor(initializer).dtype.base_dtype if init_dtype != dtype: raise ValueError("Initializer type '%s' and explicit dtype '%s' " "don't match." % (init_dtype, dtype)) if initializer is None: initializer = self._initializer if constraint is None: constraint = self._constraint if dtype is None: dtype = self._dtype if use_resource is None: use_resource = self._use_resource return var_store.get_variable( full_name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, reuse=reuse, trainable=trainable, collections=collections, caching_device=caching_device, partitioner=partitioner, validate_shape=validate_shape, use_resource=use_resource, custom_getter=custom_getter, constraint=constraint) def _get_partitioned_variable(self, var_store, name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, constraint=None): """Gets an existing variable with this name or create a new one.""" if initializer is None: initializer = self._initializer if regularizer is None: regularizer = self._regularizer if constraint is None: constraint = self._constraint if caching_device is None: caching_device = self._caching_device if partitioner is None: partitioner = self._partitioner if dtype is None: dtype = self._dtype if use_resource is None: use_resource = self._use_resource if self._custom_getter is not None: raise ValueError( "Private access to _get_partitioned_variable is not allowed when " "a custom getter is set. Current custom getter: %s. " "It is likely that you're using create_partitioned_variables. " "If so, consider instead using get_variable with a non-empty " "partitioner parameter instead." % self._custom_getter) if partitioner is None: raise ValueError("No partitioner was specified") # This allows the variable scope name to be used as the variable name if # this function is invoked with an empty name arg, for backward # compatibility with create_partitioned_variables(). full_name_list = [] if self.name: full_name_list.append(self.name) if name: full_name_list.append(name) full_name = "/".join(full_name_list) # Variable names only depend on variable_scope (full_name here), # not name_scope, so we reset it below for the time of variable creation. with ops.name_scope(None): # pylint: disable=protected-access return var_store._get_partitioned_variable( full_name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, reuse=self.reuse, trainable=trainable, collections=collections, caching_device=caching_device, partitioner=partitioner, validate_shape=validate_shape, use_resource=use_resource, constraint=constraint) # pylint: enable=protected-access _VARSTORE_KEY = ("__variable_store",) _VARSCOPE_KEY = ("__varscope",) def get_variable_scope(): """Returns the current variable scope.""" scope = ops.get_collection(_VARSCOPE_KEY) if scope: # This collection has at most 1 element, the default scope at [0]. return scope[0] scope = VariableScope(False) ops.add_to_collection(_VARSCOPE_KEY, scope) return scope def _get_default_variable_store(): store = ops.get_collection(_VARSTORE_KEY) if store: return store[0] store = _VariableStore() ops.add_to_collection(_VARSTORE_KEY, store) return store def get_variable(name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, custom_getter=None, constraint=None): return get_variable_scope().get_variable( _get_default_variable_store(), name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, trainable=trainable, collections=collections, caching_device=caching_device, partitioner=partitioner, validate_shape=validate_shape, use_resource=use_resource, custom_getter=custom_getter, constraint=constraint) get_variable_or_local_docstring = ( """%s %sThis function prefixes the name with the current variable scope and performs reuse checks. See the @{$variables$Variable Scope How To} for an extensive description of how reusing works. Here is a basic example: ```python with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) # v.name == "foo/v:0" w = tf.get_variable("w", [1]) # w.name == "foo/w:0" with tf.variable_scope("foo", reuse=True): v1 = tf.get_variable("v") # The same as v above. ``` If initializer is `None` (the default), the default initializer passed in the variable scope will be used. If that one is `None` too, a `glorot_uniform_initializer` will be used. The initializer can also be a Tensor, in which case the variable is initialized to this value and shape. Similarly, if the regularizer is `None` (the default), the default regularizer passed in the variable scope will be used (if that is `None` too, then by default no regularization is performed). If a partitioner is provided, a `PartitionedVariable` is returned. Accessing this object as a `Tensor` returns the shards concatenated along the partition axis. Some useful partitioners are available. See, e.g., `variable_axis_size_partitioner` and `min_max_variable_partitioner`. Args: name: The name of the new or existing variable. shape: Shape of the new or existing variable. dtype: Type of the new or existing variable (defaults to `DT_FLOAT`). initializer: Initializer for the variable if one is created. regularizer: A (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection @{tf.GraphKeys.REGULARIZATION_LOSSES} and can be used for regularization. %scollections: List of graph collections keys to add the Variable to. Defaults to `[%s]` (see `tf.Variable`). caching_device: Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements. partitioner: Optional callable that accepts a fully defined `TensorShape` and `dtype` of the Variable to be created, and returns a list of partitions for each axis (currently only one axis can be partitioned). validate_shape: If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial_value must be known. use_resource: If False, creates a regular Variable. If true, creates an experimental ResourceVariable instead with well-defined semantics. Defaults to False (will later change to True). custom_getter: Callable that takes as a first argument the true getter, and allows overwriting the internal get_variable method. The signature of `custom_getter` should match that of this method, but the most future-proof version will allow for changes: `def custom_getter(getter, *args, **kwargs)`. Direct access to all `get_variable` parameters is also allowed: `def custom_getter(getter, name, *args, **kwargs)`. A simple identity custom getter that simply creates variables with modified names is: ```python def custom_getter(getter, name, *args, **kwargs): return getter(name + '_suffix', *args, **kwargs) ``` Returns: The created or existing `Variable` (or `PartitionedVariable`, if a partitioner was used). Raises: ValueError: when creating a new variable and shape is not declared, when violating reuse during variable creation, or when `initializer` dtype and `dtype` don't match. Reuse is set inside `variable_scope`. """) get_variable.__doc__ = get_variable_or_local_docstring % ( "Gets an existing variable with these parameters or create a new one.", "", "trainable: If `True` also add the variable to the graph collection\n" " `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n ", "GraphKeys.GLOBAL_VARIABLES") @functools.wraps(get_variable) def get_local_variable(*args, **kwargs): kwargs["trainable"] = False if "collections" in kwargs: kwargs["collections"] += [ops.GraphKeys.LOCAL_VARIABLES] else: kwargs["collections"] = [ops.GraphKeys.LOCAL_VARIABLES] return get_variable(*args, **kwargs) get_local_variable.__doc__ = get_variable_or_local_docstring % ( "Gets an existing *local* variable or creates a new one.", "Behavior is the same as in `get_variable`, except that variables are\n" "added to the `LOCAL_VARIABLES` collection and `trainable` is set to\n" "`False`.\n", "", "GraphKeys.LOCAL_VARIABLES") def _get_partitioned_variable(name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, constraint=None): """Gets or creates a sharded variable list with these parameters. The `partitioner` must be a callable that accepts a fully defined `TensorShape` and returns a sequence of integers (the `partitions`). These integers describe how to partition the given sharded `Variable` along the given dimension. That is, `partitions[1] = 3` means split the `Variable` into 3 shards along dimension 1. Currently, sharding along only one axis is supported. If the list of variables with the given name (prefix) is already stored, we return the stored variables. Otherwise, we create a new one. Set `reuse` to `True` when you only want to reuse existing Variables. Set `reuse` to `False` when you only want to create new Variables. If `reuse` is `None` (the default), both new and existing variables are returned. If initializer is `None` (the default), the default initializer passed in the constructor is used. If that one is `None` too, we use a new `glorot_uniform_initializer`. If initializer is a Tensor, we use it as a value and derive the shape from the initializer. If the initializer is a callable, then it will be called for each shard. Otherwise the initializer should match the shape of the entire sharded Variable, and it will be sliced accordingly for each shard. Some useful partitioners are available. See, e.g., `variable_axis_size_partitioner` and `min_max_variable_partitioner`. Args: name: The name of the new or existing variable. shape: Shape of the new or existing variable. dtype: Type of the new or existing variable (defaults to `DT_FLOAT`). initializer: Initializer for the variable if one is created. regularizer: A (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. trainable: If `True` also add the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). collections: List of graph collections keys to add the Variable to. Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`). caching_device: Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements. partitioner: Optional callable that accepts a fully defined `TensorShape` and `dtype` of the Variable to be created, and returns a list of partitions for each axis (currently only one axis can be partitioned). validate_shape: If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial_value must be known. use_resource: If False, creates a regular Variable. If True, creates an experimental ResourceVariable instead which has well-defined semantics. Defaults to False (will later change to True). constraint: An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. Returns: A tuple `(shards, partitions)` where `shards` is the list of `Variable` shards and `partitions` is the output of the partitioner on the input shape. Raises: ValueError: when creating a new variable and shape is not declared, or when violating reuse during variable creation. Reuse is set inside `variable_scope`. """ # pylint: disable=protected-access scope = get_variable_scope() if scope.custom_getter is not None: raise ValueError( "Private access to _get_partitioned_variable is not allowed when " "a custom getter is set. Current custom getter: %s. " "It is likely that you're using create_partitioned_variables. " "If so, consider instead using get_variable with a non-empty " "partitioner parameter instead." % scope.custom_getter) return scope._get_partitioned_variable( _get_default_variable_store(), name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, trainable=trainable, collections=collections, caching_device=caching_device, partitioner=partitioner, validate_shape=validate_shape, use_resource=use_resource, constraint=constraint) # pylint: enable=protected-access @tf_contextlib.contextmanager def _pure_variable_scope(name_or_scope, reuse=None, initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, old_name_scope=None, dtype=dtypes.float32, use_resource=None, constraint=None): """Creates a context for the variable_scope, see `variable_scope` for docs. Note: this does not create a name scope. Args: name_or_scope: `string` or `VariableScope`: the scope to open. reuse: `True` or `None`; if `True`, we go into reuse mode for this scope as well as all sub-scopes; if `None`, we just inherit the parent scope reuse. initializer: default initializer for variables within this scope. regularizer: default regularizer for variables within this scope. caching_device: default caching device for variables within this scope. partitioner: default partitioner for variables within this scope. custom_getter: default custom getter for variables within this scope. old_name_scope: the original name scope when re-entering a variable scope. dtype: type of the variables within this scope (defaults to `DT_FLOAT`). use_resource: If False, variables in this scope will be regular Variables. If True, experimental ResourceVariables will be creates instead, with well-defined semantics. Defaults to False (will later change to True). constraint: An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. Yields: A scope that can be captured and reused. Raises: ValueError: when trying to reuse within a create scope, or create within a reuse scope, or if reuse is not `None` or `True`. TypeError: when the types of some arguments are not appropriate. """ get_variable_scope() # Ensure that a default exists, then get a pointer. # Get the reference to the collection as we want to modify it in place. default_varscope = ops.get_collection_ref(_VARSCOPE_KEY) old = default_varscope[0] var_store = _get_default_variable_store() if isinstance(name_or_scope, VariableScope): new_name = name_or_scope.name else: new_name = old.name + "/" + name_or_scope if old.name else name_or_scope try: var_store.open_variable_scope(new_name) if isinstance(name_or_scope, VariableScope): old_subscopes = copy.copy(var_store.variable_scopes_count) name_scope = name_or_scope._name_scope # pylint: disable=protected-access # Handler for the case when we jump to a shared scope. # We create a new VariableScope (default_varscope[0]) that contains # a copy of the provided shared scope, possibly with changed reuse # and initializer, if the user requested this. default_varscope[0] = VariableScope( name_or_scope.reuse if reuse is None else reuse, name=new_name, initializer=name_or_scope.initializer, regularizer=name_or_scope.regularizer, caching_device=name_or_scope.caching_device, partitioner=name_or_scope.partitioner, dtype=name_or_scope.dtype, custom_getter=name_or_scope.custom_getter, name_scope=name_scope, use_resource=name_or_scope.use_resource, constraint=constraint) if initializer is not None: default_varscope[0].set_initializer(initializer) if regularizer is not None: default_varscope[0].set_regularizer(regularizer) if caching_device is not None: default_varscope[0].set_caching_device(caching_device) if partitioner is not None: default_varscope[0].set_partitioner(partitioner) if custom_getter is not None: default_varscope[0].set_custom_getter( _maybe_wrap_custom_getter( custom_getter, name_or_scope.custom_getter)) if dtype is not None: default_varscope[0].set_dtype(dtype) if use_resource is not None: default_varscope[0].set_use_resource(use_resource) yield default_varscope[0] else: # Handler for the case when we just prolong current variable scope. # VariableScope with name extended by the provided one, and inherited # reuse and initializer (except if the user provided values to set). reuse = reuse or old.reuse # Re-using is inherited by sub-scopes. default_varscope[0] = VariableScope( reuse, name=new_name, initializer=old.initializer, regularizer=old.regularizer, caching_device=old.caching_device, partitioner=old.partitioner, dtype=old.dtype, use_resource=old.use_resource, custom_getter=old.custom_getter, name_scope=old_name_scope or name_or_scope, constraint=constraint) if initializer is not None: default_varscope[0].set_initializer(initializer) if regularizer is not None: default_varscope[0].set_regularizer(regularizer) if caching_device is not None: default_varscope[0].set_caching_device(caching_device) if partitioner is not None: default_varscope[0].set_partitioner(partitioner) if custom_getter is not None: default_varscope[0].set_custom_getter( _maybe_wrap_custom_getter(custom_getter, old.custom_getter)) if dtype is not None: default_varscope[0].set_dtype(dtype) if use_resource is not None: default_varscope[0].set_use_resource(use_resource) yield default_varscope[0] finally: var_store.close_variable_subscopes(new_name) # If jumping out from a non-prolonged scope, restore counts. if isinstance(name_or_scope, VariableScope): var_store.variable_scopes_count = old_subscopes default_varscope[0] = old def _maybe_wrap_custom_getter(custom_getter, old_getter): """Wrap a call to a custom_getter to use the old_getter internally.""" if old_getter is None: return custom_getter # The new custom_getter should call the old one def wrapped_custom_getter(getter, *args, **kwargs): # Call: # custom_getter( # lambda: old_getter(true_getter, ...), *args, **kwargs) # which means custom_getter will call old_getter, which # will call the true_getter, perform any intermediate # processing, and return the results to the current # getter, which will also perform additional processing. return custom_getter( functools.partial(old_getter, getter), *args, **kwargs) return wrapped_custom_getter def _get_unique_variable_scope(prefix): """Get a name with the given prefix unique in the current variable scope.""" var_store = _get_default_variable_store() current_scope = get_variable_scope() name = current_scope.name + "/" + prefix if current_scope.name else prefix if var_store.variable_scope_count(name) == 0: return prefix idx = 1 while var_store.variable_scope_count(name + ("_%d" % idx)) > 0: idx += 1 return prefix + ("_%d" % idx) # pylint: disable=g-doc-return-or-yield @tf_contextlib.contextmanager def variable_scope(name_or_scope, default_name=None, values=None, initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, reuse=None, dtype=None, use_resource=None, constraint=None): """Returns a context manager for defining ops that creates variables (layers). This context manager validates that the (optional) `values` are from the same graph, ensures that graph is the default graph, and pushes a name scope and a variable scope. If `name_or_scope` is not None, it is used as is. If `scope` is None, then `default_name` is used. In that case, if the same name has been previously used in the same scope, it will made unique be appending `_N` to it. Variable scope allows to create new variables and to share already created ones while providing checks to not create or share by accident. For details, see the @{$variables$Variable Scope How To}, here we present only a few basic examples. Simple example of how to create a new variable: ```python with tf.variable_scope("foo"): with tf.variable_scope("bar"): v = tf.get_variable("v", [1]) assert v.name == "foo/bar/v:0" ``` Basic example of sharing a variable: ```python with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) with tf.variable_scope("foo", reuse=True): v1 = tf.get_variable("v", [1]) assert v1 == v ``` Sharing a variable by capturing a scope and setting reuse: ```python with tf.variable_scope("foo") as scope: v = tf.get_variable("v", [1]) scope.reuse_variables() v1 = tf.get_variable("v", [1]) assert v1 == v ``` To prevent accidental sharing of variables, we raise an exception when getting an existing variable in a non-reusing scope. ```python with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) v1 = tf.get_variable("v", [1]) # Raises ValueError("... v already exists ..."). ``` Similarly, we raise an exception when trying to get a variable that does not exist in reuse mode. ```python with tf.variable_scope("foo", reuse=True): v = tf.get_variable("v", [1]) # Raises ValueError("... v does not exists ..."). ``` Note that the `reuse` flag is inherited: if we open a reusing scope, then all its sub-scopes become reusing as well. A note about name scoping: Setting `reuse` does not impact the naming of other ops such as mult. See related discussion on [github#6189](https://github.com/tensorflow/tensorflow/issues/6189) Note that up to and including version 1.0, it was allowed (though explicitly discouraged) to pass False to the reuse argument, yielding undocumented behaviour slightly different from None. Starting at 1.1.0 passing None and False as reuse has exactly the same effect. Args: name_or_scope: `string` or `VariableScope`: the scope to open. default_name: The default name to use if the `name_or_scope` argument is `None`, this name will be uniquified. If name_or_scope is provided it won't be used and therefore it is not required and can be None. values: The list of `Tensor` arguments that are passed to the op function. initializer: default initializer for variables within this scope. regularizer: default regularizer for variables within this scope. caching_device: default caching device for variables within this scope. partitioner: default partitioner for variables within this scope. custom_getter: default custom getter for variables within this scope. reuse: `True` or `None`; if `True`, we go into reuse mode for this scope as well as all sub-scopes; if `None`, we just inherit the parent scope reuse. dtype: type of variables created in this scope (defaults to the type in the passed scope, or inherited from parent scope). use_resource: If False, all variables will be regular Variables. If True, experimental ResourceVariables with well-defined semantics will be used instead. Defaults to False (will later change to True). constraint: An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. Returns: A scope that can be to captured and reused. Raises: ValueError: when trying to reuse within a create scope, or create within a reuse scope. TypeError: when the types of some arguments are not appropriate. """ if default_name is None and name_or_scope is None: raise TypeError("If default_name is None then name_or_scope is required") if not (reuse is True or reuse is False or reuse is None): raise ValueError("The reuse parameter must be True or False or None.") if reuse is False: # We don't allow non-inheriting scopes, False = None here. reuse = None if values is None: values = [] g = ops._get_graph_from_inputs(values) # pylint: disable=protected-access with g.as_default(): if name_or_scope is not None: if not isinstance(name_or_scope, (VariableScope,) + six.string_types): raise TypeError("VariableScope: name_or_scope must be a string or " "VariableScope.") if isinstance(name_or_scope, six.string_types): name_scope = name_or_scope else: name_scope = name_or_scope.name.split("/")[-1] if name_scope: with ops.name_scope(name_scope) as cur_name_scope: if isinstance(name_or_scope, six.string_types): old_name_scope = cur_name_scope else: old_name_scope = name_or_scope.original_name_scope with _pure_variable_scope( name_or_scope, reuse=reuse, initializer=initializer, regularizer=regularizer, caching_device=caching_device, partitioner=partitioner, custom_getter=custom_getter, old_name_scope=old_name_scope, dtype=dtype, use_resource=use_resource, constraint=constraint) as vs: yield vs else: # This can only happen if someone is entering the root variable scope. with _pure_variable_scope( name_or_scope, reuse=reuse, initializer=initializer, regularizer=regularizer, caching_device=caching_device, partitioner=partitioner, custom_getter=custom_getter, dtype=dtype, use_resource=use_resource, constraint=constraint) as vs: yield vs else: # Here name_or_scope is None. Using default name, but made unique. if reuse: raise ValueError("reuse=True cannot be used without a name_or_scope") with ops.name_scope(default_name) as scope: unique_default_name = _get_unique_variable_scope(default_name) with _pure_variable_scope( unique_default_name, initializer=initializer, regularizer=regularizer, caching_device=caching_device, partitioner=partitioner, custom_getter=custom_getter, old_name_scope=scope, dtype=dtype, use_resource=use_resource, constraint=constraint) as vs: yield vs # pylint: disable=g-doc-return-or-yield @tf_contextlib.contextmanager def variable_op_scope(values, name_or_scope, default_name=None, initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, reuse=None, dtype=None, use_resource=None, constraint=None): """Deprecated: context manager for defining an op that creates variables.""" logging.warn("tf.variable_op_scope(values, name, default_name) is deprecated," " use tf.variable_scope(name, default_name, values)") with variable_scope(name_or_scope, default_name=default_name, values=values, initializer=initializer, regularizer=regularizer, caching_device=caching_device, partitioner=partitioner, custom_getter=custom_getter, reuse=reuse, dtype=dtype, use_resource=use_resource, constraint=constraint) as scope: yield scope def _compute_slice_dim_and_shape(full_shape, slicing): """Computes which dimension is being sliced and the typical slice shape.""" slice_shape = [0] * len(full_shape) slice_dim = None for dim, num_slices in enumerate(slicing): dim_size = full_shape[dim] if num_slices <= 0 or dim_size < num_slices: raise ValueError("Cannot create %d slices for size %d. shape: %s, " "slicing: %s" % (num_slices, full_shape[dim], full_shape, slicing)) if num_slices == 1: # Not slicing in this dimension. slice_shape[dim] = dim_size elif slice_dim is not None: # We only support slicing along one of the dimensions. raise ValueError("Can only slice a variable along one dimension: " "shape: %s, slicing: %s" % (full_shape, slicing)) else: # Note: We will add any extras onto the last slice, later. slice_dim = dim slice_shape[dim] = dim_size // num_slices # Degenerate case: If "slicing" was all ones, pretend we are slicing along # the first dimension. if slice_dim is None: slice_dim = 0 return slice_dim, slice_shape def variable(initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, dtype=None): if get_variable_scope().use_resource: return resource_variable_ops.ResourceVariable( initial_value=initial_value, trainable=trainable, collections=collections, validate_shape=validate_shape, caching_device=caching_device, name=name, dtype=dtype) else: return variables.Variable( initial_value=initial_value, trainable=trainable, collections=collections, validate_shape=validate_shape, caching_device=caching_device, name=name, dtype=dtype)
apache-2.0
18,105,685,319,570,604
41.914834
113
0.643741
false
mastizada/kuma
vendor/packages/nose/functional_tests/test_collector.py
10
1333
import os import sys import unittest import warnings from cStringIO import StringIO from nose.result import _TextTestResult here = os.path.dirname(__file__) support = os.path.join(here, 'support') class TestRunner(unittest.TextTestRunner): def _makeResult(self): self.result = _TextTestResult( self.stream, self.descriptions, self.verbosity) return self.result class TestNoseTestCollector(unittest.TestCase): def test_skip_works_with_collector(self): verbosity = 2 stream = StringIO() runner = TestRunner(stream=stream, verbosity=verbosity) pwd = os.getcwd() # we don't need to see our own warnings warnings.filterwarnings(action='ignore', category=RuntimeWarning, module='nose.plugins.manager') try: os.chdir(os.path.join(support, 'issue038')) unittest.TestProgram( None, None, argv=['test_collector', '-v', 'nose.collector'], testRunner=runner) except SystemExit: pass os.chdir(pwd) out = stream.getvalue() assert runner.result.wasSuccessful() assert 'SKIP' in out, "SKIP not found in %s" % out if __name__ == '__main__': unittest.main()
mpl-2.0
-7,553,539,612,129,511,000
27.978261
64
0.596399
false
bsipocz/bokeh
examples/glyphs/maps.py
31
2533
from __future__ import print_function from bokeh.browserlib import view from bokeh.document import Document from bokeh.embed import file_html from bokeh.models.glyphs import Circle from bokeh.models import ( GMapPlot, Range1d, ColumnDataSource, LinearAxis, PanTool, WheelZoomTool, BoxSelectTool, BoxSelectionOverlay, GMapOptions, NumeralTickFormatter, PrintfTickFormatter) from bokeh.resources import INLINE x_range = Range1d() y_range = Range1d() # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=13, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title = "Austin" ) source = ColumnDataSource( data=dict( lat=[30.2861, 30.2855, 30.2869], lon=[-97.7394, -97.7390, -97.7405], fill=['orange', 'blue', 'green'] ) ) circle = Circle(x="lon", y="lat", size=15, fill_color="fill", line_color="black") plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() plot.add_tools(pan, wheel_zoom, box_select) xaxis = LinearAxis(axis_label="lat", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="lon", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) plot.add_layout(yaxis, 'left') overlay = BoxSelectionOverlay(tool=box_select) plot.add_layout(overlay) doc = Document() doc.add(plot) if __name__ == "__main__": filename = "maps.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Google Maps Example")) print("Wrote %s" % filename) view(filename)
bsd-3-clause
4,539,470,508,957,857,300
39.206349
797
0.683774
false
utkarsh-goswami/erpnext
erpnext/projects/doctype/timesheet/test_timesheet.py
13
5355
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest import datetime from frappe.utils.make_random import get_random from frappe.utils import now_datetime, nowdate, add_days, add_months from erpnext.projects.doctype.timesheet.timesheet import OverlapError from erpnext.projects.doctype.timesheet.timesheet import make_salary_slip, make_sales_invoice from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice class TestTimesheet(unittest.TestCase): def test_timesheet_billing_amount(self): salary_structure = make_salary_structure("_T-Employee-0001") timesheet = make_timesheet("_T-Employee-0001", simulate = True, billable=1) self.assertEquals(timesheet.total_hours, 2) self.assertEquals(timesheet.total_billable_hours, 2) self.assertEquals(timesheet.time_logs[0].billing_rate, 50) self.assertEquals(timesheet.time_logs[0].billing_amount, 100) self.assertEquals(timesheet.total_billable_amount, 100) def test_salary_slip_from_timesheet(self): salary_structure = make_salary_structure("_T-Employee-0001") timesheet = make_timesheet("_T-Employee-0001", simulate = True, billable=1) salary_slip = make_salary_slip(timesheet.name) salary_slip.submit() self.assertEquals(salary_slip.total_working_hours, 2) self.assertEquals(salary_slip.hour_rate, 50) self.assertEquals(salary_slip.net_pay, 150) self.assertEquals(salary_slip.timesheets[0].time_sheet, timesheet.name) self.assertEquals(salary_slip.timesheets[0].working_hours, 2) timesheet = frappe.get_doc('Timesheet', timesheet.name) self.assertEquals(timesheet.status, 'Payslip') salary_slip.cancel() timesheet = frappe.get_doc('Timesheet', timesheet.name) self.assertEquals(timesheet.status, 'Submitted') def test_sales_invoice_from_timesheet(self): timesheet = make_timesheet("_T-Employee-0001", simulate = True, billable = 1) sales_invoice = make_sales_invoice(timesheet.name) sales_invoice.customer = "_Test Customer" sales_invoice.due_date = nowdate() item = sales_invoice.append('items', {}) item.item_code = '_Test Item' item.qty = 2 item.rate = 100 sales_invoice.submit() timesheet = frappe.get_doc('Timesheet', timesheet.name) self.assertEquals(sales_invoice.total_billing_amount, 100) self.assertEquals(timesheet.status, 'Billed') def test_timesheet_billing_based_on_project(self): timesheet = make_timesheet("_T-Employee-0001", simulate=True, billable=1, project = '_Test Project', company='_Test Company') sales_invoice = create_sales_invoice(do_not_save=True) sales_invoice.project = '_Test Project' sales_invoice.submit() ts = frappe.get_doc('Timesheet', timesheet.name) self.assertEquals(ts.per_billed, 100) self.assertEquals(ts.time_logs[0].sales_invoice, sales_invoice.name) def make_salary_structure(employee): name = frappe.db.get_value('Salary Structure Employee', {'employee': employee}, 'parent') if name: salary_structure = frappe.get_doc('Salary Structure', name) else: salary_structure = frappe.new_doc("Salary Structure") salary_structure.name = "Timesheet Salary Structure Test" salary_structure.salary_slip_based_on_timesheet = 1 salary_structure.from_date = add_days(nowdate(), -30) salary_structure.salary_component = "Basic" salary_structure.hour_rate = 50.0 salary_structure.company = "_Test Company" salary_structure.payment_account = get_random("Account") salary_structure.set('employees', []) salary_structure.set('earnings', []) salary_structure.set('deductions', []) es = salary_structure.append('employees', { "employee": employee, "base": 1200, "from_date": add_months(nowdate(),-1) }) es = salary_structure.append('earnings', { "salary_component": "_Test Allowance", "amount": 100 }) ds = salary_structure.append('deductions', { "salary_component": "_Test Professional Tax", "amount": 50 }) salary_structure.save(ignore_permissions=True) return salary_structure def make_timesheet(employee, simulate=False, billable = 0, activity_type="_Test Activity Type", project=None, task=None, company=None): update_activity_type(activity_type) timesheet = frappe.new_doc("Timesheet") timesheet.employee = employee timesheet_detail = timesheet.append('time_logs', {}) timesheet_detail.billable = billable timesheet_detail.activity_type = activity_type timesheet_detail.from_time = now_datetime() timesheet_detail.hours = 2 timesheet_detail.to_time = timesheet_detail.from_time + datetime.timedelta(hours= timesheet_detail.hours) timesheet_detail.project = project timesheet_detail.task = task timesheet_detail.company = company or '_Test Company' for data in timesheet.get('time_logs'): if simulate: while True: try: timesheet.save(ignore_permissions=True) break except OverlapError: data.from_time = data.from_time + datetime.timedelta(minutes=10) data.to_time = data.from_time + datetime.timedelta(hours= data.hours) else: timesheet.save(ignore_permissions=True) timesheet.submit() return timesheet def update_activity_type(activity_type): activity_type = frappe.get_doc('Activity Type',activity_type) activity_type.billing_rate = 50.0 activity_type.save(ignore_permissions=True)
gpl-3.0
-9,052,740,640,349,281,000
36.447552
135
0.743231
false
Alpistinho/FreeCAD
src/Mod/Import/App/config_control_design.py
56
401336
# This file was generated by fedex_python. You probably don't want to edit # it since your modifications will be lost if fedex_plus is used to # regenerate it. import sys from SCL.SCLBase import * from SCL.SimpleDataTypes import * from SCL.ConstructedDataTypes import * from SCL.AggregationDataTypes import * from SCL.TypeChecker import check_type from SCL.Builtin import * from SCL.Rules import * schema_name = 'config_control_design' schema_scope = sys.modules[__name__] # SELECT TYPE characterized_definition characterized_definition = SELECT( 'characterized_product_definition', 'shape_definition', scope = schema_scope) # Defined datatype parameter_value class parameter_value(REAL): def __init__(self,*kargs): pass # Defined datatype plane_angle_measure class plane_angle_measure(REAL): def __init__(self,*kargs): pass # SELECT TYPE change_request_item change_request_item = SELECT( 'product_definition_formation', scope = schema_scope) # Defined datatype text class text(STRING): def __init__(self,*kargs): pass # Defined datatype year_number class year_number(INTEGER): def __init__(self,*kargs): pass # SELECT TYPE characterized_product_definition characterized_product_definition = SELECT( 'product_definition', 'product_definition_relationship', scope = schema_scope) # SELECT TYPE reversible_topology_item reversible_topology_item = SELECT( 'edge', 'path', 'face', 'face_bound', 'closed_shell', 'open_shell', scope = schema_scope) # SELECT TYPE axis2_placement axis2_placement = SELECT( 'axis2_placement_2d', 'axis2_placement_3d', scope = schema_scope) set_of_reversible_topology_item = SET(0,None,'reversible_topology_item', scope = schema_scope) # Defined datatype week_in_year_number class week_in_year_number(INTEGER): def __init__(self,*kargs): pass self.wr1() def wr1(self): eval_wr1_wr = ((1 <= self) and (self <= 53)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr # Defined datatype knot_type class knot_type(ENUMERATION): def __init__(self,*kargs): pass # SELECT TYPE specified_item specified_item = SELECT( 'product_definition', 'shape_aspect', scope = schema_scope) # Defined datatype minute_in_hour class minute_in_hour(INTEGER): def __init__(self,*kargs): pass self.wr1() def wr1(self): eval_wr1_wr = ((0 <= self) and (self <= 59)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr # Defined datatype transition_code class transition_code(ENUMERATION): def __init__(self,*kargs): pass # Defined datatype identifier class identifier(STRING): def __init__(self,*kargs): pass # SELECT TYPE measure_value measure_value = SELECT( 'length_measure', 'mass_measure', 'plane_angle_measure', 'solid_angle_measure', 'area_measure', 'volume_measure', 'parameter_value', 'context_dependent_measure', 'descriptive_measure', 'positive_length_measure', 'positive_plane_angle_measure', 'count_measure', scope = schema_scope) # SELECT TYPE person_organization_select person_organization_select = SELECT( 'person', 'organization', 'person_and_organization', scope = schema_scope) # Defined datatype preferred_surface_curve_representation class preferred_surface_curve_representation(ENUMERATION): def __init__(self,*kargs): pass # Defined datatype dimension_count class dimension_count(INTEGER): def __init__(self,*kargs): pass self.wr1() def wr1(self): eval_wr1_wr = (self > 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr # SELECT TYPE pcurve_or_surface pcurve_or_surface = SELECT( 'pcurve', 'surface', scope = schema_scope) # Defined datatype length_measure class length_measure(REAL): def __init__(self,*kargs): pass # Defined datatype positive_length_measure class positive_length_measure(length_measure): def __init__(self,*kargs): pass self.wr1() def wr1(self): eval_wr1_wr = (self > 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr # Defined datatype b_spline_curve_form class b_spline_curve_form(ENUMERATION): def __init__(self,*kargs): pass # Defined datatype hour_in_day class hour_in_day(INTEGER): def __init__(self,*kargs): pass self.wr1() def wr1(self): eval_wr1_wr = ((0 <= self) and (self < 24)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr # SELECT TYPE classified_item classified_item = SELECT( 'product_definition_formation', 'assembly_component_usage', scope = schema_scope) # Defined datatype si_unit_name class si_unit_name(ENUMERATION): def __init__(self,*kargs): pass # Defined datatype day_in_month_number class day_in_month_number(INTEGER): def __init__(self,*kargs): pass # SELECT TYPE founded_item_select founded_item_select = SELECT( 'founded_item', 'representation_item', scope = schema_scope) # Defined datatype trimming_preference class trimming_preference(ENUMERATION): def __init__(self,*kargs): pass # SELECT TYPE vector_or_direction vector_or_direction = SELECT( 'vector', 'direction', scope = schema_scope) # SELECT TYPE wireframe_model wireframe_model = SELECT( 'shell_based_wireframe_model', 'edge_based_wireframe_model', scope = schema_scope) # Defined datatype volume_measure class volume_measure(REAL): def __init__(self,*kargs): pass # SELECT TYPE geometric_set_select geometric_set_select = SELECT( 'point', 'curve', 'surface', scope = schema_scope) # Defined datatype positive_plane_angle_measure class positive_plane_angle_measure(plane_angle_measure): def __init__(self,*kargs): pass self.wr1() def wr1(self): eval_wr1_wr = (self > 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr # SELECT TYPE start_request_item start_request_item = SELECT( 'product_definition_formation', scope = schema_scope) # Defined datatype b_spline_surface_form class b_spline_surface_form(ENUMERATION): def __init__(self,*kargs): pass # SELECT TYPE person_organization_item person_organization_item = SELECT( 'change', 'start_work', 'change_request', 'start_request', 'configuration_item', 'product', 'product_definition_formation', 'product_definition', 'contract', 'security_classification', scope = schema_scope) # SELECT TYPE date_time_item date_time_item = SELECT( 'product_definition', 'change_request', 'start_request', 'change', 'start_work', 'approval_person_organization', 'contract', 'security_classification', 'certification', scope = schema_scope) # SELECT TYPE shell shell = SELECT( 'vertex_shell', 'wire_shell', 'open_shell', 'closed_shell', scope = schema_scope) # SELECT TYPE transformation transformation = SELECT( 'item_defined_transformation', 'functionally_defined_transformation', scope = schema_scope) # Defined datatype day_in_week_number class day_in_week_number(INTEGER): def __init__(self,*kargs): pass self.wr1() def wr1(self): eval_wr1_wr = ((1 <= self) and (self <= 7)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr # SELECT TYPE boolean_operand boolean_operand = SELECT( 'solid_model', scope = schema_scope) # SELECT TYPE certified_item certified_item = SELECT( 'supplied_part_relationship', scope = schema_scope) # SELECT TYPE date_time_select date_time_select = SELECT( 'date', 'local_time', 'date_and_time', scope = schema_scope) # Defined datatype solid_angle_measure class solid_angle_measure(REAL): def __init__(self,*kargs): pass # SELECT TYPE curve_on_surface curve_on_surface = SELECT( 'pcurve', 'surface_curve', 'composite_curve_on_surface', scope = schema_scope) # SELECT TYPE trimming_select trimming_select = SELECT( 'cartesian_point', 'parameter_value', scope = schema_scope) # Defined datatype ahead_or_behind class ahead_or_behind(ENUMERATION): def __init__(self,*kargs): pass # SELECT TYPE contracted_item contracted_item = SELECT( 'product_definition_formation', scope = schema_scope) # Defined datatype day_in_year_number class day_in_year_number(INTEGER): def __init__(self,*kargs): pass # Defined datatype mass_measure class mass_measure(REAL): def __init__(self,*kargs): pass # Defined datatype descriptive_measure class descriptive_measure(STRING): def __init__(self,*kargs): pass # Defined datatype area_measure class area_measure(REAL): def __init__(self,*kargs): pass # Defined datatype month_in_year_number class month_in_year_number(INTEGER): def __init__(self,*kargs): pass self.wr1() def wr1(self): eval_wr1_wr = ((1 <= self) and (self <= 12)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr # Defined datatype source class source(ENUMERATION): def __init__(self,*kargs): pass # SELECT TYPE unit unit = SELECT( 'named_unit', scope = schema_scope) # SELECT TYPE reversible_topology reversible_topology = SELECT( 'reversible_topology_item', 'list_of_reversible_topology_item', 'set_of_reversible_topology_item', scope = schema_scope) # SELECT TYPE work_item work_item = SELECT( 'product_definition_formation', scope = schema_scope) # SELECT TYPE shape_definition shape_definition = SELECT( 'product_definition_shape', 'shape_aspect', 'shape_aspect_relationship', scope = schema_scope) # Defined datatype second_in_minute class second_in_minute(REAL): def __init__(self,*kargs): pass self.wr1() def wr1(self): eval_wr1_wr = ((0 <= self) and (self < 60)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr # Defined datatype label class label(STRING): def __init__(self,*kargs): pass # Defined datatype context_dependent_measure class context_dependent_measure(REAL): def __init__(self,*kargs): pass # SELECT TYPE supported_item supported_item = SELECT( 'action_directive', 'action', 'action_method', scope = schema_scope) # Defined datatype si_prefix class si_prefix(ENUMERATION): def __init__(self,*kargs): pass # SELECT TYPE approved_item approved_item = SELECT( 'product_definition_formation', 'product_definition', 'configuration_effectivity', 'configuration_item', 'security_classification', 'change_request', 'change', 'start_request', 'start_work', 'certification', 'contract', scope = schema_scope) # Defined datatype count_measure class count_measure(NUMBER): def __init__(self,*kargs): pass # SELECT TYPE surface_model surface_model = SELECT( 'shell_based_surface_model', scope = schema_scope) list_of_reversible_topology_item = LIST(0,None,'reversible_topology_item', scope = schema_scope) #################### # ENTITY representation_item # #################### class representation_item(BaseEntityClass): '''Entity representation_item definition. :param name :type name:label ''' def __init__( self , name, ): self.name = name @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) def wr1(self): eval_wr1_wr = (SIZEOF(using_representations(self)) > 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY geometric_representation_item # #################### class geometric_representation_item(representation_item): '''Entity geometric_representation_item definition. :param dim :type dim:dimension_count ''' def __init__( self , inherited0__name , ): representation_item.__init__(self , inherited0__name , ) @apply def dim(): def fget( self ): attribute_eval = dimension_of(self) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument dim is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (SIZEOF(None) == 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY functionally_defined_transformation # #################### class functionally_defined_transformation(BaseEntityClass): '''Entity functionally_defined_transformation definition. :param name :type name:label :param description :type description:text ''' def __init__( self , name,description, ): self.name = name self.description = description @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) #################### # ENTITY cartesian_transformation_operator # #################### class cartesian_transformation_operator(geometric_representation_item,functionally_defined_transformation): '''Entity cartesian_transformation_operator definition. :param axis1 :type axis1:direction :param axis2 :type axis2:direction :param local_origin :type local_origin:cartesian_point :param scale :type scale:REAL :param scl :type scl:REAL ''' def __init__( self , inherited0__name , inherited1__name , inherited2__description , axis1,axis2,local_origin,scale, ): geometric_representation_item.__init__(self , inherited0__name , ) functionally_defined_transformation.__init__(self , inherited1__name , inherited2__description , ) self.axis1 = axis1 self.axis2 = axis2 self.local_origin = local_origin self.scale = scale @apply def axis1(): def fget( self ): return self._axis1 def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,direction): self._axis1 = direction(value) else: self._axis1 = value else: self._axis1 = value return property(**locals()) @apply def axis2(): def fget( self ): return self._axis2 def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,direction): self._axis2 = direction(value) else: self._axis2 = value else: self._axis2 = value return property(**locals()) @apply def local_origin(): def fget( self ): return self._local_origin def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument local_origin is mantatory and can not be set to None') if not check_type(value,cartesian_point): self._local_origin = cartesian_point(value) else: self._local_origin = value return property(**locals()) @apply def scale(): def fget( self ): return self._scale def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,REAL): self._scale = REAL(value) else: self._scale = value else: self._scale = value return property(**locals()) @apply def scl(): def fget( self ): attribute_eval = NVL(self.scale,1) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument scl is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (self.scl > 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY cartesian_transformation_operator_3d # #################### class cartesian_transformation_operator_3d(cartesian_transformation_operator): '''Entity cartesian_transformation_operator_3d definition. :param axis3 :type axis3:direction :param u :type u:LIST(3,3,'direction', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__name , inherited2__description , inherited3__axis1 , inherited4__axis2 , inherited5__local_origin , inherited6__scale , axis3, ): cartesian_transformation_operator.__init__(self , inherited0__name , inherited1__name , inherited2__description , inherited3__axis1 , inherited4__axis2 , inherited5__local_origin , inherited6__scale , ) self.axis3 = axis3 @apply def axis3(): def fget( self ): return self._axis3 def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,direction): self._axis3 = direction(value) else: self._axis3 = value else: self._axis3 = value return property(**locals()) @apply def u(): def fget( self ): attribute_eval = base_axis(3,self.self.cartesian_transformation_operator.self.axis1,self.self.cartesian_transformation_operator.self.axis2,self.axis3) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument u is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (self.self.geometric_representation_item.self.dim == 3) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY versioned_action_request # #################### class versioned_action_request(BaseEntityClass): '''Entity versioned_action_request definition. :param id :type id:identifier :param version :type version:label :param purpose :type purpose:text :param description :type description:text ''' def __init__( self , id,version,purpose,description, ): self.id = id self.version = version self.purpose = purpose self.description = description @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) @apply def version(): def fget( self ): return self._version def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument version is mantatory and can not be set to None') if not check_type(value,label): self._version = label(value) else: self._version = value return property(**locals()) @apply def purpose(): def fget( self ): return self._purpose def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument purpose is mantatory and can not be set to None') if not check_type(value,text): self._purpose = text(value) else: self._purpose = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) #################### # ENTITY representation # #################### class representation(BaseEntityClass): '''Entity representation definition. :param name :type name:label :param items :type items:SET(1,None,'representation_item', scope = schema_scope) :param context_of_items :type context_of_items:representation_context ''' def __init__( self , name,items,context_of_items, ): self.name = name self.items = items self.context_of_items = context_of_items @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'representation_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) @apply def context_of_items(): def fget( self ): return self._context_of_items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument context_of_items is mantatory and can not be set to None') if not check_type(value,representation_context): self._context_of_items = representation_context(value) else: self._context_of_items = value return property(**locals()) #################### # ENTITY shape_representation # #################### class shape_representation(representation): '''Entity shape_representation definition. ''' def __init__( self , inherited0__name , inherited1__items , inherited2__context_of_items , ): representation.__init__(self , inherited0__name , inherited1__items , inherited2__context_of_items , ) #################### # ENTITY manifold_surface_shape_representation # #################### class manifold_surface_shape_representation(shape_representation): '''Entity manifold_surface_shape_representation definition. ''' def __init__( self , inherited0__name , inherited1__items , inherited2__context_of_items , ): shape_representation.__init__(self , inherited0__name , inherited1__items , inherited2__context_of_items , ) def wr1(self): eval_wr1_wr = (SIZEOF(None) == 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(None) > 0) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(None) == 0) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(None) == 0) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr def wr5(self): eval_wr5_wr = (SIZEOF(None) == 0) if not eval_wr5_wr: raise AssertionError('Rule wr5 violated') else: return eval_wr5_wr def wr6(self): eval_wr6_wr = (SIZEOF(None) == 0) if not eval_wr6_wr: raise AssertionError('Rule wr6 violated') else: return eval_wr6_wr def wr7(self): eval_wr7_wr = (SIZEOF(None) == 0) if not eval_wr7_wr: raise AssertionError('Rule wr7 violated') else: return eval_wr7_wr def wr8(self): eval_wr8_wr = (SIZEOF(None) == 0) if not eval_wr8_wr: raise AssertionError('Rule wr8 violated') else: return eval_wr8_wr def wr9(self): eval_wr9_wr = (SIZEOF(None) == 0) if not eval_wr9_wr: raise AssertionError('Rule wr9 violated') else: return eval_wr9_wr def wr10(self): eval_wr10_wr = (SIZEOF(None) == 0) if not eval_wr10_wr: raise AssertionError('Rule wr10 violated') else: return eval_wr10_wr def wr11(self): eval_wr11_wr = (SIZEOF(None) == 0) if not eval_wr11_wr: raise AssertionError('Rule wr11 violated') else: return eval_wr11_wr def wr12(self): eval_wr12_wr = (SIZEOF(None) == 0) if not eval_wr12_wr: raise AssertionError('Rule wr12 violated') else: return eval_wr12_wr def wr13(self): eval_wr13_wr = (SIZEOF(None) == 0) if not eval_wr13_wr: raise AssertionError('Rule wr13 violated') else: return eval_wr13_wr def wr14(self): eval_wr14_wr = (SIZEOF(None) == 0) if not eval_wr14_wr: raise AssertionError('Rule wr14 violated') else: return eval_wr14_wr def wr15(self): eval_wr15_wr = (SIZEOF(None) == 0) if not eval_wr15_wr: raise AssertionError('Rule wr15 violated') else: return eval_wr15_wr #################### # ENTITY certification # #################### class certification(BaseEntityClass): '''Entity certification definition. :param name :type name:label :param purpose :type purpose:text :param kind :type kind:certification_type ''' def __init__( self , name,purpose,kind, ): self.name = name self.purpose = purpose self.kind = kind @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def purpose(): def fget( self ): return self._purpose def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument purpose is mantatory and can not be set to None') if not check_type(value,text): self._purpose = text(value) else: self._purpose = value return property(**locals()) @apply def kind(): def fget( self ): return self._kind def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument kind is mantatory and can not be set to None') if not check_type(value,certification_type): self._kind = certification_type(value) else: self._kind = value return property(**locals()) #################### # ENTITY product_definition_relationship # #################### class product_definition_relationship(BaseEntityClass): '''Entity product_definition_relationship definition. :param id :type id:identifier :param name :type name:label :param description :type description:text :param relating_product_definition :type relating_product_definition:product_definition :param related_product_definition :type related_product_definition:product_definition ''' def __init__( self , id,name,description,relating_product_definition,related_product_definition, ): self.id = id self.name = name self.description = description self.relating_product_definition = relating_product_definition self.related_product_definition = related_product_definition @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def relating_product_definition(): def fget( self ): return self._relating_product_definition def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument relating_product_definition is mantatory and can not be set to None') if not check_type(value,product_definition): self._relating_product_definition = product_definition(value) else: self._relating_product_definition = value return property(**locals()) @apply def related_product_definition(): def fget( self ): return self._related_product_definition def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument related_product_definition is mantatory and can not be set to None') if not check_type(value,product_definition): self._related_product_definition = product_definition(value) else: self._related_product_definition = value return property(**locals()) #################### # ENTITY product_definition_usage # #################### class product_definition_usage(product_definition_relationship): '''Entity product_definition_usage definition. ''' def __init__( self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , ): product_definition_relationship.__init__(self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , ) def wr1(self): eval_wr1_wr = acyclic_product_definition_relationship(self,[self.self.product_definition_relationship.self.related_product_definition],'CONFIG_CONTROL_DESIGN.PRODUCT_DEFINITION_USAGE') if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY assembly_component_usage # #################### class assembly_component_usage(product_definition_usage): '''Entity assembly_component_usage definition. :param reference_designator :type reference_designator:identifier ''' def __init__( self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , reference_designator, ): product_definition_usage.__init__(self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , ) self.reference_designator = reference_designator @apply def reference_designator(): def fget( self ): return self._reference_designator def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,identifier): self._reference_designator = identifier(value) else: self._reference_designator = value else: self._reference_designator = value return property(**locals()) #################### # ENTITY quantified_assembly_component_usage # #################### class quantified_assembly_component_usage(assembly_component_usage): '''Entity quantified_assembly_component_usage definition. :param quantity :type quantity:measure_with_unit ''' def __init__( self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , inherited5__reference_designator , quantity, ): assembly_component_usage.__init__(self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , inherited5__reference_designator , ) self.quantity = quantity @apply def quantity(): def fget( self ): return self._quantity def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument quantity is mantatory and can not be set to None') if not check_type(value,measure_with_unit): self._quantity = measure_with_unit(value) else: self._quantity = value return property(**locals()) #################### # ENTITY solid_model # #################### class solid_model(geometric_representation_item): '''Entity solid_model definition. ''' def __init__( self , inherited0__name , ): geometric_representation_item.__init__(self , inherited0__name , ) #################### # ENTITY manifold_solid_brep # #################### class manifold_solid_brep(solid_model): '''Entity manifold_solid_brep definition. :param outer :type outer:closed_shell ''' def __init__( self , inherited0__name , outer, ): solid_model.__init__(self , inherited0__name , ) self.outer = outer @apply def outer(): def fget( self ): return self._outer def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument outer is mantatory and can not be set to None') if not check_type(value,closed_shell): self._outer = closed_shell(value) else: self._outer = value return property(**locals()) #################### # ENTITY faceted_brep # #################### class faceted_brep(manifold_solid_brep): '''Entity faceted_brep definition. ''' def __init__( self , inherited0__name , inherited1__outer , ): manifold_solid_brep.__init__(self , inherited0__name , inherited1__outer , ) #################### # ENTITY action_directive # #################### class action_directive(BaseEntityClass): '''Entity action_directive definition. :param name :type name:label :param description :type description:text :param analysis :type analysis:text :param comment :type comment:text :param requests :type requests:SET(1,None,'versioned_action_request', scope = schema_scope) ''' def __init__( self , name,description,analysis,comment,requests, ): self.name = name self.description = description self.analysis = analysis self.comment = comment self.requests = requests @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def analysis(): def fget( self ): return self._analysis def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument analysis is mantatory and can not be set to None') if not check_type(value,text): self._analysis = text(value) else: self._analysis = value return property(**locals()) @apply def comment(): def fget( self ): return self._comment def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument comment is mantatory and can not be set to None') if not check_type(value,text): self._comment = text(value) else: self._comment = value return property(**locals()) @apply def requests(): def fget( self ): return self._requests def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument requests is mantatory and can not be set to None') if not check_type(value,SET(1,None,'versioned_action_request', scope = schema_scope)): self._requests = SET(value) else: self._requests = value return property(**locals()) #################### # ENTITY named_unit # #################### class named_unit(BaseEntityClass): '''Entity named_unit definition. :param dimensions :type dimensions:dimensional_exponents ''' def __init__( self , dimensions, ): self.dimensions = dimensions @apply def dimensions(): def fget( self ): return self._dimensions def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument dimensions is mantatory and can not be set to None') if not check_type(value,dimensional_exponents): self._dimensions = dimensional_exponents(value) else: self._dimensions = value return property(**locals()) #################### # ENTITY plane_angle_unit # #################### class plane_angle_unit(named_unit): '''Entity plane_angle_unit definition. ''' def __init__( self , inherited0__dimensions , ): named_unit.__init__(self , inherited0__dimensions , ) def wr1(self): eval_wr1_wr = (((((((self.self.named_unit.self.dimensions.self.length_exponent == 0) and (self.self.named_unit.self.dimensions.self.mass_exponent == 0)) and (self.self.named_unit.self.dimensions.self.time_exponent == 0)) and (self.self.named_unit.self.dimensions.self.electric_current_exponent == 0)) and (self.self.named_unit.self.dimensions.self.thermodynamic_temperature_exponent == 0)) and (self.self.named_unit.self.dimensions.self.amount_of_substance_exponent == 0)) and (self.self.named_unit.self.dimensions.self.luminous_intensity_exponent == 0)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY measure_with_unit # #################### class measure_with_unit(BaseEntityClass): '''Entity measure_with_unit definition. :param value_component :type value_component:measure_value :param unit_component :type unit_component:unit ''' def __init__( self , value_component,unit_component, ): self.value_component = value_component self.unit_component = unit_component @apply def value_component(): def fget( self ): return self._value_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument value_component is mantatory and can not be set to None') if not check_type(value,measure_value): self._value_component = measure_value(value) else: self._value_component = value return property(**locals()) @apply def unit_component(): def fget( self ): return self._unit_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument unit_component is mantatory and can not be set to None') if not check_type(value,unit): self._unit_component = unit(value) else: self._unit_component = value return property(**locals()) def wr1(self): eval_wr1_wr = valid_units(self) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY area_measure_with_unit # #################### class area_measure_with_unit(measure_with_unit): '''Entity area_measure_with_unit definition. ''' def __init__( self , inherited0__value_component , inherited1__unit_component , ): measure_with_unit.__init__(self , inherited0__value_component , inherited1__unit_component , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.AREA_UNIT' == TYPEOF(self.self.measure_with_unit.self.unit_component)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY effectivity # #################### class effectivity(BaseEntityClass): '''Entity effectivity definition. :param id :type id:identifier ''' def __init__( self , id, ): self.id = id @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) #################### # ENTITY serial_numbered_effectivity # #################### class serial_numbered_effectivity(effectivity): '''Entity serial_numbered_effectivity definition. :param effectivity_start_id :type effectivity_start_id:identifier :param effectivity_end_id :type effectivity_end_id:identifier ''' def __init__( self , inherited0__id , effectivity_start_id,effectivity_end_id, ): effectivity.__init__(self , inherited0__id , ) self.effectivity_start_id = effectivity_start_id self.effectivity_end_id = effectivity_end_id @apply def effectivity_start_id(): def fget( self ): return self._effectivity_start_id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument effectivity_start_id is mantatory and can not be set to None') if not check_type(value,identifier): self._effectivity_start_id = identifier(value) else: self._effectivity_start_id = value return property(**locals()) @apply def effectivity_end_id(): def fget( self ): return self._effectivity_end_id def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,identifier): self._effectivity_end_id = identifier(value) else: self._effectivity_end_id = value else: self._effectivity_end_id = value return property(**locals()) #################### # ENTITY surface # #################### class surface(geometric_representation_item): '''Entity surface definition. ''' def __init__( self , inherited0__name , ): geometric_representation_item.__init__(self , inherited0__name , ) #################### # ENTITY offset_surface # #################### class offset_surface(surface): '''Entity offset_surface definition. :param basis_surface :type basis_surface:surface :param distance :type distance:length_measure :param self_intersect :type self_intersect:LOGICAL ''' def __init__( self , inherited0__name , basis_surface,distance,self_intersect, ): surface.__init__(self , inherited0__name , ) self.basis_surface = basis_surface self.distance = distance self.self_intersect = self_intersect @apply def basis_surface(): def fget( self ): return self._basis_surface def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis_surface is mantatory and can not be set to None') if not check_type(value,surface): self._basis_surface = surface(value) else: self._basis_surface = value return property(**locals()) @apply def distance(): def fget( self ): return self._distance def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument distance is mantatory and can not be set to None') if not check_type(value,length_measure): self._distance = length_measure(value) else: self._distance = value return property(**locals()) @apply def self_intersect(): def fget( self ): return self._self_intersect def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument self_intersect is mantatory and can not be set to None') if not check_type(value,LOGICAL): self._self_intersect = LOGICAL(value) else: self._self_intersect = value return property(**locals()) #################### # ENTITY placement # #################### class placement(geometric_representation_item): '''Entity placement definition. :param location :type location:cartesian_point ''' def __init__( self , inherited0__name , location, ): geometric_representation_item.__init__(self , inherited0__name , ) self.location = location @apply def location(): def fget( self ): return self._location def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument location is mantatory and can not be set to None') if not check_type(value,cartesian_point): self._location = cartesian_point(value) else: self._location = value return property(**locals()) #################### # ENTITY axis2_placement_2d # #################### class axis2_placement_2d(placement): '''Entity axis2_placement_2d definition. :param ref_direction :type ref_direction:direction :param p :type p:LIST(2,2,'direction', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__location , ref_direction, ): placement.__init__(self , inherited0__name , inherited1__location , ) self.ref_direction = ref_direction @apply def ref_direction(): def fget( self ): return self._ref_direction def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,direction): self._ref_direction = direction(value) else: self._ref_direction = value else: self._ref_direction = value return property(**locals()) @apply def p(): def fget( self ): attribute_eval = build_2axes(self.ref_direction) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument p is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (self.self.geometric_representation_item.self.dim == 2) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY product_category # #################### class product_category(BaseEntityClass): '''Entity product_category definition. :param name :type name:label :param description :type description:text ''' def __init__( self , name,description, ): self.name = name self.description = description @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,text): self._description = text(value) else: self._description = value else: self._description = value return property(**locals()) #################### # ENTITY product_related_product_category # #################### class product_related_product_category(product_category): '''Entity product_related_product_category definition. :param products :type products:SET(1,None,'product', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__description , products, ): product_category.__init__(self , inherited0__name , inherited1__description , ) self.products = products @apply def products(): def fget( self ): return self._products def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument products is mantatory and can not be set to None') if not check_type(value,SET(1,None,'product', scope = schema_scope)): self._products = SET(value) else: self._products = value return property(**locals()) #################### # ENTITY curve # #################### class curve(geometric_representation_item): '''Entity curve definition. ''' def __init__( self , inherited0__name , ): geometric_representation_item.__init__(self , inherited0__name , ) #################### # ENTITY conic # #################### class conic(curve): '''Entity conic definition. :param position :type position:axis2_placement ''' def __init__( self , inherited0__name , position, ): curve.__init__(self , inherited0__name , ) self.position = position @apply def position(): def fget( self ): return self._position def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument position is mantatory and can not be set to None') if not check_type(value,axis2_placement): self._position = axis2_placement(value) else: self._position = value return property(**locals()) #################### # ENTITY hyperbola # #################### class hyperbola(conic): '''Entity hyperbola definition. :param semi_axis :type semi_axis:positive_length_measure :param semi_imag_axis :type semi_imag_axis:positive_length_measure ''' def __init__( self , inherited0__name , inherited1__position , semi_axis,semi_imag_axis, ): conic.__init__(self , inherited0__name , inherited1__position , ) self.semi_axis = semi_axis self.semi_imag_axis = semi_imag_axis @apply def semi_axis(): def fget( self ): return self._semi_axis def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument semi_axis is mantatory and can not be set to None') if not check_type(value,positive_length_measure): self._semi_axis = positive_length_measure(value) else: self._semi_axis = value return property(**locals()) @apply def semi_imag_axis(): def fget( self ): return self._semi_imag_axis def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument semi_imag_axis is mantatory and can not be set to None') if not check_type(value,positive_length_measure): self._semi_imag_axis = positive_length_measure(value) else: self._semi_imag_axis = value return property(**locals()) #################### # ENTITY address # #################### class address(BaseEntityClass): '''Entity address definition. :param internal_location :type internal_location:label :param street_number :type street_number:label :param street :type street:label :param postal_box :type postal_box:label :param town :type town:label :param region :type region:label :param postal_code :type postal_code:label :param country :type country:label :param facsimile_number :type facsimile_number:label :param telephone_number :type telephone_number:label :param electronic_mail_address :type electronic_mail_address:label :param telex_number :type telex_number:label ''' def __init__( self , internal_location,street_number,street,postal_box,town,region,postal_code,country,facsimile_number,telephone_number,electronic_mail_address,telex_number, ): self.internal_location = internal_location self.street_number = street_number self.street = street self.postal_box = postal_box self.town = town self.region = region self.postal_code = postal_code self.country = country self.facsimile_number = facsimile_number self.telephone_number = telephone_number self.electronic_mail_address = electronic_mail_address self.telex_number = telex_number @apply def internal_location(): def fget( self ): return self._internal_location def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._internal_location = label(value) else: self._internal_location = value else: self._internal_location = value return property(**locals()) @apply def street_number(): def fget( self ): return self._street_number def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._street_number = label(value) else: self._street_number = value else: self._street_number = value return property(**locals()) @apply def street(): def fget( self ): return self._street def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._street = label(value) else: self._street = value else: self._street = value return property(**locals()) @apply def postal_box(): def fget( self ): return self._postal_box def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._postal_box = label(value) else: self._postal_box = value else: self._postal_box = value return property(**locals()) @apply def town(): def fget( self ): return self._town def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._town = label(value) else: self._town = value else: self._town = value return property(**locals()) @apply def region(): def fget( self ): return self._region def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._region = label(value) else: self._region = value else: self._region = value return property(**locals()) @apply def postal_code(): def fget( self ): return self._postal_code def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._postal_code = label(value) else: self._postal_code = value else: self._postal_code = value return property(**locals()) @apply def country(): def fget( self ): return self._country def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._country = label(value) else: self._country = value else: self._country = value return property(**locals()) @apply def facsimile_number(): def fget( self ): return self._facsimile_number def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._facsimile_number = label(value) else: self._facsimile_number = value else: self._facsimile_number = value return property(**locals()) @apply def telephone_number(): def fget( self ): return self._telephone_number def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._telephone_number = label(value) else: self._telephone_number = value else: self._telephone_number = value return property(**locals()) @apply def electronic_mail_address(): def fget( self ): return self._electronic_mail_address def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._electronic_mail_address = label(value) else: self._electronic_mail_address = value else: self._electronic_mail_address = value return property(**locals()) @apply def telex_number(): def fget( self ): return self._telex_number def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._telex_number = label(value) else: self._telex_number = value else: self._telex_number = value return property(**locals()) def wr1(self): eval_wr1_wr = (((((((((((EXISTS(self.internal_location) or EXISTS(self.street_number)) or EXISTS(self.street)) or EXISTS(self.postal_box)) or EXISTS(self.town)) or EXISTS(self.region)) or EXISTS(self.postal_code)) or EXISTS(self.country)) or EXISTS(self.facsimile_number)) or EXISTS(self.telephone_number)) or EXISTS(self.electronic_mail_address)) or EXISTS(self.telex_number)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY organizational_address # #################### class organizational_address(address): '''Entity organizational_address definition. :param organizations :type organizations:SET(1,None,'organization', scope = schema_scope) :param description :type description:text ''' def __init__( self , inherited0__internal_location , inherited1__street_number , inherited2__street , inherited3__postal_box , inherited4__town , inherited5__region , inherited6__postal_code , inherited7__country , inherited8__facsimile_number , inherited9__telephone_number , inherited10__electronic_mail_address , inherited11__telex_number , organizations,description, ): address.__init__(self , inherited0__internal_location , inherited1__street_number , inherited2__street , inherited3__postal_box , inherited4__town , inherited5__region , inherited6__postal_code , inherited7__country , inherited8__facsimile_number , inherited9__telephone_number , inherited10__electronic_mail_address , inherited11__telex_number , ) self.organizations = organizations self.description = description @apply def organizations(): def fget( self ): return self._organizations def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument organizations is mantatory and can not be set to None') if not check_type(value,SET(1,None,'organization', scope = schema_scope)): self._organizations = SET(value) else: self._organizations = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) #################### # ENTITY bounded_surface # #################### class bounded_surface(surface): '''Entity bounded_surface definition. ''' def __init__( self , inherited0__name , ): surface.__init__(self , inherited0__name , ) #################### # ENTITY b_spline_surface # #################### class b_spline_surface(bounded_surface): '''Entity b_spline_surface definition. :param u_degree :type u_degree:INTEGER :param v_degree :type v_degree:INTEGER :param control_points_list :type control_points_list:LIST(2,None,LIST(2,None,'cartesian_point', scope = schema_scope)) :param surface_form :type surface_form:b_spline_surface_form :param u_closed :type u_closed:LOGICAL :param v_closed :type v_closed:LOGICAL :param self_intersect :type self_intersect:LOGICAL :param u_upper :type u_upper:INTEGER :param v_upper :type v_upper:INTEGER :param control_points :type control_points:ARRAY(0,u_upper,ARRAY(0,v_upper,'cartesian_point', scope = schema_scope)) ''' def __init__( self , inherited0__name , u_degree,v_degree,control_points_list,surface_form,u_closed,v_closed,self_intersect, ): bounded_surface.__init__(self , inherited0__name , ) self.u_degree = u_degree self.v_degree = v_degree self.control_points_list = control_points_list self.surface_form = surface_form self.u_closed = u_closed self.v_closed = v_closed self.self_intersect = self_intersect @apply def u_degree(): def fget( self ): return self._u_degree def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument u_degree is mantatory and can not be set to None') if not check_type(value,INTEGER): self._u_degree = INTEGER(value) else: self._u_degree = value return property(**locals()) @apply def v_degree(): def fget( self ): return self._v_degree def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument v_degree is mantatory and can not be set to None') if not check_type(value,INTEGER): self._v_degree = INTEGER(value) else: self._v_degree = value return property(**locals()) @apply def control_points_list(): def fget( self ): return self._control_points_list def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument control_points_list is mantatory and can not be set to None') if not check_type(value,LIST(2,None,LIST(2,None,'cartesian_point', scope = schema_scope))): self._control_points_list = LIST(value) else: self._control_points_list = value return property(**locals()) @apply def surface_form(): def fget( self ): return self._surface_form def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument surface_form is mantatory and can not be set to None') if not check_type(value,b_spline_surface_form): self._surface_form = b_spline_surface_form(value) else: self._surface_form = value return property(**locals()) @apply def u_closed(): def fget( self ): return self._u_closed def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument u_closed is mantatory and can not be set to None') if not check_type(value,LOGICAL): self._u_closed = LOGICAL(value) else: self._u_closed = value return property(**locals()) @apply def v_closed(): def fget( self ): return self._v_closed def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument v_closed is mantatory and can not be set to None') if not check_type(value,LOGICAL): self._v_closed = LOGICAL(value) else: self._v_closed = value return property(**locals()) @apply def self_intersect(): def fget( self ): return self._self_intersect def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument self_intersect is mantatory and can not be set to None') if not check_type(value,LOGICAL): self._self_intersect = LOGICAL(value) else: self._self_intersect = value return property(**locals()) @apply def u_upper(): def fget( self ): attribute_eval = (SIZEOF(self.control_points_list) - 1) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument u_upper is DERIVED. It is computed and can not be set to any value') return property(**locals()) @apply def v_upper(): def fget( self ): attribute_eval = (SIZEOF(self.control_points_list[1]) - 1) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument v_upper is DERIVED. It is computed and can not be set to any value') return property(**locals()) @apply def control_points(): def fget( self ): attribute_eval = make_array_of_array(self.control_points_list,0,self.u_upper,0,self.v_upper) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument control_points is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (((('CONFIG_CONTROL_DESIGN.UNIFORM_SURFACE' == TYPEOF(self)) or ('CONFIG_CONTROL_DESIGN.QUASI_UNIFORM_SURFACE' == TYPEOF(self))) or ('CONFIG_CONTROL_DESIGN.BEZIER_SURFACE' == TYPEOF(self))) or ('CONFIG_CONTROL_DESIGN.B_SPLINE_SURFACE_WITH_KNOTS' == TYPEOF(self))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY uniform_surface # #################### class uniform_surface(b_spline_surface): '''Entity uniform_surface definition. ''' def __init__( self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , ): b_spline_surface.__init__(self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , ) #################### # ENTITY geometrically_bounded_surface_shape_representation # #################### class geometrically_bounded_surface_shape_representation(shape_representation): '''Entity geometrically_bounded_surface_shape_representation definition. ''' def __init__( self , inherited0__name , inherited1__items , inherited2__context_of_items , ): shape_representation.__init__(self , inherited0__name , inherited1__items , inherited2__context_of_items , ) def wr1(self): eval_wr1_wr = (SIZEOF(None) == 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(None) > 0) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(None) == 0) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(None) == 0) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr def wr5(self): eval_wr5_wr = (SIZEOF(None) == 0) if not eval_wr5_wr: raise AssertionError('Rule wr5 violated') else: return eval_wr5_wr def wr6(self): eval_wr6_wr = (SIZEOF(None) == 0) if not eval_wr6_wr: raise AssertionError('Rule wr6 violated') else: return eval_wr6_wr def wr7(self): eval_wr7_wr = (SIZEOF(None) > 0) if not eval_wr7_wr: raise AssertionError('Rule wr7 violated') else: return eval_wr7_wr #################### # ENTITY axis1_placement # #################### class axis1_placement(placement): '''Entity axis1_placement definition. :param axis :type axis:direction :param z :type z:direction ''' def __init__( self , inherited0__name , inherited1__location , axis, ): placement.__init__(self , inherited0__name , inherited1__location , ) self.axis = axis @apply def axis(): def fget( self ): return self._axis def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,direction): self._axis = direction(value) else: self._axis = value else: self._axis = value return property(**locals()) @apply def z(): def fget( self ): attribute_eval = NVL(normalise(self.axis),self.dummy_gri == direction([0,0,1])) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument z is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (self.self.geometric_representation_item.self.dim == 3) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY bounded_curve # #################### class bounded_curve(curve): '''Entity bounded_curve definition. ''' def __init__( self , inherited0__name , ): curve.__init__(self , inherited0__name , ) #################### # ENTITY b_spline_curve # #################### class b_spline_curve(bounded_curve): '''Entity b_spline_curve definition. :param degree :type degree:INTEGER :param control_points_list :type control_points_list:LIST(2,None,'cartesian_point', scope = schema_scope) :param curve_form :type curve_form:b_spline_curve_form :param closed_curve :type closed_curve:LOGICAL :param self_intersect :type self_intersect:LOGICAL :param upper_index_on_control_points :type upper_index_on_control_points:INTEGER :param control_points :type control_points:ARRAY(0,upper_index_on_control_points,'cartesian_point', scope = schema_scope) ''' def __init__( self , inherited0__name , degree,control_points_list,curve_form,closed_curve,self_intersect, ): bounded_curve.__init__(self , inherited0__name , ) self.degree = degree self.control_points_list = control_points_list self.curve_form = curve_form self.closed_curve = closed_curve self.self_intersect = self_intersect @apply def degree(): def fget( self ): return self._degree def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument degree is mantatory and can not be set to None') if not check_type(value,INTEGER): self._degree = INTEGER(value) else: self._degree = value return property(**locals()) @apply def control_points_list(): def fget( self ): return self._control_points_list def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument control_points_list is mantatory and can not be set to None') if not check_type(value,LIST(2,None,'cartesian_point', scope = schema_scope)): self._control_points_list = LIST(value) else: self._control_points_list = value return property(**locals()) @apply def curve_form(): def fget( self ): return self._curve_form def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument curve_form is mantatory and can not be set to None') if not check_type(value,b_spline_curve_form): self._curve_form = b_spline_curve_form(value) else: self._curve_form = value return property(**locals()) @apply def closed_curve(): def fget( self ): return self._closed_curve def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument closed_curve is mantatory and can not be set to None') if not check_type(value,LOGICAL): self._closed_curve = LOGICAL(value) else: self._closed_curve = value return property(**locals()) @apply def self_intersect(): def fget( self ): return self._self_intersect def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument self_intersect is mantatory and can not be set to None') if not check_type(value,LOGICAL): self._self_intersect = LOGICAL(value) else: self._self_intersect = value return property(**locals()) @apply def upper_index_on_control_points(): def fget( self ): attribute_eval = (SIZEOF(self.control_points_list) - 1) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument upper_index_on_control_points is DERIVED. It is computed and can not be set to any value') return property(**locals()) @apply def control_points(): def fget( self ): attribute_eval = list_to_array(self.control_points_list,0,self.upper_index_on_control_points) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument control_points is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (((('CONFIG_CONTROL_DESIGN.UNIFORM_CURVE' == TYPEOF(self)) or ('CONFIG_CONTROL_DESIGN.QUASI_UNIFORM_CURVE' == TYPEOF(self))) or ('CONFIG_CONTROL_DESIGN.BEZIER_CURVE' == TYPEOF(self))) or ('CONFIG_CONTROL_DESIGN.B_SPLINE_CURVE_WITH_KNOTS' == TYPEOF(self))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY rational_b_spline_curve # #################### class rational_b_spline_curve(b_spline_curve): '''Entity rational_b_spline_curve definition. :param weights_data :type weights_data:LIST(2,None,'REAL', scope = schema_scope) :param weights :type weights:ARRAY(0,upper_index_on_control_points,'REAL', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , weights_data, ): b_spline_curve.__init__(self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , ) self.weights_data = weights_data @apply def weights_data(): def fget( self ): return self._weights_data def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument weights_data is mantatory and can not be set to None') if not check_type(value,LIST(2,None,'REAL', scope = schema_scope)): self._weights_data = LIST(value) else: self._weights_data = value return property(**locals()) @apply def weights(): def fget( self ): attribute_eval = list_to_array(self.weights_data,0,self.upper_index_on_control_points) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument weights is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (SIZEOF(self.weights_data) == SIZEOF(self.self.b_spline_curve.self.control_points_list)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = curve_weights_positive(self) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY action_request_assignment # #################### class action_request_assignment(BaseEntityClass): '''Entity action_request_assignment definition. :param assigned_action_request :type assigned_action_request:versioned_action_request ''' def __init__( self , assigned_action_request, ): self.assigned_action_request = assigned_action_request @apply def assigned_action_request(): def fget( self ): return self._assigned_action_request def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_action_request is mantatory and can not be set to None') if not check_type(value,versioned_action_request): self._assigned_action_request = versioned_action_request(value) else: self._assigned_action_request = value return property(**locals()) #################### # ENTITY topological_representation_item # #################### class topological_representation_item(representation_item): '''Entity topological_representation_item definition. ''' def __init__( self , inherited0__name , ): representation_item.__init__(self , inherited0__name , ) #################### # ENTITY face_bound # #################### class face_bound(topological_representation_item): '''Entity face_bound definition. :param bound :type bound:loop :param orientation :type orientation:BOOLEAN ''' def __init__( self , inherited0__name , bound,orientation, ): topological_representation_item.__init__(self , inherited0__name , ) self.bound = bound self.orientation = orientation @apply def bound(): def fget( self ): return self._bound def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument bound is mantatory and can not be set to None') if not check_type(value,loop): self._bound = loop(value) else: self._bound = value return property(**locals()) @apply def orientation(): def fget( self ): return self._orientation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument orientation is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._orientation = BOOLEAN(value) else: self._orientation = value return property(**locals()) #################### # ENTITY length_measure_with_unit # #################### class length_measure_with_unit(measure_with_unit): '''Entity length_measure_with_unit definition. ''' def __init__( self , inherited0__value_component , inherited1__unit_component , ): measure_with_unit.__init__(self , inherited0__value_component , inherited1__unit_component , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.LENGTH_UNIT' == TYPEOF(self.self.measure_with_unit.self.unit_component)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY dated_effectivity # #################### class dated_effectivity(effectivity): '''Entity dated_effectivity definition. :param effectivity_start_date :type effectivity_start_date:date_and_time :param effectivity_end_date :type effectivity_end_date:date_and_time ''' def __init__( self , inherited0__id , effectivity_start_date,effectivity_end_date, ): effectivity.__init__(self , inherited0__id , ) self.effectivity_start_date = effectivity_start_date self.effectivity_end_date = effectivity_end_date @apply def effectivity_start_date(): def fget( self ): return self._effectivity_start_date def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument effectivity_start_date is mantatory and can not be set to None') if not check_type(value,date_and_time): self._effectivity_start_date = date_and_time(value) else: self._effectivity_start_date = value return property(**locals()) @apply def effectivity_end_date(): def fget( self ): return self._effectivity_end_date def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,date_and_time): self._effectivity_end_date = date_and_time(value) else: self._effectivity_end_date = value else: self._effectivity_end_date = value return property(**locals()) #################### # ENTITY direction # #################### class direction(geometric_representation_item): '''Entity direction definition. :param direction_ratios :type direction_ratios:LIST(2,3,'REAL', scope = schema_scope) ''' def __init__( self , inherited0__name , direction_ratios, ): geometric_representation_item.__init__(self , inherited0__name , ) self.direction_ratios = direction_ratios @apply def direction_ratios(): def fget( self ): return self._direction_ratios def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument direction_ratios is mantatory and can not be set to None') if not check_type(value,LIST(2,3,'REAL', scope = schema_scope)): self._direction_ratios = LIST(value) else: self._direction_ratios = value return property(**locals()) def wr1(self): eval_wr1_wr = (SIZEOF(None) > 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY next_assembly_usage_occurrence # #################### class next_assembly_usage_occurrence(assembly_component_usage): '''Entity next_assembly_usage_occurrence definition. ''' def __init__( self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , inherited5__reference_designator , ): assembly_component_usage.__init__(self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , inherited5__reference_designator , ) #################### # ENTITY edge # #################### class edge(topological_representation_item): '''Entity edge definition. :param edge_start :type edge_start:vertex :param edge_end :type edge_end:vertex ''' def __init__( self , inherited0__name , edge_start,edge_end, ): topological_representation_item.__init__(self , inherited0__name , ) self.edge_start = edge_start self.edge_end = edge_end @apply def edge_start(): def fget( self ): return self._edge_start def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument edge_start is mantatory and can not be set to None') if not check_type(value,vertex): self._edge_start = vertex(value) else: self._edge_start = value return property(**locals()) @apply def edge_end(): def fget( self ): return self._edge_end def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument edge_end is mantatory and can not be set to None') if not check_type(value,vertex): self._edge_end = vertex(value) else: self._edge_end = value return property(**locals()) #################### # ENTITY oriented_edge # #################### class oriented_edge(edge): '''Entity oriented_edge definition. :param edge_element :type edge_element:edge :param orientation :type orientation:BOOLEAN :param edge_edge_start :type edge_edge_start:vertex :param edge_edge_end :type edge_edge_end:vertex ''' def __init__( self , inherited0__name , inherited1__edge_start , inherited2__edge_end , edge_element,orientation, ): edge.__init__(self , inherited0__name , inherited1__edge_start , inherited2__edge_end , ) self.edge_element = edge_element self.orientation = orientation @apply def edge_element(): def fget( self ): return self._edge_element def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument edge_element is mantatory and can not be set to None') if not check_type(value,edge): self._edge_element = edge(value) else: self._edge_element = value return property(**locals()) @apply def orientation(): def fget( self ): return self._orientation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument orientation is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._orientation = BOOLEAN(value) else: self._orientation = value return property(**locals()) @apply def edge_edge_start(): def fget( self ): attribute_eval = boolean_choose(self.self.orientation,self.self.edge_element.self.edge_start,self.self.edge_element.self.edge_end) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument edge_edge_start is DERIVED. It is computed and can not be set to any value') return property(**locals()) @apply def edge_edge_end(): def fget( self ): attribute_eval = boolean_choose(self.self.orientation,self.self.edge_element.self.edge_end,self.self.edge_element.self.edge_start) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument edge_edge_end is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ( not ('CONFIG_CONTROL_DESIGN.ORIENTED_EDGE' == TYPEOF(self.self.edge_element))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY person # #################### class person(BaseEntityClass): '''Entity person definition. :param id :type id:identifier :param last_name :type last_name:label :param first_name :type first_name:label :param middle_names :type middle_names:LIST(1,None,'STRING', scope = schema_scope) :param prefix_titles :type prefix_titles:LIST(1,None,'STRING', scope = schema_scope) :param suffix_titles :type suffix_titles:LIST(1,None,'STRING', scope = schema_scope) ''' def __init__( self , id,last_name,first_name,middle_names,prefix_titles,suffix_titles, ): self.id = id self.last_name = last_name self.first_name = first_name self.middle_names = middle_names self.prefix_titles = prefix_titles self.suffix_titles = suffix_titles @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) @apply def last_name(): def fget( self ): return self._last_name def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._last_name = label(value) else: self._last_name = value else: self._last_name = value return property(**locals()) @apply def first_name(): def fget( self ): return self._first_name def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._first_name = label(value) else: self._first_name = value else: self._first_name = value return property(**locals()) @apply def middle_names(): def fget( self ): return self._middle_names def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,LIST(1,None,'STRING', scope = schema_scope)): self._middle_names = LIST(value) else: self._middle_names = value else: self._middle_names = value return property(**locals()) @apply def prefix_titles(): def fget( self ): return self._prefix_titles def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,LIST(1,None,'STRING', scope = schema_scope)): self._prefix_titles = LIST(value) else: self._prefix_titles = value else: self._prefix_titles = value return property(**locals()) @apply def suffix_titles(): def fget( self ): return self._suffix_titles def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,LIST(1,None,'STRING', scope = schema_scope)): self._suffix_titles = LIST(value) else: self._suffix_titles = value else: self._suffix_titles = value return property(**locals()) def wr1(self): eval_wr1_wr = (EXISTS(self.last_name) or EXISTS(self.first_name)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY document # #################### class document(BaseEntityClass): '''Entity document definition. :param id :type id:identifier :param name :type name:label :param description :type description:text :param kind :type kind:document_type ''' def __init__( self , id,name,description,kind, ): self.id = id self.name = name self.description = description self.kind = kind @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def kind(): def fget( self ): return self._kind def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument kind is mantatory and can not be set to None') if not check_type(value,document_type): self._kind = document_type(value) else: self._kind = value return property(**locals()) #################### # ENTITY document_with_class # #################### class document_with_class(document): '''Entity document_with_class definition. :param class_ :type class_:identifier ''' def __init__( self , inherited0__id , inherited1__name , inherited2__description , inherited3__kind , class_, ): document.__init__(self , inherited0__id , inherited1__name , inherited2__description , inherited3__kind , ) self.class_ = class_ @apply def class_(): def fget( self ): return self._class_ def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument class_ is mantatory and can not be set to None') if not check_type(value,identifier): self._class_ = identifier(value) else: self._class_ = value return property(**locals()) #################### # ENTITY conversion_based_unit # #################### class conversion_based_unit(named_unit): '''Entity conversion_based_unit definition. :param name :type name:label :param conversion_factor :type conversion_factor:measure_with_unit ''' def __init__( self , inherited0__dimensions , name,conversion_factor, ): named_unit.__init__(self , inherited0__dimensions , ) self.name = name self.conversion_factor = conversion_factor @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def conversion_factor(): def fget( self ): return self._conversion_factor def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument conversion_factor is mantatory and can not be set to None') if not check_type(value,measure_with_unit): self._conversion_factor = measure_with_unit(value) else: self._conversion_factor = value return property(**locals()) #################### # ENTITY point # #################### class point(geometric_representation_item): '''Entity point definition. ''' def __init__( self , inherited0__name , ): geometric_representation_item.__init__(self , inherited0__name , ) #################### # ENTITY point_on_surface # #################### class point_on_surface(point): '''Entity point_on_surface definition. :param basis_surface :type basis_surface:surface :param point_parameter_u :type point_parameter_u:parameter_value :param point_parameter_v :type point_parameter_v:parameter_value ''' def __init__( self , inherited0__name , basis_surface,point_parameter_u,point_parameter_v, ): point.__init__(self , inherited0__name , ) self.basis_surface = basis_surface self.point_parameter_u = point_parameter_u self.point_parameter_v = point_parameter_v @apply def basis_surface(): def fget( self ): return self._basis_surface def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis_surface is mantatory and can not be set to None') if not check_type(value,surface): self._basis_surface = surface(value) else: self._basis_surface = value return property(**locals()) @apply def point_parameter_u(): def fget( self ): return self._point_parameter_u def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument point_parameter_u is mantatory and can not be set to None') if not check_type(value,parameter_value): self._point_parameter_u = parameter_value(value) else: self._point_parameter_u = value return property(**locals()) @apply def point_parameter_v(): def fget( self ): return self._point_parameter_v def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument point_parameter_v is mantatory and can not be set to None') if not check_type(value,parameter_value): self._point_parameter_v = parameter_value(value) else: self._point_parameter_v = value return property(**locals()) #################### # ENTITY product_definition_formation # #################### class product_definition_formation(BaseEntityClass): '''Entity product_definition_formation definition. :param id :type id:identifier :param description :type description:text :param of_product :type of_product:product ''' def __init__( self , id,description,of_product, ): self.id = id self.description = description self.of_product = of_product @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def of_product(): def fget( self ): return self._of_product def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument of_product is mantatory and can not be set to None') if not check_type(value,product): self._of_product = product(value) else: self._of_product = value return property(**locals()) #################### # ENTITY person_and_organization_assignment # #################### class person_and_organization_assignment(BaseEntityClass): '''Entity person_and_organization_assignment definition. :param assigned_person_and_organization :type assigned_person_and_organization:person_and_organization :param role :type role:person_and_organization_role ''' def __init__( self , assigned_person_and_organization,role, ): self.assigned_person_and_organization = assigned_person_and_organization self.role = role @apply def assigned_person_and_organization(): def fget( self ): return self._assigned_person_and_organization def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_person_and_organization is mantatory and can not be set to None') if not check_type(value,person_and_organization): self._assigned_person_and_organization = person_and_organization(value) else: self._assigned_person_and_organization = value return property(**locals()) @apply def role(): def fget( self ): return self._role def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument role is mantatory and can not be set to None') if not check_type(value,person_and_organization_role): self._role = person_and_organization_role(value) else: self._role = value return property(**locals()) #################### # ENTITY cc_design_person_and_organization_assignment # #################### class cc_design_person_and_organization_assignment(person_and_organization_assignment): '''Entity cc_design_person_and_organization_assignment definition. :param items :type items:SET(1,None,'person_organization_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_person_and_organization , inherited1__role , items, ): person_and_organization_assignment.__init__(self , inherited0__assigned_person_and_organization , inherited1__role , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'person_organization_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) def wr1(self): eval_wr1_wr = cc_design_person_and_organization_correlation(self) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY offset_curve_3d # #################### class offset_curve_3d(curve): '''Entity offset_curve_3d definition. :param basis_curve :type basis_curve:curve :param distance :type distance:length_measure :param self_intersect :type self_intersect:LOGICAL :param ref_direction :type ref_direction:direction ''' def __init__( self , inherited0__name , basis_curve,distance,self_intersect,ref_direction, ): curve.__init__(self , inherited0__name , ) self.basis_curve = basis_curve self.distance = distance self.self_intersect = self_intersect self.ref_direction = ref_direction @apply def basis_curve(): def fget( self ): return self._basis_curve def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis_curve is mantatory and can not be set to None') if not check_type(value,curve): self._basis_curve = curve(value) else: self._basis_curve = value return property(**locals()) @apply def distance(): def fget( self ): return self._distance def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument distance is mantatory and can not be set to None') if not check_type(value,length_measure): self._distance = length_measure(value) else: self._distance = value return property(**locals()) @apply def self_intersect(): def fget( self ): return self._self_intersect def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument self_intersect is mantatory and can not be set to None') if not check_type(value,LOGICAL): self._self_intersect = LOGICAL(value) else: self._self_intersect = value return property(**locals()) @apply def ref_direction(): def fget( self ): return self._ref_direction def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument ref_direction is mantatory and can not be set to None') if not check_type(value,direction): self._ref_direction = direction(value) else: self._ref_direction = value return property(**locals()) def wr1(self): eval_wr1_wr = ((self.basis_curve.self.dim == 3) and (self.ref_direction.self.dim == 3)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY approval # #################### class approval(BaseEntityClass): '''Entity approval definition. :param status :type status:approval_status :param level :type level:label ''' def __init__( self , status,level, ): self.status = status self.level = level @apply def status(): def fget( self ): return self._status def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument status is mantatory and can not be set to None') if not check_type(value,approval_status): self._status = approval_status(value) else: self._status = value return property(**locals()) @apply def level(): def fget( self ): return self._level def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument level is mantatory and can not be set to None') if not check_type(value,label): self._level = label(value) else: self._level = value return property(**locals()) #################### # ENTITY composite_curve # #################### class composite_curve(bounded_curve): '''Entity composite_curve definition. :param segments :type segments:LIST(1,None,'composite_curve_segment', scope = schema_scope) :param self_intersect :type self_intersect:LOGICAL :param n_segments :type n_segments:INTEGER :param closed_curve :type closed_curve:LOGICAL ''' def __init__( self , inherited0__name , segments,self_intersect, ): bounded_curve.__init__(self , inherited0__name , ) self.segments = segments self.self_intersect = self_intersect @apply def segments(): def fget( self ): return self._segments def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument segments is mantatory and can not be set to None') if not check_type(value,LIST(1,None,'composite_curve_segment', scope = schema_scope)): self._segments = LIST(value) else: self._segments = value return property(**locals()) @apply def self_intersect(): def fget( self ): return self._self_intersect def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument self_intersect is mantatory and can not be set to None') if not check_type(value,LOGICAL): self._self_intersect = LOGICAL(value) else: self._self_intersect = value return property(**locals()) @apply def n_segments(): def fget( self ): attribute_eval = SIZEOF(self.segments) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument n_segments is DERIVED. It is computed and can not be set to any value') return property(**locals()) @apply def closed_curve(): def fget( self ): attribute_eval = (self.segments[self.n_segments].self.transition != discontinuous) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument closed_curve is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ((( not self.closed_curve) and (SIZEOF(None) == 1)) or (self.closed_curve and (SIZEOF(None) == 0))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY composite_curve_on_surface # #################### class composite_curve_on_surface(composite_curve): '''Entity composite_curve_on_surface definition. :param basis_surface :type basis_surface:SET(0,2,'surface', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__segments , inherited2__self_intersect , ): composite_curve.__init__(self , inherited0__name , inherited1__segments , inherited2__self_intersect , ) @apply def basis_surface(): def fget( self ): attribute_eval = get_basis_surface(self) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument basis_surface is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (SIZEOF(self.basis_surface) > 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = constraints_composite_curve_on_surface(self) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY boundary_curve # #################### class boundary_curve(composite_curve_on_surface): '''Entity boundary_curve definition. ''' def __init__( self , inherited0__name , inherited1__segments , inherited2__self_intersect , ): composite_curve_on_surface.__init__(self , inherited0__name , inherited1__segments , inherited2__self_intersect , ) def wr1(self): eval_wr1_wr = self.self.composite_curve.self.closed_curve if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY representation_context # #################### class representation_context(BaseEntityClass): '''Entity representation_context definition. :param context_identifier :type context_identifier:identifier :param context_type :type context_type:text :param representations_in_context :type representations_in_context:SET(1,None,'representation', scope = schema_scope) ''' def __init__( self , context_identifier,context_type, ): self.context_identifier = context_identifier self.context_type = context_type @apply def context_identifier(): def fget( self ): return self._context_identifier def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument context_identifier is mantatory and can not be set to None') if not check_type(value,identifier): self._context_identifier = identifier(value) else: self._context_identifier = value return property(**locals()) @apply def context_type(): def fget( self ): return self._context_type def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument context_type is mantatory and can not be set to None') if not check_type(value,text): self._context_type = text(value) else: self._context_type = value return property(**locals()) @apply def representations_in_context(): def fget( self ): return self._representations_in_context def fset( self, value ): # INVERSE argument raise AssertionError('Argument representations_in_context is INVERSE. It is computed and can not be set to any value') return property(**locals()) #################### # ENTITY geometric_representation_context # #################### class geometric_representation_context(representation_context): '''Entity geometric_representation_context definition. :param coordinate_space_dimension :type coordinate_space_dimension:dimension_count ''' def __init__( self , inherited0__context_identifier , inherited1__context_type , coordinate_space_dimension, ): representation_context.__init__(self , inherited0__context_identifier , inherited1__context_type , ) self.coordinate_space_dimension = coordinate_space_dimension @apply def coordinate_space_dimension(): def fget( self ): return self._coordinate_space_dimension def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument coordinate_space_dimension is mantatory and can not be set to None') if not check_type(value,dimension_count): self._coordinate_space_dimension = dimension_count(value) else: self._coordinate_space_dimension = value return property(**locals()) #################### # ENTITY action_status # #################### class action_status(BaseEntityClass): '''Entity action_status definition. :param status :type status:label :param assigned_action :type assigned_action:executed_action ''' def __init__( self , status,assigned_action, ): self.status = status self.assigned_action = assigned_action @apply def status(): def fget( self ): return self._status def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument status is mantatory and can not be set to None') if not check_type(value,label): self._status = label(value) else: self._status = value return property(**locals()) @apply def assigned_action(): def fget( self ): return self._assigned_action def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_action is mantatory and can not be set to None') if not check_type(value,executed_action): self._assigned_action = executed_action(value) else: self._assigned_action = value return property(**locals()) #################### # ENTITY application_context # #################### class application_context(BaseEntityClass): '''Entity application_context definition. :param application :type application:text :param context_elements :type context_elements:SET(1,None,'application_context_element', scope = schema_scope) ''' def __init__( self , application, ): self.application = application @apply def application(): def fget( self ): return self._application def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument application is mantatory and can not be set to None') if not check_type(value,text): self._application = text(value) else: self._application = value return property(**locals()) @apply def context_elements(): def fget( self ): return self._context_elements def fset( self, value ): # INVERSE argument raise AssertionError('Argument context_elements is INVERSE. It is computed and can not be set to any value') return property(**locals()) #################### # ENTITY change_request # #################### class change_request(action_request_assignment): '''Entity change_request definition. :param items :type items:SET(1,None,'change_request_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_action_request , items, ): action_request_assignment.__init__(self , inherited0__assigned_action_request , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'change_request_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) #################### # ENTITY date_and_time # #################### class date_and_time(BaseEntityClass): '''Entity date_and_time definition. :param date_component :type date_component:date :param time_component :type time_component:local_time ''' def __init__( self , date_component,time_component, ): self.date_component = date_component self.time_component = time_component @apply def date_component(): def fget( self ): return self._date_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument date_component is mantatory and can not be set to None') if not check_type(value,date): self._date_component = date(value) else: self._date_component = value return property(**locals()) @apply def time_component(): def fget( self ): return self._time_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument time_component is mantatory and can not be set to None') if not check_type(value,local_time): self._time_component = local_time(value) else: self._time_component = value return property(**locals()) #################### # ENTITY approval_date_time # #################### class approval_date_time(BaseEntityClass): '''Entity approval_date_time definition. :param date_time :type date_time:date_time_select :param dated_approval :type dated_approval:approval ''' def __init__( self , date_time,dated_approval, ): self.date_time = date_time self.dated_approval = dated_approval @apply def date_time(): def fget( self ): return self._date_time def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument date_time is mantatory and can not be set to None') if not check_type(value,date_time_select): self._date_time = date_time_select(value) else: self._date_time = value return property(**locals()) @apply def dated_approval(): def fget( self ): return self._dated_approval def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument dated_approval is mantatory and can not be set to None') if not check_type(value,approval): self._dated_approval = approval(value) else: self._dated_approval = value return property(**locals()) #################### # ENTITY approval_role # #################### class approval_role(BaseEntityClass): '''Entity approval_role definition. :param role :type role:label ''' def __init__( self , role, ): self.role = role @apply def role(): def fget( self ): return self._role def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument role is mantatory and can not be set to None') if not check_type(value,label): self._role = label(value) else: self._role = value return property(**locals()) #################### # ENTITY application_context_element # #################### class application_context_element(BaseEntityClass): '''Entity application_context_element definition. :param name :type name:label :param frame_of_reference :type frame_of_reference:application_context ''' def __init__( self , name,frame_of_reference, ): self.name = name self.frame_of_reference = frame_of_reference @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def frame_of_reference(): def fget( self ): return self._frame_of_reference def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument frame_of_reference is mantatory and can not be set to None') if not check_type(value,application_context): self._frame_of_reference = application_context(value) else: self._frame_of_reference = value return property(**locals()) #################### # ENTITY product_context # #################### class product_context(application_context_element): '''Entity product_context definition. :param discipline_type :type discipline_type:label ''' def __init__( self , inherited0__name , inherited1__frame_of_reference , discipline_type, ): application_context_element.__init__(self , inherited0__name , inherited1__frame_of_reference , ) self.discipline_type = discipline_type @apply def discipline_type(): def fget( self ): return self._discipline_type def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument discipline_type is mantatory and can not be set to None') if not check_type(value,label): self._discipline_type = label(value) else: self._discipline_type = value return property(**locals()) #################### # ENTITY elementary_surface # #################### class elementary_surface(surface): '''Entity elementary_surface definition. :param position :type position:axis2_placement_3d ''' def __init__( self , inherited0__name , position, ): surface.__init__(self , inherited0__name , ) self.position = position @apply def position(): def fget( self ): return self._position def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument position is mantatory and can not be set to None') if not check_type(value,axis2_placement_3d): self._position = axis2_placement_3d(value) else: self._position = value return property(**locals()) #################### # ENTITY spherical_surface # #################### class spherical_surface(elementary_surface): '''Entity spherical_surface definition. :param radius :type radius:positive_length_measure ''' def __init__( self , inherited0__name , inherited1__position , radius, ): elementary_surface.__init__(self , inherited0__name , inherited1__position , ) self.radius = radius @apply def radius(): def fget( self ): return self._radius def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument radius is mantatory and can not be set to None') if not check_type(value,positive_length_measure): self._radius = positive_length_measure(value) else: self._radius = value return property(**locals()) #################### # ENTITY application_protocol_definition # #################### class application_protocol_definition(BaseEntityClass): '''Entity application_protocol_definition definition. :param status :type status:label :param application_interpreted_model_schema_name :type application_interpreted_model_schema_name:label :param application_protocol_year :type application_protocol_year:year_number :param application :type application:application_context ''' def __init__( self , status,application_interpreted_model_schema_name,application_protocol_year,application, ): self.status = status self.application_interpreted_model_schema_name = application_interpreted_model_schema_name self.application_protocol_year = application_protocol_year self.application = application @apply def status(): def fget( self ): return self._status def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument status is mantatory and can not be set to None') if not check_type(value,label): self._status = label(value) else: self._status = value return property(**locals()) @apply def application_interpreted_model_schema_name(): def fget( self ): return self._application_interpreted_model_schema_name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument application_interpreted_model_schema_name is mantatory and can not be set to None') if not check_type(value,label): self._application_interpreted_model_schema_name = label(value) else: self._application_interpreted_model_schema_name = value return property(**locals()) @apply def application_protocol_year(): def fget( self ): return self._application_protocol_year def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument application_protocol_year is mantatory and can not be set to None') if not check_type(value,year_number): self._application_protocol_year = year_number(value) else: self._application_protocol_year = value return property(**locals()) @apply def application(): def fget( self ): return self._application def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument application is mantatory and can not be set to None') if not check_type(value,application_context): self._application = application_context(value) else: self._application = value return property(**locals()) #################### # ENTITY specified_higher_usage_occurrence # #################### class specified_higher_usage_occurrence(assembly_component_usage): '''Entity specified_higher_usage_occurrence definition. :param upper_usage :type upper_usage:assembly_component_usage :param next_usage :type next_usage:next_assembly_usage_occurrence ''' def __init__( self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , inherited5__reference_designator , upper_usage,next_usage, ): assembly_component_usage.__init__(self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , inherited5__reference_designator , ) self.upper_usage = upper_usage self.next_usage = next_usage @apply def upper_usage(): def fget( self ): return self._upper_usage def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument upper_usage is mantatory and can not be set to None') if not check_type(value,assembly_component_usage): self._upper_usage = assembly_component_usage(value) else: self._upper_usage = value return property(**locals()) @apply def next_usage(): def fget( self ): return self._next_usage def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument next_usage is mantatory and can not be set to None') if not check_type(value,next_assembly_usage_occurrence): self._next_usage = next_assembly_usage_occurrence(value) else: self._next_usage = value return property(**locals()) def wr1(self): eval_wr1_wr = (self != self.upper_usage) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (self.self.product_definition_relationship.self.relating_product_definition == self.upper_usage.self.relating_product_definition) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (self.self.product_definition_relationship.self.related_product_definition == self.next_usage.self.related_product_definition) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (self.upper_usage.self.related_product_definition == self.next_usage.self.relating_product_definition) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr def wr5(self): eval_wr5_wr = ( not ('CONFIG_CONTROL_DESIGN.PROMISSORY_USAGE_OCCURRENCE' == TYPEOF(self.upper_usage))) if not eval_wr5_wr: raise AssertionError('Rule wr5 violated') else: return eval_wr5_wr #################### # ENTITY product_definition_formation_with_specified_source # #################### class product_definition_formation_with_specified_source(product_definition_formation): '''Entity product_definition_formation_with_specified_source definition. :param make_or_buy :type make_or_buy:source ''' def __init__( self , inherited0__id , inherited1__description , inherited2__of_product , make_or_buy, ): product_definition_formation.__init__(self , inherited0__id , inherited1__description , inherited2__of_product , ) self.make_or_buy = make_or_buy @apply def make_or_buy(): def fget( self ): return self._make_or_buy def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument make_or_buy is mantatory and can not be set to None') if not check_type(value,source): self._make_or_buy = source(value) else: self._make_or_buy = value return property(**locals()) #################### # ENTITY action_request_solution # #################### class action_request_solution(BaseEntityClass): '''Entity action_request_solution definition. :param method :type method:action_method :param request :type request:versioned_action_request ''' def __init__( self , method,request, ): self.method = method self.request = request @apply def method(): def fget( self ): return self._method def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument method is mantatory and can not be set to None') if not check_type(value,action_method): self._method = action_method(value) else: self._method = value return property(**locals()) @apply def request(): def fget( self ): return self._request def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument request is mantatory and can not be set to None') if not check_type(value,versioned_action_request): self._request = versioned_action_request(value) else: self._request = value return property(**locals()) #################### # ENTITY uncertainty_measure_with_unit # #################### class uncertainty_measure_with_unit(measure_with_unit): '''Entity uncertainty_measure_with_unit definition. :param name :type name:label :param description :type description:text ''' def __init__( self , inherited0__value_component , inherited1__unit_component , name,description, ): measure_with_unit.__init__(self , inherited0__value_component , inherited1__unit_component , ) self.name = name self.description = description @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) def wr1(self): eval_wr1_wr = valid_measure_value(self.self.measure_with_unit.self.value_component) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY edge_based_wireframe_model # #################### class edge_based_wireframe_model(geometric_representation_item): '''Entity edge_based_wireframe_model definition. :param ebwm_boundary :type ebwm_boundary:SET(1,None,'connected_edge_set', scope = schema_scope) ''' def __init__( self , inherited0__name , ebwm_boundary, ): geometric_representation_item.__init__(self , inherited0__name , ) self.ebwm_boundary = ebwm_boundary @apply def ebwm_boundary(): def fget( self ): return self._ebwm_boundary def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument ebwm_boundary is mantatory and can not be set to None') if not check_type(value,SET(1,None,'connected_edge_set', scope = schema_scope)): self._ebwm_boundary = SET(value) else: self._ebwm_boundary = value return property(**locals()) #################### # ENTITY path # #################### class path(topological_representation_item): '''Entity path definition. :param edge_list :type edge_list:LIST(1,None,'oriented_edge', scope = schema_scope) ''' def __init__( self , inherited0__name , edge_list, ): topological_representation_item.__init__(self , inherited0__name , ) self.edge_list = edge_list @apply def edge_list(): def fget( self ): return self._edge_list def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument edge_list is mantatory and can not be set to None') if not check_type(value,LIST(1,None,'oriented_edge', scope = schema_scope)): self._edge_list = LIST(value) else: self._edge_list = value return property(**locals()) def wr1(self): eval_wr1_wr = path_head_to_tail(self) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY connected_face_set # #################### class connected_face_set(topological_representation_item): '''Entity connected_face_set definition. :param cfs_faces :type cfs_faces:SET(1,None,'face', scope = schema_scope) ''' def __init__( self , inherited0__name , cfs_faces, ): topological_representation_item.__init__(self , inherited0__name , ) self.cfs_faces = cfs_faces @apply def cfs_faces(): def fget( self ): return self._cfs_faces def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument cfs_faces is mantatory and can not be set to None') if not check_type(value,SET(1,None,'face', scope = schema_scope)): self._cfs_faces = SET(value) else: self._cfs_faces = value return property(**locals()) #################### # ENTITY open_shell # #################### class open_shell(connected_face_set): '''Entity open_shell definition. ''' def __init__( self , inherited0__name , inherited1__cfs_faces , ): connected_face_set.__init__(self , inherited0__name , inherited1__cfs_faces , ) #################### # ENTITY oriented_open_shell # #################### class oriented_open_shell(open_shell): '''Entity oriented_open_shell definition. :param open_shell_element :type open_shell_element:open_shell :param orientation :type orientation:BOOLEAN :param connected_face_set_cfs_faces :type connected_face_set_cfs_faces:SET(1,None,'face', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__cfs_faces , open_shell_element,orientation, ): open_shell.__init__(self , inherited0__name , inherited1__cfs_faces , ) self.open_shell_element = open_shell_element self.orientation = orientation @apply def open_shell_element(): def fget( self ): return self._open_shell_element def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument open_shell_element is mantatory and can not be set to None') if not check_type(value,open_shell): self._open_shell_element = open_shell(value) else: self._open_shell_element = value return property(**locals()) @apply def orientation(): def fget( self ): return self._orientation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument orientation is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._orientation = BOOLEAN(value) else: self._orientation = value return property(**locals()) @apply def connected_face_set_cfs_faces(): def fget( self ): attribute_eval = conditional_reverse(self.self.orientation,self.self.open_shell_element.self.cfs_faces) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument connected_face_set_cfs_faces is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ( not ('CONFIG_CONTROL_DESIGN.ORIENTED_OPEN_SHELL' == TYPEOF(self.self.open_shell_element))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY solid_angle_unit # #################### class solid_angle_unit(named_unit): '''Entity solid_angle_unit definition. ''' def __init__( self , inherited0__dimensions , ): named_unit.__init__(self , inherited0__dimensions , ) def wr1(self): eval_wr1_wr = (((((((self.self.named_unit.self.dimensions.self.length_exponent == 0) and (self.self.named_unit.self.dimensions.self.mass_exponent == 0)) and (self.self.named_unit.self.dimensions.self.time_exponent == 0)) and (self.self.named_unit.self.dimensions.self.electric_current_exponent == 0)) and (self.self.named_unit.self.dimensions.self.thermodynamic_temperature_exponent == 0)) and (self.self.named_unit.self.dimensions.self.amount_of_substance_exponent == 0)) and (self.self.named_unit.self.dimensions.self.luminous_intensity_exponent == 0)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY coordinated_universal_time_offset # #################### class coordinated_universal_time_offset(BaseEntityClass): '''Entity coordinated_universal_time_offset definition. :param hour_offset :type hour_offset:hour_in_day :param minute_offset :type minute_offset:minute_in_hour :param sense :type sense:ahead_or_behind ''' def __init__( self , hour_offset,minute_offset,sense, ): self.hour_offset = hour_offset self.minute_offset = minute_offset self.sense = sense @apply def hour_offset(): def fget( self ): return self._hour_offset def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument hour_offset is mantatory and can not be set to None') if not check_type(value,hour_in_day): self._hour_offset = hour_in_day(value) else: self._hour_offset = value return property(**locals()) @apply def minute_offset(): def fget( self ): return self._minute_offset def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,minute_in_hour): self._minute_offset = minute_in_hour(value) else: self._minute_offset = value else: self._minute_offset = value return property(**locals()) @apply def sense(): def fget( self ): return self._sense def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument sense is mantatory and can not be set to None') if not check_type(value,ahead_or_behind): self._sense = ahead_or_behind(value) else: self._sense = value return property(**locals()) #################### # ENTITY curve_replica # #################### class curve_replica(curve): '''Entity curve_replica definition. :param parent_curve :type parent_curve:curve :param transformation :type transformation:cartesian_transformation_operator ''' def __init__( self , inherited0__name , parent_curve,transformation, ): curve.__init__(self , inherited0__name , ) self.parent_curve = parent_curve self.transformation = transformation @apply def parent_curve(): def fget( self ): return self._parent_curve def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument parent_curve is mantatory and can not be set to None') if not check_type(value,curve): self._parent_curve = curve(value) else: self._parent_curve = value return property(**locals()) @apply def transformation(): def fget( self ): return self._transformation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument transformation is mantatory and can not be set to None') if not check_type(value,cartesian_transformation_operator): self._transformation = cartesian_transformation_operator(value) else: self._transformation = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.transformation.self.dim == self.parent_curve.self.dim) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = acyclic_curve_replica(self,self.parent_curve) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY quasi_uniform_surface # #################### class quasi_uniform_surface(b_spline_surface): '''Entity quasi_uniform_surface definition. ''' def __init__( self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , ): b_spline_surface.__init__(self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , ) #################### # ENTITY surface_curve # #################### class surface_curve(curve): '''Entity surface_curve definition. :param curve_3d :type curve_3d:curve :param associated_geometry :type associated_geometry:LIST(1,2,'pcurve_or_surface', scope = schema_scope) :param master_representation :type master_representation:preferred_surface_curve_representation :param basis_surface :type basis_surface:SET(1,2,'surface', scope = schema_scope) ''' def __init__( self , inherited0__name , curve_3d,associated_geometry,master_representation, ): curve.__init__(self , inherited0__name , ) self.curve_3d = curve_3d self.associated_geometry = associated_geometry self.master_representation = master_representation @apply def curve_3d(): def fget( self ): return self._curve_3d def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument curve_3d is mantatory and can not be set to None') if not check_type(value,curve): self._curve_3d = curve(value) else: self._curve_3d = value return property(**locals()) @apply def associated_geometry(): def fget( self ): return self._associated_geometry def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument associated_geometry is mantatory and can not be set to None') if not check_type(value,LIST(1,2,'pcurve_or_surface', scope = schema_scope)): self._associated_geometry = LIST(value) else: self._associated_geometry = value return property(**locals()) @apply def master_representation(): def fget( self ): return self._master_representation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument master_representation is mantatory and can not be set to None') if not check_type(value,preferred_surface_curve_representation): self._master_representation = preferred_surface_curve_representation(value) else: self._master_representation = value return property(**locals()) @apply def basis_surface(): def fget( self ): attribute_eval = get_basis_surface(self) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument basis_surface is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (self.curve_3d.self.dim == 3) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(self.associated_geometry[1])) or (self.master_representation != pcurve_s1)) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(self.associated_geometry[2])) or (self.master_representation != pcurve_s2)) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = ( not ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(self.curve_3d))) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr #################### # ENTITY action_request_status # #################### class action_request_status(BaseEntityClass): '''Entity action_request_status definition. :param status :type status:label :param assigned_request :type assigned_request:versioned_action_request ''' def __init__( self , status,assigned_request, ): self.status = status self.assigned_request = assigned_request @apply def status(): def fget( self ): return self._status def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument status is mantatory and can not be set to None') if not check_type(value,label): self._status = label(value) else: self._status = value return property(**locals()) @apply def assigned_request(): def fget( self ): return self._assigned_request def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_request is mantatory and can not be set to None') if not check_type(value,versioned_action_request): self._assigned_request = versioned_action_request(value) else: self._assigned_request = value return property(**locals()) #################### # ENTITY founded_item # #################### class founded_item(BaseEntityClass): '''Entity founded_item definition. ''' # This class does not define any attribute. pass #################### # ENTITY composite_curve_segment # #################### class composite_curve_segment(founded_item): '''Entity composite_curve_segment definition. :param transition :type transition:transition_code :param same_sense :type same_sense:BOOLEAN :param parent_curve :type parent_curve:curve :param using_curves :type using_curves:BAG(1,None,'composite_curve', scope = schema_scope) ''' def __init__( self , transition,same_sense,parent_curve, ): founded_item.__init__(self , ) self.transition = transition self.same_sense = same_sense self.parent_curve = parent_curve @apply def transition(): def fget( self ): return self._transition def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument transition is mantatory and can not be set to None') if not check_type(value,transition_code): self._transition = transition_code(value) else: self._transition = value return property(**locals()) @apply def same_sense(): def fget( self ): return self._same_sense def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument same_sense is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._same_sense = BOOLEAN(value) else: self._same_sense = value return property(**locals()) @apply def parent_curve(): def fget( self ): return self._parent_curve def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument parent_curve is mantatory and can not be set to None') if not check_type(value,curve): self._parent_curve = curve(value) else: self._parent_curve = value return property(**locals()) @apply def using_curves(): def fget( self ): return self._using_curves def fset( self, value ): # INVERSE argument raise AssertionError('Argument using_curves is INVERSE. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.BOUNDED_CURVE' == TYPEOF(self.parent_curve)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY reparametrised_composite_curve_segment # #################### class reparametrised_composite_curve_segment(composite_curve_segment): '''Entity reparametrised_composite_curve_segment definition. :param param_length :type param_length:parameter_value ''' def __init__( self , inherited0__transition , inherited1__same_sense , inherited2__parent_curve , param_length, ): composite_curve_segment.__init__(self , inherited0__transition , inherited1__same_sense , inherited2__parent_curve , ) self.param_length = param_length @apply def param_length(): def fget( self ): return self._param_length def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument param_length is mantatory and can not be set to None') if not check_type(value,parameter_value): self._param_length = parameter_value(value) else: self._param_length = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.param_length > 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY representation_relationship # #################### class representation_relationship(BaseEntityClass): '''Entity representation_relationship definition. :param name :type name:label :param description :type description:text :param rep_1 :type rep_1:representation :param rep_2 :type rep_2:representation ''' def __init__( self , name,description,rep_1,rep_2, ): self.name = name self.description = description self.rep_1 = rep_1 self.rep_2 = rep_2 @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def rep_1(): def fget( self ): return self._rep_1 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument rep_1 is mantatory and can not be set to None') if not check_type(value,representation): self._rep_1 = representation(value) else: self._rep_1 = value return property(**locals()) @apply def rep_2(): def fget( self ): return self._rep_2 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument rep_2 is mantatory and can not be set to None') if not check_type(value,representation): self._rep_2 = representation(value) else: self._rep_2 = value return property(**locals()) #################### # ENTITY representation_relationship_with_transformation # #################### class representation_relationship_with_transformation(representation_relationship): '''Entity representation_relationship_with_transformation definition. :param transformation_operator :type transformation_operator:transformation ''' def __init__( self , inherited0__name , inherited1__description , inherited2__rep_1 , inherited3__rep_2 , transformation_operator, ): representation_relationship.__init__(self , inherited0__name , inherited1__description , inherited2__rep_1 , inherited3__rep_2 , ) self.transformation_operator = transformation_operator @apply def transformation_operator(): def fget( self ): return self._transformation_operator def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument transformation_operator is mantatory and can not be set to None') if not check_type(value,transformation): self._transformation_operator = transformation(value) else: self._transformation_operator = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.self.representation_relationship.self.rep_1.self.context_of_items != self.self.representation_relationship.self.rep_2.self.context_of_items) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY person_and_organization_role # #################### class person_and_organization_role(BaseEntityClass): '''Entity person_and_organization_role definition. :param name :type name:label ''' def __init__( self , name, ): self.name = name @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) #################### # ENTITY quasi_uniform_curve # #################### class quasi_uniform_curve(b_spline_curve): '''Entity quasi_uniform_curve definition. ''' def __init__( self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , ): b_spline_curve.__init__(self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , ) #################### # ENTITY swept_surface # #################### class swept_surface(surface): '''Entity swept_surface definition. :param swept_curve :type swept_curve:curve ''' def __init__( self , inherited0__name , swept_curve, ): surface.__init__(self , inherited0__name , ) self.swept_curve = swept_curve @apply def swept_curve(): def fget( self ): return self._swept_curve def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument swept_curve is mantatory and can not be set to None') if not check_type(value,curve): self._swept_curve = curve(value) else: self._swept_curve = value return property(**locals()) #################### # ENTITY property_definition # #################### class property_definition(BaseEntityClass): '''Entity property_definition definition. :param name :type name:label :param description :type description:text :param definition :type definition:characterized_definition ''' def __init__( self , name,description,definition, ): self.name = name self.description = description self.definition = definition @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def definition(): def fget( self ): return self._definition def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument definition is mantatory and can not be set to None') if not check_type(value,characterized_definition): self._definition = characterized_definition(value) else: self._definition = value return property(**locals()) #################### # ENTITY global_uncertainty_assigned_context # #################### class global_uncertainty_assigned_context(representation_context): '''Entity global_uncertainty_assigned_context definition. :param uncertainty :type uncertainty:SET(1,None,'uncertainty_measure_with_unit', scope = schema_scope) ''' def __init__( self , inherited0__context_identifier , inherited1__context_type , uncertainty, ): representation_context.__init__(self , inherited0__context_identifier , inherited1__context_type , ) self.uncertainty = uncertainty @apply def uncertainty(): def fget( self ): return self._uncertainty def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument uncertainty is mantatory and can not be set to None') if not check_type(value,SET(1,None,'uncertainty_measure_with_unit', scope = schema_scope)): self._uncertainty = SET(value) else: self._uncertainty = value return property(**locals()) #################### # ENTITY organization_relationship # #################### class organization_relationship(BaseEntityClass): '''Entity organization_relationship definition. :param name :type name:label :param description :type description:text :param relating_organization :type relating_organization:organization :param related_organization :type related_organization:organization ''' def __init__( self , name,description,relating_organization,related_organization, ): self.name = name self.description = description self.relating_organization = relating_organization self.related_organization = related_organization @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def relating_organization(): def fget( self ): return self._relating_organization def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument relating_organization is mantatory and can not be set to None') if not check_type(value,organization): self._relating_organization = organization(value) else: self._relating_organization = value return property(**locals()) @apply def related_organization(): def fget( self ): return self._related_organization def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument related_organization is mantatory and can not be set to None') if not check_type(value,organization): self._related_organization = organization(value) else: self._related_organization = value return property(**locals()) #################### # ENTITY parabola # #################### class parabola(conic): '''Entity parabola definition. :param focal_dist :type focal_dist:length_measure ''' def __init__( self , inherited0__name , inherited1__position , focal_dist, ): conic.__init__(self , inherited0__name , inherited1__position , ) self.focal_dist = focal_dist @apply def focal_dist(): def fget( self ): return self._focal_dist def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument focal_dist is mantatory and can not be set to None') if not check_type(value,length_measure): self._focal_dist = length_measure(value) else: self._focal_dist = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.focal_dist != 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY rectangular_composite_surface # #################### class rectangular_composite_surface(bounded_surface): '''Entity rectangular_composite_surface definition. :param segments :type segments:LIST(1,None,LIST(1,None,'surface_patch', scope = schema_scope)) :param n_u :type n_u:INTEGER :param n_v :type n_v:INTEGER ''' def __init__( self , inherited0__name , segments, ): bounded_surface.__init__(self , inherited0__name , ) self.segments = segments @apply def segments(): def fget( self ): return self._segments def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument segments is mantatory and can not be set to None') if not check_type(value,LIST(1,None,LIST(1,None,'surface_patch', scope = schema_scope))): self._segments = LIST(value) else: self._segments = value return property(**locals()) @apply def n_u(): def fget( self ): attribute_eval = SIZEOF(self.segments) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument n_u is DERIVED. It is computed and can not be set to any value') return property(**locals()) @apply def n_v(): def fget( self ): attribute_eval = SIZEOF(self.segments[1]) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument n_v is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ([] == None) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = constraints_rectangular_composite_surface(self) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY lot_effectivity # #################### class lot_effectivity(effectivity): '''Entity lot_effectivity definition. :param effectivity_lot_id :type effectivity_lot_id:identifier :param effectivity_lot_size :type effectivity_lot_size:measure_with_unit ''' def __init__( self , inherited0__id , effectivity_lot_id,effectivity_lot_size, ): effectivity.__init__(self , inherited0__id , ) self.effectivity_lot_id = effectivity_lot_id self.effectivity_lot_size = effectivity_lot_size @apply def effectivity_lot_id(): def fget( self ): return self._effectivity_lot_id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument effectivity_lot_id is mantatory and can not be set to None') if not check_type(value,identifier): self._effectivity_lot_id = identifier(value) else: self._effectivity_lot_id = value return property(**locals()) @apply def effectivity_lot_size(): def fget( self ): return self._effectivity_lot_size def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument effectivity_lot_size is mantatory and can not be set to None') if not check_type(value,measure_with_unit): self._effectivity_lot_size = measure_with_unit(value) else: self._effectivity_lot_size = value return property(**locals()) #################### # ENTITY surface_of_linear_extrusion # #################### class surface_of_linear_extrusion(swept_surface): '''Entity surface_of_linear_extrusion definition. :param extrusion_axis :type extrusion_axis:vector ''' def __init__( self , inherited0__name , inherited1__swept_curve , extrusion_axis, ): swept_surface.__init__(self , inherited0__name , inherited1__swept_curve , ) self.extrusion_axis = extrusion_axis @apply def extrusion_axis(): def fget( self ): return self._extrusion_axis def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument extrusion_axis is mantatory and can not be set to None') if not check_type(value,vector): self._extrusion_axis = vector(value) else: self._extrusion_axis = value return property(**locals()) #################### # ENTITY shell_based_surface_model # #################### class shell_based_surface_model(geometric_representation_item): '''Entity shell_based_surface_model definition. :param sbsm_boundary :type sbsm_boundary:SET(1,None,'shell', scope = schema_scope) ''' def __init__( self , inherited0__name , sbsm_boundary, ): geometric_representation_item.__init__(self , inherited0__name , ) self.sbsm_boundary = sbsm_boundary @apply def sbsm_boundary(): def fget( self ): return self._sbsm_boundary def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument sbsm_boundary is mantatory and can not be set to None') if not check_type(value,SET(1,None,'shell', scope = schema_scope)): self._sbsm_boundary = SET(value) else: self._sbsm_boundary = value return property(**locals()) def wr1(self): eval_wr1_wr = constraints_geometry_shell_based_surface_model(self) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY uniform_curve # #################### class uniform_curve(b_spline_curve): '''Entity uniform_curve definition. ''' def __init__( self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , ): b_spline_curve.__init__(self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , ) #################### # ENTITY bezier_curve # #################### class bezier_curve(b_spline_curve): '''Entity bezier_curve definition. ''' def __init__( self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , ): b_spline_curve.__init__(self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , ) #################### # ENTITY loop # #################### class loop(topological_representation_item): '''Entity loop definition. ''' def __init__( self , inherited0__name , ): topological_representation_item.__init__(self , inherited0__name , ) #################### # ENTITY edge_loop # #################### class edge_loop(loop,path): '''Entity edge_loop definition. :param ne :type ne:INTEGER ''' def __init__( self , inherited0__name , inherited1__name , inherited2__edge_list , ): loop.__init__(self , inherited0__name , ) path.__init__(self , inherited1__name , inherited2__edge_list , ) @apply def ne(): def fget( self ): attribute_eval = SIZEOF(self.self.path.self.edge_list) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument ne is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (self.self.path.self.edge_list[1].self.edge_start == self.self.path.self.edge_list[self.ne].self.edge_end) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY date # #################### class date(BaseEntityClass): '''Entity date definition. :param year_component :type year_component:year_number ''' def __init__( self , year_component, ): self.year_component = year_component @apply def year_component(): def fget( self ): return self._year_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument year_component is mantatory and can not be set to None') if not check_type(value,year_number): self._year_component = year_number(value) else: self._year_component = value return property(**locals()) #################### # ENTITY calendar_date # #################### class calendar_date(date): '''Entity calendar_date definition. :param day_component :type day_component:day_in_month_number :param month_component :type month_component:month_in_year_number ''' def __init__( self , inherited0__year_component , day_component,month_component, ): date.__init__(self , inherited0__year_component , ) self.day_component = day_component self.month_component = month_component @apply def day_component(): def fget( self ): return self._day_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument day_component is mantatory and can not be set to None') if not check_type(value,day_in_month_number): self._day_component = day_in_month_number(value) else: self._day_component = value return property(**locals()) @apply def month_component(): def fget( self ): return self._month_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument month_component is mantatory and can not be set to None') if not check_type(value,month_in_year_number): self._month_component = month_in_year_number(value) else: self._month_component = value return property(**locals()) def wr1(self): eval_wr1_wr = valid_calendar_date(self) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY toroidal_surface # #################### class toroidal_surface(elementary_surface): '''Entity toroidal_surface definition. :param major_radius :type major_radius:positive_length_measure :param minor_radius :type minor_radius:positive_length_measure ''' def __init__( self , inherited0__name , inherited1__position , major_radius,minor_radius, ): elementary_surface.__init__(self , inherited0__name , inherited1__position , ) self.major_radius = major_radius self.minor_radius = minor_radius @apply def major_radius(): def fget( self ): return self._major_radius def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument major_radius is mantatory and can not be set to None') if not check_type(value,positive_length_measure): self._major_radius = positive_length_measure(value) else: self._major_radius = value return property(**locals()) @apply def minor_radius(): def fget( self ): return self._minor_radius def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument minor_radius is mantatory and can not be set to None') if not check_type(value,positive_length_measure): self._minor_radius = positive_length_measure(value) else: self._minor_radius = value return property(**locals()) #################### # ENTITY promissory_usage_occurrence # #################### class promissory_usage_occurrence(assembly_component_usage): '''Entity promissory_usage_occurrence definition. ''' def __init__( self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , inherited5__reference_designator , ): assembly_component_usage.__init__(self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , inherited5__reference_designator , ) #################### # ENTITY approval_assignment # #################### class approval_assignment(BaseEntityClass): '''Entity approval_assignment definition. :param assigned_approval :type assigned_approval:approval ''' def __init__( self , assigned_approval, ): self.assigned_approval = assigned_approval @apply def assigned_approval(): def fget( self ): return self._assigned_approval def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_approval is mantatory and can not be set to None') if not check_type(value,approval): self._assigned_approval = approval(value) else: self._assigned_approval = value return property(**locals()) #################### # ENTITY configuration_item # #################### class configuration_item(BaseEntityClass): '''Entity configuration_item definition. :param id :type id:identifier :param name :type name:label :param description :type description:text :param item_concept :type item_concept:product_concept :param purpose :type purpose:label ''' def __init__( self , id,name,description,item_concept,purpose, ): self.id = id self.name = name self.description = description self.item_concept = item_concept self.purpose = purpose @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,text): self._description = text(value) else: self._description = value else: self._description = value return property(**locals()) @apply def item_concept(): def fget( self ): return self._item_concept def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument item_concept is mantatory and can not be set to None') if not check_type(value,product_concept): self._item_concept = product_concept(value) else: self._item_concept = value return property(**locals()) @apply def purpose(): def fget( self ): return self._purpose def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,label): self._purpose = label(value) else: self._purpose = value else: self._purpose = value return property(**locals()) #################### # ENTITY contract_assignment # #################### class contract_assignment(BaseEntityClass): '''Entity contract_assignment definition. :param assigned_contract :type assigned_contract:contract ''' def __init__( self , assigned_contract, ): self.assigned_contract = assigned_contract @apply def assigned_contract(): def fget( self ): return self._assigned_contract def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_contract is mantatory and can not be set to None') if not check_type(value,contract): self._assigned_contract = contract(value) else: self._assigned_contract = value return property(**locals()) #################### # ENTITY vector # #################### class vector(geometric_representation_item): '''Entity vector definition. :param orientation :type orientation:direction :param magnitude :type magnitude:length_measure ''' def __init__( self , inherited0__name , orientation,magnitude, ): geometric_representation_item.__init__(self , inherited0__name , ) self.orientation = orientation self.magnitude = magnitude @apply def orientation(): def fget( self ): return self._orientation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument orientation is mantatory and can not be set to None') if not check_type(value,direction): self._orientation = direction(value) else: self._orientation = value return property(**locals()) @apply def magnitude(): def fget( self ): return self._magnitude def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument magnitude is mantatory and can not be set to None') if not check_type(value,length_measure): self._magnitude = length_measure(value) else: self._magnitude = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.magnitude >= 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY pcurve # #################### class pcurve(curve): '''Entity pcurve definition. :param basis_surface :type basis_surface:surface :param reference_to_curve :type reference_to_curve:definitional_representation ''' def __init__( self , inherited0__name , basis_surface,reference_to_curve, ): curve.__init__(self , inherited0__name , ) self.basis_surface = basis_surface self.reference_to_curve = reference_to_curve @apply def basis_surface(): def fget( self ): return self._basis_surface def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis_surface is mantatory and can not be set to None') if not check_type(value,surface): self._basis_surface = surface(value) else: self._basis_surface = value return property(**locals()) @apply def reference_to_curve(): def fget( self ): return self._reference_to_curve def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument reference_to_curve is mantatory and can not be set to None') if not check_type(value,definitional_representation): self._reference_to_curve = definitional_representation(value) else: self._reference_to_curve = value return property(**locals()) def wr1(self): eval_wr1_wr = (SIZEOF(self.reference_to_curve.self.representation.self.items) == 1) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = ('CONFIG_CONTROL_DESIGN.CURVE' == TYPEOF(self.reference_to_curve.self.representation.self.items[1])) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (self.reference_to_curve.self.representation.self.items[1].self.geometric_representation_item.self.dim == 2) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr #################### # ENTITY bounded_pcurve # #################### class bounded_pcurve(pcurve,bounded_curve): '''Entity bounded_pcurve definition. ''' def __init__( self , inherited0__name , inherited1__basis_surface , inherited2__reference_to_curve , inherited3__name , ): pcurve.__init__(self , inherited0__name , inherited1__basis_surface , inherited2__reference_to_curve , ) bounded_curve.__init__(self , inherited3__name , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.BOUNDED_CURVE' == TYPEOF(self.self.pcurve.self.reference_to_curve.self.items[1])) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY intersection_curve # #################### class intersection_curve(surface_curve): '''Entity intersection_curve definition. ''' def __init__( self , inherited0__name , inherited1__curve_3d , inherited2__associated_geometry , inherited3__master_representation , ): surface_curve.__init__(self , inherited0__name , inherited1__curve_3d , inherited2__associated_geometry , inherited3__master_representation , ) def wr1(self): eval_wr1_wr = (SIZEOF(self.self.surface_curve.self.associated_geometry) == 2) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (associated_surface(self.self.surface_curve.self.associated_geometry[1]) != associated_surface(self.self.surface_curve.self.associated_geometry[2])) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY trimmed_curve # #################### class trimmed_curve(bounded_curve): '''Entity trimmed_curve definition. :param basis_curve :type basis_curve:curve :param trim_1 :type trim_1:SET(1,2,'trimming_select', scope = schema_scope) :param trim_2 :type trim_2:SET(1,2,'trimming_select', scope = schema_scope) :param sense_agreement :type sense_agreement:BOOLEAN :param master_representation :type master_representation:trimming_preference ''' def __init__( self , inherited0__name , basis_curve,trim_1,trim_2,sense_agreement,master_representation, ): bounded_curve.__init__(self , inherited0__name , ) self.basis_curve = basis_curve self.trim_1 = trim_1 self.trim_2 = trim_2 self.sense_agreement = sense_agreement self.master_representation = master_representation @apply def basis_curve(): def fget( self ): return self._basis_curve def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis_curve is mantatory and can not be set to None') if not check_type(value,curve): self._basis_curve = curve(value) else: self._basis_curve = value return property(**locals()) @apply def trim_1(): def fget( self ): return self._trim_1 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument trim_1 is mantatory and can not be set to None') if not check_type(value,SET(1,2,'trimming_select', scope = schema_scope)): self._trim_1 = SET(value) else: self._trim_1 = value return property(**locals()) @apply def trim_2(): def fget( self ): return self._trim_2 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument trim_2 is mantatory and can not be set to None') if not check_type(value,SET(1,2,'trimming_select', scope = schema_scope)): self._trim_2 = SET(value) else: self._trim_2 = value return property(**locals()) @apply def sense_agreement(): def fget( self ): return self._sense_agreement def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument sense_agreement is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._sense_agreement = BOOLEAN(value) else: self._sense_agreement = value return property(**locals()) @apply def master_representation(): def fget( self ): return self._master_representation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument master_representation is mantatory and can not be set to None') if not check_type(value,trimming_preference): self._master_representation = trimming_preference(value) else: self._master_representation = value return property(**locals()) def wr1(self): eval_wr1_wr = ((HIINDEX(self.trim_1) == 1) or (TYPEOF(self.trim_1[1]) != TYPEOF(self.trim_1[2]))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = ((HIINDEX(self.trim_2) == 1) or (TYPEOF(self.trim_2[1]) != TYPEOF(self.trim_2[2]))) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY product_definition_context # #################### class product_definition_context(application_context_element): '''Entity product_definition_context definition. :param life_cycle_stage :type life_cycle_stage:label ''' def __init__( self , inherited0__name , inherited1__frame_of_reference , life_cycle_stage, ): application_context_element.__init__(self , inherited0__name , inherited1__frame_of_reference , ) self.life_cycle_stage = life_cycle_stage @apply def life_cycle_stage(): def fget( self ): return self._life_cycle_stage def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument life_cycle_stage is mantatory and can not be set to None') if not check_type(value,label): self._life_cycle_stage = label(value) else: self._life_cycle_stage = value return property(**locals()) #################### # ENTITY bounded_surface_curve # #################### class bounded_surface_curve(surface_curve,bounded_curve): '''Entity bounded_surface_curve definition. ''' def __init__( self , inherited0__name , inherited1__curve_3d , inherited2__associated_geometry , inherited3__master_representation , inherited4__name , ): surface_curve.__init__(self , inherited0__name , inherited1__curve_3d , inherited2__associated_geometry , inherited3__master_representation , ) bounded_curve.__init__(self , inherited4__name , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.BOUNDED_CURVE' == TYPEOF(self.self.surface_curve.self.curve_3d)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY item_defined_transformation # #################### class item_defined_transformation(BaseEntityClass): '''Entity item_defined_transformation definition. :param name :type name:label :param description :type description:text :param transform_item_1 :type transform_item_1:representation_item :param transform_item_2 :type transform_item_2:representation_item ''' def __init__( self , name,description,transform_item_1,transform_item_2, ): self.name = name self.description = description self.transform_item_1 = transform_item_1 self.transform_item_2 = transform_item_2 @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def transform_item_1(): def fget( self ): return self._transform_item_1 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument transform_item_1 is mantatory and can not be set to None') if not check_type(value,representation_item): self._transform_item_1 = representation_item(value) else: self._transform_item_1 = value return property(**locals()) @apply def transform_item_2(): def fget( self ): return self._transform_item_2 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument transform_item_2 is mantatory and can not be set to None') if not check_type(value,representation_item): self._transform_item_2 = representation_item(value) else: self._transform_item_2 = value return property(**locals()) #################### # ENTITY action_method # #################### class action_method(BaseEntityClass): '''Entity action_method definition. :param name :type name:label :param description :type description:text :param consequence :type consequence:text :param purpose :type purpose:text ''' def __init__( self , name,description,consequence,purpose, ): self.name = name self.description = description self.consequence = consequence self.purpose = purpose @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def consequence(): def fget( self ): return self._consequence def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument consequence is mantatory and can not be set to None') if not check_type(value,text): self._consequence = text(value) else: self._consequence = value return property(**locals()) @apply def purpose(): def fget( self ): return self._purpose def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument purpose is mantatory and can not be set to None') if not check_type(value,text): self._purpose = text(value) else: self._purpose = value return property(**locals()) #################### # ENTITY product_category_relationship # #################### class product_category_relationship(BaseEntityClass): '''Entity product_category_relationship definition. :param name :type name:label :param description :type description:text :param category :type category:product_category :param sub_category :type sub_category:product_category ''' def __init__( self , name,description,category,sub_category, ): self.name = name self.description = description self.category = category self.sub_category = sub_category @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def category(): def fget( self ): return self._category def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument category is mantatory and can not be set to None') if not check_type(value,product_category): self._category = product_category(value) else: self._category = value return property(**locals()) @apply def sub_category(): def fget( self ): return self._sub_category def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument sub_category is mantatory and can not be set to None') if not check_type(value,product_category): self._sub_category = product_category(value) else: self._sub_category = value return property(**locals()) def wr1(self): eval_wr1_wr = acyclic_product_category_relationship(self,[self.self.sub_category]) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY plane_angle_measure_with_unit # #################### class plane_angle_measure_with_unit(measure_with_unit): '''Entity plane_angle_measure_with_unit definition. ''' def __init__( self , inherited0__value_component , inherited1__unit_component , ): measure_with_unit.__init__(self , inherited0__value_component , inherited1__unit_component , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.PLANE_ANGLE_UNIT' == TYPEOF(self.self.measure_with_unit.self.unit_component)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY vertex # #################### class vertex(topological_representation_item): '''Entity vertex definition. ''' def __init__( self , inherited0__name , ): topological_representation_item.__init__(self , inherited0__name , ) #################### # ENTITY representation_map # #################### class representation_map(BaseEntityClass): '''Entity representation_map definition. :param mapping_origin :type mapping_origin:representation_item :param mapped_representation :type mapped_representation:representation :param map_usage :type map_usage:SET(1,None,'mapped_item', scope = schema_scope) ''' def __init__( self , mapping_origin,mapped_representation, ): self.mapping_origin = mapping_origin self.mapped_representation = mapped_representation @apply def mapping_origin(): def fget( self ): return self._mapping_origin def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument mapping_origin is mantatory and can not be set to None') if not check_type(value,representation_item): self._mapping_origin = representation_item(value) else: self._mapping_origin = value return property(**locals()) @apply def mapped_representation(): def fget( self ): return self._mapped_representation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument mapped_representation is mantatory and can not be set to None') if not check_type(value,representation): self._mapped_representation = representation(value) else: self._mapped_representation = value return property(**locals()) @apply def map_usage(): def fget( self ): return self._map_usage def fset( self, value ): # INVERSE argument raise AssertionError('Argument map_usage is INVERSE. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = item_in_context(self.self.mapping_origin,self.self.mapped_representation.self.context_of_items) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY product_definition_effectivity # #################### class product_definition_effectivity(effectivity): '''Entity product_definition_effectivity definition. :param usage :type usage:product_definition_relationship ''' def __init__( self , inherited0__id , usage, ): effectivity.__init__(self , inherited0__id , ) self.usage = usage @apply def usage(): def fget( self ): return self._usage def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument usage is mantatory and can not be set to None') if not check_type(value,product_definition_relationship): self._usage = product_definition_relationship(value) else: self._usage = value return property(**locals()) #################### # ENTITY configuration_effectivity # #################### class configuration_effectivity(product_definition_effectivity): '''Entity configuration_effectivity definition. :param configuration :type configuration:configuration_design ''' def __init__( self , inherited0__id , inherited1__usage , configuration, ): product_definition_effectivity.__init__(self , inherited0__id , inherited1__usage , ) self.configuration = configuration @apply def configuration(): def fget( self ): return self._configuration def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument configuration is mantatory and can not be set to None') if not check_type(value,configuration_design): self._configuration = configuration_design(value) else: self._configuration = value return property(**locals()) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.PRODUCT_DEFINITION_USAGE' == TYPEOF(self.self.product_definition_effectivity.self.usage)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY ellipse # #################### class ellipse(conic): '''Entity ellipse definition. :param semi_axis_1 :type semi_axis_1:positive_length_measure :param semi_axis_2 :type semi_axis_2:positive_length_measure ''' def __init__( self , inherited0__name , inherited1__position , semi_axis_1,semi_axis_2, ): conic.__init__(self , inherited0__name , inherited1__position , ) self.semi_axis_1 = semi_axis_1 self.semi_axis_2 = semi_axis_2 @apply def semi_axis_1(): def fget( self ): return self._semi_axis_1 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument semi_axis_1 is mantatory and can not be set to None') if not check_type(value,positive_length_measure): self._semi_axis_1 = positive_length_measure(value) else: self._semi_axis_1 = value return property(**locals()) @apply def semi_axis_2(): def fget( self ): return self._semi_axis_2 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument semi_axis_2 is mantatory and can not be set to None') if not check_type(value,positive_length_measure): self._semi_axis_2 = positive_length_measure(value) else: self._semi_axis_2 = value return property(**locals()) #################### # ENTITY context_dependent_unit # #################### class context_dependent_unit(named_unit): '''Entity context_dependent_unit definition. :param name :type name:label ''' def __init__( self , inherited0__dimensions , name, ): named_unit.__init__(self , inherited0__dimensions , ) self.name = name @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) #################### # ENTITY alternate_product_relationship # #################### class alternate_product_relationship(BaseEntityClass): '''Entity alternate_product_relationship definition. :param name :type name:label :param definition :type definition:text :param alternate :type alternate:product :param base :type base:product :param basis :type basis:text ''' def __init__( self , name,definition,alternate,base,basis, ): self.name = name self.definition = definition self.alternate = alternate self.base = base self.basis = basis @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def definition(): def fget( self ): return self._definition def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument definition is mantatory and can not be set to None') if not check_type(value,text): self._definition = text(value) else: self._definition = value return property(**locals()) @apply def alternate(): def fget( self ): return self._alternate def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument alternate is mantatory and can not be set to None') if not check_type(value,product): self._alternate = product(value) else: self._alternate = value return property(**locals()) @apply def base(): def fget( self ): return self._base def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument base is mantatory and can not be set to None') if not check_type(value,product): self._base = product(value) else: self._base = value return property(**locals()) @apply def basis(): def fget( self ): return self._basis def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis is mantatory and can not be set to None') if not check_type(value,text): self._basis = text(value) else: self._basis = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.alternate != self.base) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY document_type # #################### class document_type(BaseEntityClass): '''Entity document_type definition. :param product_data_type :type product_data_type:label ''' def __init__( self , product_data_type, ): self.product_data_type = product_data_type @apply def product_data_type(): def fget( self ): return self._product_data_type def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument product_data_type is mantatory and can not be set to None') if not check_type(value,label): self._product_data_type = label(value) else: self._product_data_type = value return property(**locals()) #################### # ENTITY document_reference # #################### class document_reference(BaseEntityClass): '''Entity document_reference definition. :param assigned_document :type assigned_document:document :param source :type source:label ''' def __init__( self , assigned_document,source, ): self.assigned_document = assigned_document self.source = source @apply def assigned_document(): def fget( self ): return self._assigned_document def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_document is mantatory and can not be set to None') if not check_type(value,document): self._assigned_document = document(value) else: self._assigned_document = value return property(**locals()) @apply def source(): def fget( self ): return self._source def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument source is mantatory and can not be set to None') if not check_type(value,label): self._source = label(value) else: self._source = value return property(**locals()) #################### # ENTITY mechanical_context # #################### class mechanical_context(product_context): '''Entity mechanical_context definition. ''' def __init__( self , inherited0__name , inherited1__frame_of_reference , inherited2__discipline_type , ): product_context.__init__(self , inherited0__name , inherited1__frame_of_reference , inherited2__discipline_type , ) def wr1(self): eval_wr1_wr = (self.self.discipline_type == 'mechanical') if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY shell_based_wireframe_model # #################### class shell_based_wireframe_model(geometric_representation_item): '''Entity shell_based_wireframe_model definition. :param sbwm_boundary :type sbwm_boundary:SET(1,None,'shell', scope = schema_scope) ''' def __init__( self , inherited0__name , sbwm_boundary, ): geometric_representation_item.__init__(self , inherited0__name , ) self.sbwm_boundary = sbwm_boundary @apply def sbwm_boundary(): def fget( self ): return self._sbwm_boundary def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument sbwm_boundary is mantatory and can not be set to None') if not check_type(value,SET(1,None,'shell', scope = schema_scope)): self._sbwm_boundary = SET(value) else: self._sbwm_boundary = value return property(**locals()) def wr1(self): eval_wr1_wr = constraints_geometry_shell_based_wireframe_model(self) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY contract # #################### class contract(BaseEntityClass): '''Entity contract definition. :param name :type name:label :param purpose :type purpose:text :param kind :type kind:contract_type ''' def __init__( self , name,purpose,kind, ): self.name = name self.purpose = purpose self.kind = kind @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def purpose(): def fget( self ): return self._purpose def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument purpose is mantatory and can not be set to None') if not check_type(value,text): self._purpose = text(value) else: self._purpose = value return property(**locals()) @apply def kind(): def fget( self ): return self._kind def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument kind is mantatory and can not be set to None') if not check_type(value,contract_type): self._kind = contract_type(value) else: self._kind = value return property(**locals()) #################### # ENTITY dimensional_exponents # #################### class dimensional_exponents(BaseEntityClass): '''Entity dimensional_exponents definition. :param length_exponent :type length_exponent:REAL :param mass_exponent :type mass_exponent:REAL :param time_exponent :type time_exponent:REAL :param electric_current_exponent :type electric_current_exponent:REAL :param thermodynamic_temperature_exponent :type thermodynamic_temperature_exponent:REAL :param amount_of_substance_exponent :type amount_of_substance_exponent:REAL :param luminous_intensity_exponent :type luminous_intensity_exponent:REAL ''' def __init__( self , length_exponent,mass_exponent,time_exponent,electric_current_exponent,thermodynamic_temperature_exponent,amount_of_substance_exponent,luminous_intensity_exponent, ): self.length_exponent = length_exponent self.mass_exponent = mass_exponent self.time_exponent = time_exponent self.electric_current_exponent = electric_current_exponent self.thermodynamic_temperature_exponent = thermodynamic_temperature_exponent self.amount_of_substance_exponent = amount_of_substance_exponent self.luminous_intensity_exponent = luminous_intensity_exponent @apply def length_exponent(): def fget( self ): return self._length_exponent def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument length_exponent is mantatory and can not be set to None') if not check_type(value,REAL): self._length_exponent = REAL(value) else: self._length_exponent = value return property(**locals()) @apply def mass_exponent(): def fget( self ): return self._mass_exponent def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument mass_exponent is mantatory and can not be set to None') if not check_type(value,REAL): self._mass_exponent = REAL(value) else: self._mass_exponent = value return property(**locals()) @apply def time_exponent(): def fget( self ): return self._time_exponent def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument time_exponent is mantatory and can not be set to None') if not check_type(value,REAL): self._time_exponent = REAL(value) else: self._time_exponent = value return property(**locals()) @apply def electric_current_exponent(): def fget( self ): return self._electric_current_exponent def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument electric_current_exponent is mantatory and can not be set to None') if not check_type(value,REAL): self._electric_current_exponent = REAL(value) else: self._electric_current_exponent = value return property(**locals()) @apply def thermodynamic_temperature_exponent(): def fget( self ): return self._thermodynamic_temperature_exponent def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument thermodynamic_temperature_exponent is mantatory and can not be set to None') if not check_type(value,REAL): self._thermodynamic_temperature_exponent = REAL(value) else: self._thermodynamic_temperature_exponent = value return property(**locals()) @apply def amount_of_substance_exponent(): def fget( self ): return self._amount_of_substance_exponent def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument amount_of_substance_exponent is mantatory and can not be set to None') if not check_type(value,REAL): self._amount_of_substance_exponent = REAL(value) else: self._amount_of_substance_exponent = value return property(**locals()) @apply def luminous_intensity_exponent(): def fget( self ): return self._luminous_intensity_exponent def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument luminous_intensity_exponent is mantatory and can not be set to None') if not check_type(value,REAL): self._luminous_intensity_exponent = REAL(value) else: self._luminous_intensity_exponent = value return property(**locals()) #################### # ENTITY start_request # #################### class start_request(action_request_assignment): '''Entity start_request definition. :param items :type items:SET(1,None,'start_request_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_action_request , items, ): action_request_assignment.__init__(self , inherited0__assigned_action_request , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'start_request_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) #################### # ENTITY cc_design_specification_reference # #################### class cc_design_specification_reference(document_reference): '''Entity cc_design_specification_reference definition. :param items :type items:SET(1,None,'specified_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_document , inherited1__source , items, ): document_reference.__init__(self , inherited0__assigned_document , inherited1__source , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'specified_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) #################### # ENTITY supplied_part_relationship # #################### class supplied_part_relationship(product_definition_relationship): '''Entity supplied_part_relationship definition. ''' def __init__( self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , ): product_definition_relationship.__init__(self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , ) #################### # ENTITY context_dependent_shape_representation # #################### class context_dependent_shape_representation(BaseEntityClass): '''Entity context_dependent_shape_representation definition. :param representation_relation :type representation_relation:shape_representation_relationship :param represented_product_relation :type represented_product_relation:product_definition_shape ''' def __init__( self , representation_relation,represented_product_relation, ): self.representation_relation = representation_relation self.represented_product_relation = represented_product_relation @apply def representation_relation(): def fget( self ): return self._representation_relation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument representation_relation is mantatory and can not be set to None') if not check_type(value,shape_representation_relationship): self._representation_relation = shape_representation_relationship(value) else: self._representation_relation = value return property(**locals()) @apply def represented_product_relation(): def fget( self ): return self._represented_product_relation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument represented_product_relation is mantatory and can not be set to None') if not check_type(value,product_definition_shape): self._represented_product_relation = product_definition_shape(value) else: self._represented_product_relation = value return property(**locals()) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.PRODUCT_DEFINITION_RELATIONSHIP' == TYPEOF(self.self.represented_product_relation.self.definition)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY degenerate_toroidal_surface # #################### class degenerate_toroidal_surface(toroidal_surface): '''Entity degenerate_toroidal_surface definition. :param select_outer :type select_outer:BOOLEAN ''' def __init__( self , inherited0__name , inherited1__position , inherited2__major_radius , inherited3__minor_radius , select_outer, ): toroidal_surface.__init__(self , inherited0__name , inherited1__position , inherited2__major_radius , inherited3__minor_radius , ) self.select_outer = select_outer @apply def select_outer(): def fget( self ): return self._select_outer def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument select_outer is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._select_outer = BOOLEAN(value) else: self._select_outer = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.major_radius < self.minor_radius) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY ordinal_date # #################### class ordinal_date(date): '''Entity ordinal_date definition. :param day_component :type day_component:day_in_year_number ''' def __init__( self , inherited0__year_component , day_component, ): date.__init__(self , inherited0__year_component , ) self.day_component = day_component @apply def day_component(): def fget( self ): return self._day_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument day_component is mantatory and can not be set to None') if not check_type(value,day_in_year_number): self._day_component = day_in_year_number(value) else: self._day_component = value return property(**locals()) def wr1(self): eval_wr1_wr = (((( not leap_year(self.self.year_component)) and (1 <= self.day_component)) and (self.day_component <= 365)) or ((leap_year(self.self.year_component) and (1 <= self.day_component)) and (self.day_component <= 366))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY face_outer_bound # #################### class face_outer_bound(face_bound): '''Entity face_outer_bound definition. ''' def __init__( self , inherited0__name , inherited1__bound , inherited2__orientation , ): face_bound.__init__(self , inherited0__name , inherited1__bound , inherited2__orientation , ) #################### # ENTITY mass_measure_with_unit # #################### class mass_measure_with_unit(measure_with_unit): '''Entity mass_measure_with_unit definition. ''' def __init__( self , inherited0__value_component , inherited1__unit_component , ): measure_with_unit.__init__(self , inherited0__value_component , inherited1__unit_component , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.MASS_UNIT' == TYPEOF(self.self.measure_with_unit.self.unit_component)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY brep_with_voids # #################### class brep_with_voids(manifold_solid_brep): '''Entity brep_with_voids definition. :param voids :type voids:SET(1,None,'oriented_closed_shell', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__outer , voids, ): manifold_solid_brep.__init__(self , inherited0__name , inherited1__outer , ) self.voids = voids @apply def voids(): def fget( self ): return self._voids def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument voids is mantatory and can not be set to None') if not check_type(value,SET(1,None,'oriented_closed_shell', scope = schema_scope)): self._voids = SET(value) else: self._voids = value return property(**locals()) #################### # ENTITY week_of_year_and_day_date # #################### class week_of_year_and_day_date(date): '''Entity week_of_year_and_day_date definition. :param week_component :type week_component:week_in_year_number :param day_component :type day_component:day_in_week_number ''' def __init__( self , inherited0__year_component , week_component,day_component, ): date.__init__(self , inherited0__year_component , ) self.week_component = week_component self.day_component = day_component @apply def week_component(): def fget( self ): return self._week_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument week_component is mantatory and can not be set to None') if not check_type(value,week_in_year_number): self._week_component = week_in_year_number(value) else: self._week_component = value return property(**locals()) @apply def day_component(): def fget( self ): return self._day_component def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,day_in_week_number): self._day_component = day_in_week_number(value) else: self._day_component = value else: self._day_component = value return property(**locals()) #################### # ENTITY point_on_curve # #################### class point_on_curve(point): '''Entity point_on_curve definition. :param basis_curve :type basis_curve:curve :param point_parameter :type point_parameter:parameter_value ''' def __init__( self , inherited0__name , basis_curve,point_parameter, ): point.__init__(self , inherited0__name , ) self.basis_curve = basis_curve self.point_parameter = point_parameter @apply def basis_curve(): def fget( self ): return self._basis_curve def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis_curve is mantatory and can not be set to None') if not check_type(value,curve): self._basis_curve = curve(value) else: self._basis_curve = value return property(**locals()) @apply def point_parameter(): def fget( self ): return self._point_parameter def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument point_parameter is mantatory and can not be set to None') if not check_type(value,parameter_value): self._point_parameter = parameter_value(value) else: self._point_parameter = value return property(**locals()) #################### # ENTITY shell_based_wireframe_shape_representation # #################### class shell_based_wireframe_shape_representation(shape_representation): '''Entity shell_based_wireframe_shape_representation definition. ''' def __init__( self , inherited0__name , inherited1__items , inherited2__context_of_items , ): shape_representation.__init__(self , inherited0__name , inherited1__items , inherited2__context_of_items , ) def wr1(self): eval_wr1_wr = (SIZEOF(None) == 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(None) >= 1) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(None) == 0) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(None) == 0) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr def wr5(self): eval_wr5_wr = (SIZEOF(None) == 0) if not eval_wr5_wr: raise AssertionError('Rule wr5 violated') else: return eval_wr5_wr def wr6(self): eval_wr6_wr = (SIZEOF(None) == 0) if not eval_wr6_wr: raise AssertionError('Rule wr6 violated') else: return eval_wr6_wr def wr7(self): eval_wr7_wr = (SIZEOF(None) == 0) if not eval_wr7_wr: raise AssertionError('Rule wr7 violated') else: return eval_wr7_wr def wr8(self): eval_wr8_wr = (SIZEOF(None) == 0) if not eval_wr8_wr: raise AssertionError('Rule wr8 violated') else: return eval_wr8_wr def wr9(self): eval_wr9_wr = (SIZEOF(None) == 0) if not eval_wr9_wr: raise AssertionError('Rule wr9 violated') else: return eval_wr9_wr def wr10(self): eval_wr10_wr = (SIZEOF(None) == 0) if not eval_wr10_wr: raise AssertionError('Rule wr10 violated') else: return eval_wr10_wr def wr11(self): eval_wr11_wr = (SIZEOF(None) == 0) if not eval_wr11_wr: raise AssertionError('Rule wr11 violated') else: return eval_wr11_wr def wr12(self): eval_wr12_wr = (SIZEOF(None) == 0) if not eval_wr12_wr: raise AssertionError('Rule wr12 violated') else: return eval_wr12_wr def wr13(self): eval_wr13_wr = (self.self.context_of_items.self.geometric_representation_context.self.coordinate_space_dimension == 3) if not eval_wr13_wr: raise AssertionError('Rule wr13 violated') else: return eval_wr13_wr #################### # ENTITY face # #################### class face(topological_representation_item): '''Entity face definition. :param bounds :type bounds:SET(1,None,'face_bound', scope = schema_scope) ''' def __init__( self , inherited0__name , bounds, ): topological_representation_item.__init__(self , inherited0__name , ) self.bounds = bounds @apply def bounds(): def fget( self ): return self._bounds def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument bounds is mantatory and can not be set to None') if not check_type(value,SET(1,None,'face_bound', scope = schema_scope)): self._bounds = SET(value) else: self._bounds = value return property(**locals()) def wr1(self): eval_wr1_wr = ( not mixed_loop_type_set(list_to_set(list_face_loops(self)))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(None) <= 1) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY face_surface # #################### class face_surface(face,geometric_representation_item): '''Entity face_surface definition. :param face_geometry :type face_geometry:surface :param same_sense :type same_sense:BOOLEAN ''' def __init__( self , inherited0__name , inherited1__bounds , inherited2__name , face_geometry,same_sense, ): face.__init__(self , inherited0__name , inherited1__bounds , ) geometric_representation_item.__init__(self , inherited2__name , ) self.face_geometry = face_geometry self.same_sense = same_sense @apply def face_geometry(): def fget( self ): return self._face_geometry def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument face_geometry is mantatory and can not be set to None') if not check_type(value,surface): self._face_geometry = surface(value) else: self._face_geometry = value return property(**locals()) @apply def same_sense(): def fget( self ): return self._same_sense def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument same_sense is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._same_sense = BOOLEAN(value) else: self._same_sense = value return property(**locals()) #################### # ENTITY oriented_face # #################### class oriented_face(face): '''Entity oriented_face definition. :param face_element :type face_element:face :param orientation :type orientation:BOOLEAN :param face_bounds :type face_bounds:SET(1,None,'face_bound', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__bounds , face_element,orientation, ): face.__init__(self , inherited0__name , inherited1__bounds , ) self.face_element = face_element self.orientation = orientation @apply def face_element(): def fget( self ): return self._face_element def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument face_element is mantatory and can not be set to None') if not check_type(value,face): self._face_element = face(value) else: self._face_element = value return property(**locals()) @apply def orientation(): def fget( self ): return self._orientation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument orientation is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._orientation = BOOLEAN(value) else: self._orientation = value return property(**locals()) @apply def face_bounds(): def fget( self ): attribute_eval = conditional_reverse(self.self.orientation,self.self.face_element.self.bounds) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument face_bounds is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ( not ('CONFIG_CONTROL_DESIGN.ORIENTED_FACE' == TYPEOF(self.self.face_element))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY surface_of_revolution # #################### class surface_of_revolution(swept_surface): '''Entity surface_of_revolution definition. :param axis_position :type axis_position:axis1_placement :param axis_line :type axis_line:line ''' def __init__( self , inherited0__name , inherited1__swept_curve , axis_position, ): swept_surface.__init__(self , inherited0__name , inherited1__swept_curve , ) self.axis_position = axis_position @apply def axis_position(): def fget( self ): return self._axis_position def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument axis_position is mantatory and can not be set to None') if not check_type(value,axis1_placement): self._axis_position = axis1_placement(value) else: self._axis_position = value return property(**locals()) @apply def axis_line(): def fget( self ): attribute_eval = ((self.dummy_gri == curve()) == line(self.axis_position.self.location,self.dummy_gri == vector(self.axis_position.self.z,1))) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument axis_line is DERIVED. It is computed and can not be set to any value') return property(**locals()) #################### # ENTITY advanced_brep_shape_representation # #################### class advanced_brep_shape_representation(shape_representation): '''Entity advanced_brep_shape_representation definition. ''' def __init__( self , inherited0__name , inherited1__items , inherited2__context_of_items , ): shape_representation.__init__(self , inherited0__name , inherited1__items , inherited2__context_of_items , ) def wr1(self): eval_wr1_wr = (SIZEOF(None) == 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(None) > 0) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(None) == 0) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(None) == 0) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr def wr5(self): eval_wr5_wr = (SIZEOF(None) == 0) if not eval_wr5_wr: raise AssertionError('Rule wr5 violated') else: return eval_wr5_wr def wr6(self): eval_wr6_wr = (SIZEOF(None) == 0) if not eval_wr6_wr: raise AssertionError('Rule wr6 violated') else: return eval_wr6_wr #################### # ENTITY edge_curve # #################### class edge_curve(edge,geometric_representation_item): '''Entity edge_curve definition. :param edge_geometry :type edge_geometry:curve :param same_sense :type same_sense:BOOLEAN ''' def __init__( self , inherited0__name , inherited1__edge_start , inherited2__edge_end , inherited3__name , edge_geometry,same_sense, ): edge.__init__(self , inherited0__name , inherited1__edge_start , inherited2__edge_end , ) geometric_representation_item.__init__(self , inherited3__name , ) self.edge_geometry = edge_geometry self.same_sense = same_sense @apply def edge_geometry(): def fget( self ): return self._edge_geometry def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument edge_geometry is mantatory and can not be set to None') if not check_type(value,curve): self._edge_geometry = curve(value) else: self._edge_geometry = value return property(**locals()) @apply def same_sense(): def fget( self ): return self._same_sense def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument same_sense is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._same_sense = BOOLEAN(value) else: self._same_sense = value return property(**locals()) #################### # ENTITY point_replica # #################### class point_replica(point): '''Entity point_replica definition. :param parent_pt :type parent_pt:point :param transformation :type transformation:cartesian_transformation_operator ''' def __init__( self , inherited0__name , parent_pt,transformation, ): point.__init__(self , inherited0__name , ) self.parent_pt = parent_pt self.transformation = transformation @apply def parent_pt(): def fget( self ): return self._parent_pt def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument parent_pt is mantatory and can not be set to None') if not check_type(value,point): self._parent_pt = point(value) else: self._parent_pt = value return property(**locals()) @apply def transformation(): def fget( self ): return self._transformation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument transformation is mantatory and can not be set to None') if not check_type(value,cartesian_transformation_operator): self._transformation = cartesian_transformation_operator(value) else: self._transformation = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.transformation.self.dim == self.parent_pt.self.dim) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = acyclic_point_replica(self,self.parent_pt) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY product # #################### class product(BaseEntityClass): '''Entity product definition. :param id :type id:identifier :param name :type name:label :param description :type description:text :param frame_of_reference :type frame_of_reference:SET(1,None,'product_context', scope = schema_scope) ''' def __init__( self , id,name,description,frame_of_reference, ): self.id = id self.name = name self.description = description self.frame_of_reference = frame_of_reference @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def frame_of_reference(): def fget( self ): return self._frame_of_reference def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument frame_of_reference is mantatory and can not be set to None') if not check_type(value,SET(1,None,'product_context', scope = schema_scope)): self._frame_of_reference = SET(value) else: self._frame_of_reference = value return property(**locals()) #################### # ENTITY shape_aspect_relationship # #################### class shape_aspect_relationship(BaseEntityClass): '''Entity shape_aspect_relationship definition. :param name :type name:label :param description :type description:text :param relating_shape_aspect :type relating_shape_aspect:shape_aspect :param related_shape_aspect :type related_shape_aspect:shape_aspect ''' def __init__( self , name,description,relating_shape_aspect,related_shape_aspect, ): self.name = name self.description = description self.relating_shape_aspect = relating_shape_aspect self.related_shape_aspect = related_shape_aspect @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def relating_shape_aspect(): def fget( self ): return self._relating_shape_aspect def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument relating_shape_aspect is mantatory and can not be set to None') if not check_type(value,shape_aspect): self._relating_shape_aspect = shape_aspect(value) else: self._relating_shape_aspect = value return property(**locals()) @apply def related_shape_aspect(): def fget( self ): return self._related_shape_aspect def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument related_shape_aspect is mantatory and can not be set to None') if not check_type(value,shape_aspect): self._related_shape_aspect = shape_aspect(value) else: self._related_shape_aspect = value return property(**locals()) #################### # ENTITY rectangular_trimmed_surface # #################### class rectangular_trimmed_surface(bounded_surface): '''Entity rectangular_trimmed_surface definition. :param basis_surface :type basis_surface:surface :param u1 :type u1:parameter_value :param u2 :type u2:parameter_value :param v1 :type v1:parameter_value :param v2 :type v2:parameter_value :param usense :type usense:BOOLEAN :param vsense :type vsense:BOOLEAN ''' def __init__( self , inherited0__name , basis_surface,u1,u2,v1,v2,usense,vsense, ): bounded_surface.__init__(self , inherited0__name , ) self.basis_surface = basis_surface self.u1 = u1 self.u2 = u2 self.v1 = v1 self.v2 = v2 self.usense = usense self.vsense = vsense @apply def basis_surface(): def fget( self ): return self._basis_surface def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis_surface is mantatory and can not be set to None') if not check_type(value,surface): self._basis_surface = surface(value) else: self._basis_surface = value return property(**locals()) @apply def u1(): def fget( self ): return self._u1 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument u1 is mantatory and can not be set to None') if not check_type(value,parameter_value): self._u1 = parameter_value(value) else: self._u1 = value return property(**locals()) @apply def u2(): def fget( self ): return self._u2 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument u2 is mantatory and can not be set to None') if not check_type(value,parameter_value): self._u2 = parameter_value(value) else: self._u2 = value return property(**locals()) @apply def v1(): def fget( self ): return self._v1 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument v1 is mantatory and can not be set to None') if not check_type(value,parameter_value): self._v1 = parameter_value(value) else: self._v1 = value return property(**locals()) @apply def v2(): def fget( self ): return self._v2 def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument v2 is mantatory and can not be set to None') if not check_type(value,parameter_value): self._v2 = parameter_value(value) else: self._v2 = value return property(**locals()) @apply def usense(): def fget( self ): return self._usense def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument usense is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._usense = BOOLEAN(value) else: self._usense = value return property(**locals()) @apply def vsense(): def fget( self ): return self._vsense def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument vsense is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._vsense = BOOLEAN(value) else: self._vsense = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.u1 != self.u2) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (self.v1 != self.v2) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (((('CONFIG_CONTROL_DESIGN.ELEMENTARY_SURFACE' == TYPEOF(self.basis_surface)) and ( not ('CONFIG_CONTROL_DESIGN.PLANE' == TYPEOF(self.basis_surface)))) or ('CONFIG_CONTROL_DESIGN.SURFACE_OF_REVOLUTION' == TYPEOF(self.basis_surface))) or (self.usense == (self.u2 > self.u1))) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = ((('CONFIG_CONTROL_DESIGN.SPHERICAL_SURFACE' == TYPEOF(self.basis_surface)) or ('CONFIG_CONTROL_DESIGN.TOROIDAL_SURFACE' == TYPEOF(self.basis_surface))) or (self.vsense == (self.v2 > self.v1))) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr #################### # ENTITY plane # #################### class plane(elementary_surface): '''Entity plane definition. ''' def __init__( self , inherited0__name , inherited1__position , ): elementary_surface.__init__(self , inherited0__name , inherited1__position , ) #################### # ENTITY action_assignment # #################### class action_assignment(BaseEntityClass): '''Entity action_assignment definition. :param assigned_action :type assigned_action:action ''' def __init__( self , assigned_action, ): self.assigned_action = assigned_action @apply def assigned_action(): def fget( self ): return self._assigned_action def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_action is mantatory and can not be set to None') if not check_type(value,action): self._assigned_action = action(value) else: self._assigned_action = value return property(**locals()) #################### # ENTITY change # #################### class change(action_assignment): '''Entity change definition. :param items :type items:SET(1,None,'work_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_action , items, ): action_assignment.__init__(self , inherited0__assigned_action , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'work_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) #################### # ENTITY circle # #################### class circle(conic): '''Entity circle definition. :param radius :type radius:positive_length_measure ''' def __init__( self , inherited0__name , inherited1__position , radius, ): conic.__init__(self , inherited0__name , inherited1__position , ) self.radius = radius @apply def radius(): def fget( self ): return self._radius def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument radius is mantatory and can not be set to None') if not check_type(value,positive_length_measure): self._radius = positive_length_measure(value) else: self._radius = value return property(**locals()) #################### # ENTITY line # #################### class line(curve): '''Entity line definition. :param pnt :type pnt:cartesian_point :param dir :type dir:vector ''' def __init__( self , inherited0__name , pnt,dir, ): curve.__init__(self , inherited0__name , ) self.pnt = pnt self.dir = dir @apply def pnt(): def fget( self ): return self._pnt def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument pnt is mantatory and can not be set to None') if not check_type(value,cartesian_point): self._pnt = cartesian_point(value) else: self._pnt = value return property(**locals()) @apply def dir(): def fget( self ): return self._dir def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument dir is mantatory and can not be set to None') if not check_type(value,vector): self._dir = vector(value) else: self._dir = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.dir.self.dim == self.pnt.self.dim) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY property_definition_representation # #################### class property_definition_representation(BaseEntityClass): '''Entity property_definition_representation definition. :param definition :type definition:property_definition :param used_representation :type used_representation:representation ''' def __init__( self , definition,used_representation, ): self.definition = definition self.used_representation = used_representation @apply def definition(): def fget( self ): return self._definition def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument definition is mantatory and can not be set to None') if not check_type(value,property_definition): self._definition = property_definition(value) else: self._definition = value return property(**locals()) @apply def used_representation(): def fget( self ): return self._used_representation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument used_representation is mantatory and can not be set to None') if not check_type(value,representation): self._used_representation = representation(value) else: self._used_representation = value return property(**locals()) #################### # ENTITY geometric_set # #################### class geometric_set(geometric_representation_item): '''Entity geometric_set definition. :param elements :type elements:SET(1,None,'geometric_set_select', scope = schema_scope) ''' def __init__( self , inherited0__name , elements, ): geometric_representation_item.__init__(self , inherited0__name , ) self.elements = elements @apply def elements(): def fget( self ): return self._elements def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument elements is mantatory and can not be set to None') if not check_type(value,SET(1,None,'geometric_set_select', scope = schema_scope)): self._elements = SET(value) else: self._elements = value return property(**locals()) #################### # ENTITY geometric_curve_set # #################### class geometric_curve_set(geometric_set): '''Entity geometric_curve_set definition. ''' def __init__( self , inherited0__name , inherited1__elements , ): geometric_set.__init__(self , inherited0__name , inherited1__elements , ) def wr1(self): eval_wr1_wr = (SIZEOF(None) == 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY personal_address # #################### class personal_address(address): '''Entity personal_address definition. :param people :type people:SET(1,None,'person', scope = schema_scope) :param description :type description:text ''' def __init__( self , inherited0__internal_location , inherited1__street_number , inherited2__street , inherited3__postal_box , inherited4__town , inherited5__region , inherited6__postal_code , inherited7__country , inherited8__facsimile_number , inherited9__telephone_number , inherited10__electronic_mail_address , inherited11__telex_number , people,description, ): address.__init__(self , inherited0__internal_location , inherited1__street_number , inherited2__street , inherited3__postal_box , inherited4__town , inherited5__region , inherited6__postal_code , inherited7__country , inherited8__facsimile_number , inherited9__telephone_number , inherited10__electronic_mail_address , inherited11__telex_number , ) self.people = people self.description = description @apply def people(): def fget( self ): return self._people def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument people is mantatory and can not be set to None') if not check_type(value,SET(1,None,'person', scope = schema_scope)): self._people = SET(value) else: self._people = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) #################### # ENTITY document_relationship # #################### class document_relationship(BaseEntityClass): '''Entity document_relationship definition. :param name :type name:label :param description :type description:text :param relating_document :type relating_document:document :param related_document :type related_document:document ''' def __init__( self , name,description,relating_document,related_document, ): self.name = name self.description = description self.relating_document = relating_document self.related_document = related_document @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def relating_document(): def fget( self ): return self._relating_document def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument relating_document is mantatory and can not be set to None') if not check_type(value,document): self._relating_document = document(value) else: self._relating_document = value return property(**locals()) @apply def related_document(): def fget( self ): return self._related_document def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument related_document is mantatory and can not be set to None') if not check_type(value,document): self._related_document = document(value) else: self._related_document = value return property(**locals()) #################### # ENTITY outer_boundary_curve # #################### class outer_boundary_curve(boundary_curve): '''Entity outer_boundary_curve definition. ''' def __init__( self , inherited0__name , inherited1__segments , inherited2__self_intersect , ): boundary_curve.__init__(self , inherited0__name , inherited1__segments , inherited2__self_intersect , ) #################### # ENTITY shape_representation_relationship # #################### class shape_representation_relationship(representation_relationship): '''Entity shape_representation_relationship definition. ''' def __init__( self , inherited0__name , inherited1__description , inherited2__rep_1 , inherited3__rep_2 , ): representation_relationship.__init__(self , inherited0__name , inherited1__description , inherited2__rep_1 , inherited3__rep_2 , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.SHAPE_REPRESENTATION' == (TYPEOF(self.self.representation_relationship.self.rep_1) + TYPEOF(self.self.representation_relationship.self.rep_2))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY assembly_component_usage_substitute # #################### class assembly_component_usage_substitute(BaseEntityClass): '''Entity assembly_component_usage_substitute definition. :param name :type name:label :param definition :type definition:text :param base :type base:assembly_component_usage :param substitute :type substitute:assembly_component_usage ''' def __init__( self , name,definition,base,substitute, ): self.name = name self.definition = definition self.base = base self.substitute = substitute @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def definition(): def fget( self ): return self._definition def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument definition is mantatory and can not be set to None') if not check_type(value,text): self._definition = text(value) else: self._definition = value return property(**locals()) @apply def base(): def fget( self ): return self._base def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument base is mantatory and can not be set to None') if not check_type(value,assembly_component_usage): self._base = assembly_component_usage(value) else: self._base = value return property(**locals()) @apply def substitute(): def fget( self ): return self._substitute def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument substitute is mantatory and can not be set to None') if not check_type(value,assembly_component_usage): self._substitute = assembly_component_usage(value) else: self._substitute = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.base.self.relating_product_definition == self.substitute.self.relating_product_definition) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (self.base != self.substitute) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY degenerate_pcurve # #################### class degenerate_pcurve(point): '''Entity degenerate_pcurve definition. :param basis_surface :type basis_surface:surface :param reference_to_curve :type reference_to_curve:definitional_representation ''' def __init__( self , inherited0__name , basis_surface,reference_to_curve, ): point.__init__(self , inherited0__name , ) self.basis_surface = basis_surface self.reference_to_curve = reference_to_curve @apply def basis_surface(): def fget( self ): return self._basis_surface def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis_surface is mantatory and can not be set to None') if not check_type(value,surface): self._basis_surface = surface(value) else: self._basis_surface = value return property(**locals()) @apply def reference_to_curve(): def fget( self ): return self._reference_to_curve def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument reference_to_curve is mantatory and can not be set to None') if not check_type(value,definitional_representation): self._reference_to_curve = definitional_representation(value) else: self._reference_to_curve = value return property(**locals()) def wr1(self): eval_wr1_wr = (SIZEOF(self.reference_to_curve.self.representation.self.items) == 1) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = ('CONFIG_CONTROL_DESIGN.CURVE' == TYPEOF(self.reference_to_curve.self.representation.self.items[1])) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (self.reference_to_curve.self.representation.self.items[1].self.geometric_representation_item.self.dim == 2) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr #################### # ENTITY evaluated_degenerate_pcurve # #################### class evaluated_degenerate_pcurve(degenerate_pcurve): '''Entity evaluated_degenerate_pcurve definition. :param equivalent_point :type equivalent_point:cartesian_point ''' def __init__( self , inherited0__name , inherited1__basis_surface , inherited2__reference_to_curve , equivalent_point, ): degenerate_pcurve.__init__(self , inherited0__name , inherited1__basis_surface , inherited2__reference_to_curve , ) self.equivalent_point = equivalent_point @apply def equivalent_point(): def fget( self ): return self._equivalent_point def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument equivalent_point is mantatory and can not be set to None') if not check_type(value,cartesian_point): self._equivalent_point = cartesian_point(value) else: self._equivalent_point = value return property(**locals()) #################### # ENTITY solid_angle_measure_with_unit # #################### class solid_angle_measure_with_unit(measure_with_unit): '''Entity solid_angle_measure_with_unit definition. ''' def __init__( self , inherited0__value_component , inherited1__unit_component , ): measure_with_unit.__init__(self , inherited0__value_component , inherited1__unit_component , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.SOLID_ANGLE_UNIT' == TYPEOF(self.self.measure_with_unit.self.unit_component)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY connected_edge_set # #################### class connected_edge_set(topological_representation_item): '''Entity connected_edge_set definition. :param ces_edges :type ces_edges:SET(1,None,'edge', scope = schema_scope) ''' def __init__( self , inherited0__name , ces_edges, ): topological_representation_item.__init__(self , inherited0__name , ) self.ces_edges = ces_edges @apply def ces_edges(): def fget( self ): return self._ces_edges def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument ces_edges is mantatory and can not be set to None') if not check_type(value,SET(1,None,'edge', scope = schema_scope)): self._ces_edges = SET(value) else: self._ces_edges = value return property(**locals()) #################### # ENTITY action # #################### class action(BaseEntityClass): '''Entity action definition. :param name :type name:label :param description :type description:text :param chosen_method :type chosen_method:action_method ''' def __init__( self , name,description,chosen_method, ): self.name = name self.description = description self.chosen_method = chosen_method @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def chosen_method(): def fget( self ): return self._chosen_method def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument chosen_method is mantatory and can not be set to None') if not check_type(value,action_method): self._chosen_method = action_method(value) else: self._chosen_method = value return property(**locals()) #################### # ENTITY executed_action # #################### class executed_action(action): '''Entity executed_action definition. ''' def __init__( self , inherited0__name , inherited1__description , inherited2__chosen_method , ): action.__init__(self , inherited0__name , inherited1__description , inherited2__chosen_method , ) #################### # ENTITY directed_action # #################### class directed_action(executed_action): '''Entity directed_action definition. :param directive :type directive:action_directive ''' def __init__( self , inherited0__name , inherited1__description , inherited2__chosen_method , directive, ): executed_action.__init__(self , inherited0__name , inherited1__description , inherited2__chosen_method , ) self.directive = directive @apply def directive(): def fget( self ): return self._directive def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument directive is mantatory and can not be set to None') if not check_type(value,action_directive): self._directive = action_directive(value) else: self._directive = value return property(**locals()) #################### # ENTITY organizational_project # #################### class organizational_project(BaseEntityClass): '''Entity organizational_project definition. :param name :type name:label :param description :type description:text :param responsible_organizations :type responsible_organizations:SET(1,None,'organization', scope = schema_scope) ''' def __init__( self , name,description,responsible_organizations, ): self.name = name self.description = description self.responsible_organizations = responsible_organizations @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def responsible_organizations(): def fget( self ): return self._responsible_organizations def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument responsible_organizations is mantatory and can not be set to None') if not check_type(value,SET(1,None,'organization', scope = schema_scope)): self._responsible_organizations = SET(value) else: self._responsible_organizations = value return property(**locals()) #################### # ENTITY date_time_role # #################### class date_time_role(BaseEntityClass): '''Entity date_time_role definition. :param name :type name:label ''' def __init__( self , name, ): self.name = name @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) #################### # ENTITY curve_bounded_surface # #################### class curve_bounded_surface(bounded_surface): '''Entity curve_bounded_surface definition. :param basis_surface :type basis_surface:surface :param boundaries :type boundaries:SET(1,None,'boundary_curve', scope = schema_scope) :param implicit_outer :type implicit_outer:BOOLEAN ''' def __init__( self , inherited0__name , basis_surface,boundaries,implicit_outer, ): bounded_surface.__init__(self , inherited0__name , ) self.basis_surface = basis_surface self.boundaries = boundaries self.implicit_outer = implicit_outer @apply def basis_surface(): def fget( self ): return self._basis_surface def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument basis_surface is mantatory and can not be set to None') if not check_type(value,surface): self._basis_surface = surface(value) else: self._basis_surface = value return property(**locals()) @apply def boundaries(): def fget( self ): return self._boundaries def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument boundaries is mantatory and can not be set to None') if not check_type(value,SET(1,None,'boundary_curve', scope = schema_scope)): self._boundaries = SET(value) else: self._boundaries = value return property(**locals()) @apply def implicit_outer(): def fget( self ): return self._implicit_outer def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument implicit_outer is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._implicit_outer = BOOLEAN(value) else: self._implicit_outer = value return property(**locals()) def wr1(self): eval_wr1_wr = ( not (self.implicit_outer and ('CONFIG_CONTROL_DESIGN.OUTER_BOUNDARY_CURVE' == TYPEOF(self.boundaries)))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (( not self.implicit_outer) or ('CONFIG_CONTROL_DESIGN.BOUNDED_SURFACE' == TYPEOF(self.basis_surface))) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(None) <= 1) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(None) == 0) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr #################### # ENTITY closed_shell # #################### class closed_shell(connected_face_set): '''Entity closed_shell definition. ''' def __init__( self , inherited0__name , inherited1__cfs_faces , ): connected_face_set.__init__(self , inherited0__name , inherited1__cfs_faces , ) #################### # ENTITY design_make_from_relationship # #################### class design_make_from_relationship(product_definition_relationship): '''Entity design_make_from_relationship definition. ''' def __init__( self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , ): product_definition_relationship.__init__(self , inherited0__id , inherited1__name , inherited2__description , inherited3__relating_product_definition , inherited4__related_product_definition , ) #################### # ENTITY definitional_representation # #################### class definitional_representation(representation): '''Entity definitional_representation definition. ''' def __init__( self , inherited0__name , inherited1__items , inherited2__context_of_items , ): representation.__init__(self , inherited0__name , inherited1__items , inherited2__context_of_items , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.PARAMETRIC_REPRESENTATION_CONTEXT' == TYPEOF(self.self.representation.self.context_of_items)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY product_definition_shape # #################### class product_definition_shape(property_definition): '''Entity product_definition_shape definition. ''' def __init__( self , inherited0__name , inherited1__description , inherited2__definition , ): property_definition.__init__(self , inherited0__name , inherited1__description , inherited2__definition , ) def wr1(self): eval_wr1_wr = ( not ('CONFIG_CONTROL_DESIGN.SHAPE_DEFINITION' == TYPEOF(self.self.property_definition.self.definition))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY si_unit # #################### class si_unit(named_unit): '''Entity si_unit definition. :param prefix :type prefix:si_prefix :param name :type name:si_unit_name :param named_unit_dimensions :type named_unit_dimensions:dimensional_exponents ''' def __init__( self , inherited0__dimensions , prefix,name, ): named_unit.__init__(self , inherited0__dimensions , ) self.prefix = prefix self.name = name @apply def prefix(): def fget( self ): return self._prefix def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,si_prefix): self._prefix = si_prefix(value) else: self._prefix = value else: self._prefix = value return property(**locals()) @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,si_unit_name): self._name = si_unit_name(value) else: self._name = value return property(**locals()) @apply def named_unit_dimensions(): def fget( self ): attribute_eval = dimensions_for_si_unit(self.self.name) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument named_unit_dimensions is DERIVED. It is computed and can not be set to any value') return property(**locals()) #################### # ENTITY bezier_surface # #################### class bezier_surface(b_spline_surface): '''Entity bezier_surface definition. ''' def __init__( self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , ): b_spline_surface.__init__(self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , ) #################### # ENTITY certification_assignment # #################### class certification_assignment(BaseEntityClass): '''Entity certification_assignment definition. :param assigned_certification :type assigned_certification:certification ''' def __init__( self , assigned_certification, ): self.assigned_certification = assigned_certification @apply def assigned_certification(): def fget( self ): return self._assigned_certification def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_certification is mantatory and can not be set to None') if not check_type(value,certification): self._assigned_certification = certification(value) else: self._assigned_certification = value return property(**locals()) #################### # ENTITY start_work # #################### class start_work(action_assignment): '''Entity start_work definition. :param items :type items:SET(1,None,'work_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_action , items, ): action_assignment.__init__(self , inherited0__assigned_action , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'work_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) #################### # ENTITY contract_type # #################### class contract_type(BaseEntityClass): '''Entity contract_type definition. :param description :type description:label ''' def __init__( self , description, ): self.description = description @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,label): self._description = label(value) else: self._description = value return property(**locals()) #################### # ENTITY b_spline_curve_with_knots # #################### class b_spline_curve_with_knots(b_spline_curve): '''Entity b_spline_curve_with_knots definition. :param knot_multiplicities :type knot_multiplicities:LIST(2,None,'INTEGER', scope = schema_scope) :param knots :type knots:LIST(2,None,'REAL', scope = schema_scope) :param knot_spec :type knot_spec:knot_type :param upper_index_on_knots :type upper_index_on_knots:INTEGER ''' def __init__( self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , knot_multiplicities,knots,knot_spec, ): b_spline_curve.__init__(self , inherited0__name , inherited1__degree , inherited2__control_points_list , inherited3__curve_form , inherited4__closed_curve , inherited5__self_intersect , ) self.knot_multiplicities = knot_multiplicities self.knots = knots self.knot_spec = knot_spec @apply def knot_multiplicities(): def fget( self ): return self._knot_multiplicities def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument knot_multiplicities is mantatory and can not be set to None') if not check_type(value,LIST(2,None,'INTEGER', scope = schema_scope)): self._knot_multiplicities = LIST(value) else: self._knot_multiplicities = value return property(**locals()) @apply def knots(): def fget( self ): return self._knots def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument knots is mantatory and can not be set to None') if not check_type(value,LIST(2,None,'REAL', scope = schema_scope)): self._knots = LIST(value) else: self._knots = value return property(**locals()) @apply def knot_spec(): def fget( self ): return self._knot_spec def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument knot_spec is mantatory and can not be set to None') if not check_type(value,knot_type): self._knot_spec = knot_type(value) else: self._knot_spec = value return property(**locals()) @apply def upper_index_on_knots(): def fget( self ): attribute_eval = SIZEOF(self.knots) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument upper_index_on_knots is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = constraints_param_b_spline(self.degree,self.upper_index_on_knots,self.upper_index_on_control_points,self.knot_multiplicities,self.knots) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(self.knot_multiplicities) == self.upper_index_on_knots) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY cc_design_approval # #################### class cc_design_approval(approval_assignment): '''Entity cc_design_approval definition. :param items :type items:SET(1,None,'approved_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_approval , items, ): approval_assignment.__init__(self , inherited0__assigned_approval , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'approved_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) #################### # ENTITY edge_based_wireframe_shape_representation # #################### class edge_based_wireframe_shape_representation(shape_representation): '''Entity edge_based_wireframe_shape_representation definition. ''' def __init__( self , inherited0__name , inherited1__items , inherited2__context_of_items , ): shape_representation.__init__(self , inherited0__name , inherited1__items , inherited2__context_of_items , ) def wr1(self): eval_wr1_wr = (SIZEOF(None) == 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(None) >= 1) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(None) == 0) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(None) == 0) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr def wr5(self): eval_wr5_wr = (SIZEOF(None) == 0) if not eval_wr5_wr: raise AssertionError('Rule wr5 violated') else: return eval_wr5_wr def wr6(self): eval_wr6_wr = (SIZEOF(None) == 0) if not eval_wr6_wr: raise AssertionError('Rule wr6 violated') else: return eval_wr6_wr def wr7(self): eval_wr7_wr = (SIZEOF(None) == 0) if not eval_wr7_wr: raise AssertionError('Rule wr7 violated') else: return eval_wr7_wr def wr8(self): eval_wr8_wr = (SIZEOF(None) == 0) if not eval_wr8_wr: raise AssertionError('Rule wr8 violated') else: return eval_wr8_wr def wr9(self): eval_wr9_wr = (self.self.context_of_items.self.geometric_representation_context.self.coordinate_space_dimension == 3) if not eval_wr9_wr: raise AssertionError('Rule wr9 violated') else: return eval_wr9_wr #################### # ENTITY geometrically_bounded_wireframe_shape_representation # #################### class geometrically_bounded_wireframe_shape_representation(shape_representation): '''Entity geometrically_bounded_wireframe_shape_representation definition. ''' def __init__( self , inherited0__name , inherited1__items , inherited2__context_of_items , ): shape_representation.__init__(self , inherited0__name , inherited1__items , inherited2__context_of_items , ) def wr1(self): eval_wr1_wr = (SIZEOF(None) == 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(None) >= 1) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(None) == 0) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(None) == 0) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr def wr5(self): eval_wr5_wr = (SIZEOF(None) == 0) if not eval_wr5_wr: raise AssertionError('Rule wr5 violated') else: return eval_wr5_wr def wr6(self): eval_wr6_wr = (SIZEOF(None) == 0) if not eval_wr6_wr: raise AssertionError('Rule wr6 violated') else: return eval_wr6_wr def wr7(self): eval_wr7_wr = (SIZEOF(None) == 0) if not eval_wr7_wr: raise AssertionError('Rule wr7 violated') else: return eval_wr7_wr #################### # ENTITY product_concept # #################### class product_concept(BaseEntityClass): '''Entity product_concept definition. :param id :type id:identifier :param name :type name:label :param description :type description:text :param market_context :type market_context:product_concept_context ''' def __init__( self , id,name,description,market_context, ): self.id = id self.name = name self.description = description self.market_context = market_context @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def market_context(): def fget( self ): return self._market_context def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument market_context is mantatory and can not be set to None') if not check_type(value,product_concept_context): self._market_context = product_concept_context(value) else: self._market_context = value return property(**locals()) #################### # ENTITY cc_design_contract # #################### class cc_design_contract(contract_assignment): '''Entity cc_design_contract definition. :param items :type items:SET(1,None,'contracted_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_contract , items, ): contract_assignment.__init__(self , inherited0__assigned_contract , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'contracted_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) #################### # ENTITY seam_curve # #################### class seam_curve(surface_curve): '''Entity seam_curve definition. ''' def __init__( self , inherited0__name , inherited1__curve_3d , inherited2__associated_geometry , inherited3__master_representation , ): surface_curve.__init__(self , inherited0__name , inherited1__curve_3d , inherited2__associated_geometry , inherited3__master_representation , ) def wr1(self): eval_wr1_wr = (SIZEOF(self.self.surface_curve.self.associated_geometry) == 2) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (associated_surface(self.self.surface_curve.self.associated_geometry[1]) == associated_surface(self.self.surface_curve.self.associated_geometry[2])) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(self.self.surface_curve.self.associated_geometry[1])) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(self.self.surface_curve.self.associated_geometry[2])) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr #################### # ENTITY axis2_placement_3d # #################### class axis2_placement_3d(placement): '''Entity axis2_placement_3d definition. :param axis :type axis:direction :param ref_direction :type ref_direction:direction :param p :type p:LIST(3,3,'direction', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__location , axis,ref_direction, ): placement.__init__(self , inherited0__name , inherited1__location , ) self.axis = axis self.ref_direction = ref_direction @apply def axis(): def fget( self ): return self._axis def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,direction): self._axis = direction(value) else: self._axis = value else: self._axis = value return property(**locals()) @apply def ref_direction(): def fget( self ): return self._ref_direction def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,direction): self._ref_direction = direction(value) else: self._ref_direction = value else: self._ref_direction = value return property(**locals()) @apply def p(): def fget( self ): attribute_eval = build_axes(self.axis,self.ref_direction) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument p is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = (self.self.placement.self.location.self.dim == 3) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (( not EXISTS(self.axis)) or (self.axis.self.dim == 3)) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (( not EXISTS(self.ref_direction)) or (self.ref_direction.self.dim == 3)) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = ((( not EXISTS(self.axis)) or ( not EXISTS(self.ref_direction))) or (cross_product(self.axis,self.ref_direction).self.magnitude > 0)) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr #################### # ENTITY rational_b_spline_surface # #################### class rational_b_spline_surface(b_spline_surface): '''Entity rational_b_spline_surface definition. :param weights_data :type weights_data:LIST(2,None,LIST(2,None,'REAL', scope = schema_scope)) :param weights :type weights:ARRAY(0,u_upper,ARRAY(0,v_upper,'REAL', scope = schema_scope)) ''' def __init__( self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , weights_data, ): b_spline_surface.__init__(self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , ) self.weights_data = weights_data @apply def weights_data(): def fget( self ): return self._weights_data def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument weights_data is mantatory and can not be set to None') if not check_type(value,LIST(2,None,LIST(2,None,'REAL', scope = schema_scope))): self._weights_data = LIST(value) else: self._weights_data = value return property(**locals()) @apply def weights(): def fget( self ): attribute_eval = make_array_of_array(self.weights_data,0,self.u_upper,0,self.v_upper) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument weights is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ((SIZEOF(self.weights_data) == SIZEOF(self.self.b_spline_surface.self.control_points_list)) and (SIZEOF(self.weights_data[1]) == SIZEOF(self.self.b_spline_surface.self.control_points_list[1]))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = surface_weights_positive(self) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY configuration_design # #################### class configuration_design(BaseEntityClass): '''Entity configuration_design definition. :param configuration :type configuration:configuration_item :param design :type design:product_definition_formation ''' def __init__( self , configuration,design, ): self.configuration = configuration self.design = design @apply def configuration(): def fget( self ): return self._configuration def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument configuration is mantatory and can not be set to None') if not check_type(value,configuration_item): self._configuration = configuration_item(value) else: self._configuration = value return property(**locals()) @apply def design(): def fget( self ): return self._design def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument design is mantatory and can not be set to None') if not check_type(value,product_definition_formation): self._design = product_definition_formation(value) else: self._design = value return property(**locals()) #################### # ENTITY design_context # #################### class design_context(product_definition_context): '''Entity design_context definition. ''' def __init__( self , inherited0__name , inherited1__frame_of_reference , inherited2__life_cycle_stage , ): product_definition_context.__init__(self , inherited0__name , inherited1__frame_of_reference , inherited2__life_cycle_stage , ) def wr1(self): eval_wr1_wr = (self.self.life_cycle_stage == 'design') if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY product_definition # #################### class product_definition(BaseEntityClass): '''Entity product_definition definition. :param id :type id:identifier :param description :type description:text :param formation :type formation:product_definition_formation :param frame_of_reference :type frame_of_reference:product_definition_context ''' def __init__( self , id,description,formation,frame_of_reference, ): self.id = id self.description = description self.formation = formation self.frame_of_reference = frame_of_reference @apply def id(): def fget( self ): return self._id def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument id is mantatory and can not be set to None') if not check_type(value,identifier): self._id = identifier(value) else: self._id = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def formation(): def fget( self ): return self._formation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument formation is mantatory and can not be set to None') if not check_type(value,product_definition_formation): self._formation = product_definition_formation(value) else: self._formation = value return property(**locals()) @apply def frame_of_reference(): def fget( self ): return self._frame_of_reference def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument frame_of_reference is mantatory and can not be set to None') if not check_type(value,product_definition_context): self._frame_of_reference = product_definition_context(value) else: self._frame_of_reference = value return property(**locals()) #################### # ENTITY product_definition_with_associated_documents # #################### class product_definition_with_associated_documents(product_definition): '''Entity product_definition_with_associated_documents definition. :param documentation_ids :type documentation_ids:SET(1,None,'document', scope = schema_scope) ''' def __init__( self , inherited0__id , inherited1__description , inherited2__formation , inherited3__frame_of_reference , documentation_ids, ): product_definition.__init__(self , inherited0__id , inherited1__description , inherited2__formation , inherited3__frame_of_reference , ) self.documentation_ids = documentation_ids @apply def documentation_ids(): def fget( self ): return self._documentation_ids def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument documentation_ids is mantatory and can not be set to None') if not check_type(value,SET(1,None,'document', scope = schema_scope)): self._documentation_ids = SET(value) else: self._documentation_ids = value return property(**locals()) #################### # ENTITY organization # #################### class organization(BaseEntityClass): '''Entity organization definition. :param id :type id:identifier :param name :type name:label :param description :type description:text ''' def __init__( self , id,name,description, ): self.id = id self.name = name self.description = description @apply def id(): def fget( self ): return self._id def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,identifier): self._id = identifier(value) else: self._id = value else: self._id = value return property(**locals()) @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) #################### # ENTITY cc_design_certification # #################### class cc_design_certification(certification_assignment): '''Entity cc_design_certification definition. :param items :type items:SET(1,None,'certified_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_certification , items, ): certification_assignment.__init__(self , inherited0__assigned_certification , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'certified_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) #################### # ENTITY b_spline_surface_with_knots # #################### class b_spline_surface_with_knots(b_spline_surface): '''Entity b_spline_surface_with_knots definition. :param u_multiplicities :type u_multiplicities:LIST(2,None,'INTEGER', scope = schema_scope) :param v_multiplicities :type v_multiplicities:LIST(2,None,'INTEGER', scope = schema_scope) :param u_knots :type u_knots:LIST(2,None,'REAL', scope = schema_scope) :param v_knots :type v_knots:LIST(2,None,'REAL', scope = schema_scope) :param knot_spec :type knot_spec:knot_type :param knot_u_upper :type knot_u_upper:INTEGER :param knot_v_upper :type knot_v_upper:INTEGER ''' def __init__( self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , u_multiplicities,v_multiplicities,u_knots,v_knots,knot_spec, ): b_spline_surface.__init__(self , inherited0__name , inherited1__u_degree , inherited2__v_degree , inherited3__control_points_list , inherited4__surface_form , inherited5__u_closed , inherited6__v_closed , inherited7__self_intersect , ) self.u_multiplicities = u_multiplicities self.v_multiplicities = v_multiplicities self.u_knots = u_knots self.v_knots = v_knots self.knot_spec = knot_spec @apply def u_multiplicities(): def fget( self ): return self._u_multiplicities def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument u_multiplicities is mantatory and can not be set to None') if not check_type(value,LIST(2,None,'INTEGER', scope = schema_scope)): self._u_multiplicities = LIST(value) else: self._u_multiplicities = value return property(**locals()) @apply def v_multiplicities(): def fget( self ): return self._v_multiplicities def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument v_multiplicities is mantatory and can not be set to None') if not check_type(value,LIST(2,None,'INTEGER', scope = schema_scope)): self._v_multiplicities = LIST(value) else: self._v_multiplicities = value return property(**locals()) @apply def u_knots(): def fget( self ): return self._u_knots def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument u_knots is mantatory and can not be set to None') if not check_type(value,LIST(2,None,'REAL', scope = schema_scope)): self._u_knots = LIST(value) else: self._u_knots = value return property(**locals()) @apply def v_knots(): def fget( self ): return self._v_knots def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument v_knots is mantatory and can not be set to None') if not check_type(value,LIST(2,None,'REAL', scope = schema_scope)): self._v_knots = LIST(value) else: self._v_knots = value return property(**locals()) @apply def knot_spec(): def fget( self ): return self._knot_spec def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument knot_spec is mantatory and can not be set to None') if not check_type(value,knot_type): self._knot_spec = knot_type(value) else: self._knot_spec = value return property(**locals()) @apply def knot_u_upper(): def fget( self ): attribute_eval = SIZEOF(self.u_knots) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument knot_u_upper is DERIVED. It is computed and can not be set to any value') return property(**locals()) @apply def knot_v_upper(): def fget( self ): attribute_eval = SIZEOF(self.v_knots) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument knot_v_upper is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = constraints_param_b_spline(self.self.b_spline_surface.self.u_degree,self.knot_u_upper,self.self.b_spline_surface.self.u_upper,self.u_multiplicities,self.u_knots) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = constraints_param_b_spline(self.self.b_spline_surface.self.v_degree,self.knot_v_upper,self.self.b_spline_surface.self.v_upper,self.v_multiplicities,self.v_knots) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(self.u_multiplicities) == self.knot_u_upper) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(self.v_multiplicities) == self.knot_v_upper) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr #################### # ENTITY certification_type # #################### class certification_type(BaseEntityClass): '''Entity certification_type definition. :param description :type description:label ''' def __init__( self , description, ): self.description = description @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,label): self._description = label(value) else: self._description = value return property(**locals()) #################### # ENTITY oriented_path # #################### class oriented_path(path): '''Entity oriented_path definition. :param path_element :type path_element:path :param orientation :type orientation:BOOLEAN :param path_edge_list :type path_edge_list:LIST(1,None,'oriented_edge', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__edge_list , path_element,orientation, ): path.__init__(self , inherited0__name , inherited1__edge_list , ) self.path_element = path_element self.orientation = orientation @apply def path_element(): def fget( self ): return self._path_element def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument path_element is mantatory and can not be set to None') if not check_type(value,path): self._path_element = path(value) else: self._path_element = value return property(**locals()) @apply def orientation(): def fget( self ): return self._orientation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument orientation is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._orientation = BOOLEAN(value) else: self._orientation = value return property(**locals()) @apply def path_edge_list(): def fget( self ): attribute_eval = conditional_reverse(self.self.orientation,self.self.path_element.self.edge_list) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument path_edge_list is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ( not ('CONFIG_CONTROL_DESIGN.ORIENTED_PATH' == TYPEOF(self.self.path_element))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY security_classification # #################### class security_classification(BaseEntityClass): '''Entity security_classification definition. :param name :type name:label :param purpose :type purpose:text :param security_level :type security_level:security_classification_level ''' def __init__( self , name,purpose,security_level, ): self.name = name self.purpose = purpose self.security_level = security_level @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def purpose(): def fget( self ): return self._purpose def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument purpose is mantatory and can not be set to None') if not check_type(value,text): self._purpose = text(value) else: self._purpose = value return property(**locals()) @apply def security_level(): def fget( self ): return self._security_level def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument security_level is mantatory and can not be set to None') if not check_type(value,security_classification_level): self._security_level = security_classification_level(value) else: self._security_level = value return property(**locals()) #################### # ENTITY vertex_loop # #################### class vertex_loop(loop): '''Entity vertex_loop definition. :param loop_vertex :type loop_vertex:vertex ''' def __init__( self , inherited0__name , loop_vertex, ): loop.__init__(self , inherited0__name , ) self.loop_vertex = loop_vertex @apply def loop_vertex(): def fget( self ): return self._loop_vertex def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument loop_vertex is mantatory and can not be set to None') if not check_type(value,vertex): self._loop_vertex = vertex(value) else: self._loop_vertex = value return property(**locals()) #################### # ENTITY approval_status # #################### class approval_status(BaseEntityClass): '''Entity approval_status definition. :param name :type name:label ''' def __init__( self , name, ): self.name = name @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) #################### # ENTITY cartesian_point # #################### class cartesian_point(point): '''Entity cartesian_point definition. :param coordinates :type coordinates:LIST(1,3,'REAL', scope = schema_scope) ''' def __init__( self , inherited0__name , coordinates, ): point.__init__(self , inherited0__name , ) self.coordinates = coordinates @apply def coordinates(): def fget( self ): return self._coordinates def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument coordinates is mantatory and can not be set to None') if not check_type(value,LIST(1,3,'REAL', scope = schema_scope)): self._coordinates = LIST(value) else: self._coordinates = value return property(**locals()) #################### # ENTITY date_and_time_assignment # #################### class date_and_time_assignment(BaseEntityClass): '''Entity date_and_time_assignment definition. :param assigned_date_and_time :type assigned_date_and_time:date_and_time :param role :type role:date_time_role ''' def __init__( self , assigned_date_and_time,role, ): self.assigned_date_and_time = assigned_date_and_time self.role = role @apply def assigned_date_and_time(): def fget( self ): return self._assigned_date_and_time def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_date_and_time is mantatory and can not be set to None') if not check_type(value,date_and_time): self._assigned_date_and_time = date_and_time(value) else: self._assigned_date_and_time = value return property(**locals()) @apply def role(): def fget( self ): return self._role def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument role is mantatory and can not be set to None') if not check_type(value,date_time_role): self._role = date_time_role(value) else: self._role = value return property(**locals()) #################### # ENTITY parametric_representation_context # #################### class parametric_representation_context(representation_context): '''Entity parametric_representation_context definition. ''' def __init__( self , inherited0__context_identifier , inherited1__context_type , ): representation_context.__init__(self , inherited0__context_identifier , inherited1__context_type , ) #################### # ENTITY product_concept_context # #################### class product_concept_context(application_context_element): '''Entity product_concept_context definition. :param market_segment_type :type market_segment_type:label ''' def __init__( self , inherited0__name , inherited1__frame_of_reference , market_segment_type, ): application_context_element.__init__(self , inherited0__name , inherited1__frame_of_reference , ) self.market_segment_type = market_segment_type @apply def market_segment_type(): def fget( self ): return self._market_segment_type def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument market_segment_type is mantatory and can not be set to None') if not check_type(value,label): self._market_segment_type = label(value) else: self._market_segment_type = value return property(**locals()) #################### # ENTITY surface_patch # #################### class surface_patch(founded_item): '''Entity surface_patch definition. :param parent_surface :type parent_surface:bounded_surface :param u_transition :type u_transition:transition_code :param v_transition :type v_transition:transition_code :param u_sense :type u_sense:BOOLEAN :param v_sense :type v_sense:BOOLEAN :param using_surfaces :type using_surfaces:BAG(1,None,'rectangular_composite_surface', scope = schema_scope) ''' def __init__( self , parent_surface,u_transition,v_transition,u_sense,v_sense, ): founded_item.__init__(self , ) self.parent_surface = parent_surface self.u_transition = u_transition self.v_transition = v_transition self.u_sense = u_sense self.v_sense = v_sense @apply def parent_surface(): def fget( self ): return self._parent_surface def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument parent_surface is mantatory and can not be set to None') if not check_type(value,bounded_surface): self._parent_surface = bounded_surface(value) else: self._parent_surface = value return property(**locals()) @apply def u_transition(): def fget( self ): return self._u_transition def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument u_transition is mantatory and can not be set to None') if not check_type(value,transition_code): self._u_transition = transition_code(value) else: self._u_transition = value return property(**locals()) @apply def v_transition(): def fget( self ): return self._v_transition def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument v_transition is mantatory and can not be set to None') if not check_type(value,transition_code): self._v_transition = transition_code(value) else: self._v_transition = value return property(**locals()) @apply def u_sense(): def fget( self ): return self._u_sense def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument u_sense is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._u_sense = BOOLEAN(value) else: self._u_sense = value return property(**locals()) @apply def v_sense(): def fget( self ): return self._v_sense def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument v_sense is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._v_sense = BOOLEAN(value) else: self._v_sense = value return property(**locals()) @apply def using_surfaces(): def fget( self ): return self._using_surfaces def fset( self, value ): # INVERSE argument raise AssertionError('Argument using_surfaces is INVERSE. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ( not ('CONFIG_CONTROL_DESIGN.CURVE_BOUNDED_SURFACE' == TYPEOF(self.parent_surface))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY length_unit # #################### class length_unit(named_unit): '''Entity length_unit definition. ''' def __init__( self , inherited0__dimensions , ): named_unit.__init__(self , inherited0__dimensions , ) def wr1(self): eval_wr1_wr = (((((((self.self.named_unit.self.dimensions.self.length_exponent == 1) and (self.self.named_unit.self.dimensions.self.mass_exponent == 0)) and (self.self.named_unit.self.dimensions.self.time_exponent == 0)) and (self.self.named_unit.self.dimensions.self.electric_current_exponent == 0)) and (self.self.named_unit.self.dimensions.self.thermodynamic_temperature_exponent == 0)) and (self.self.named_unit.self.dimensions.self.amount_of_substance_exponent == 0)) and (self.self.named_unit.self.dimensions.self.luminous_intensity_exponent == 0)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY shape_aspect # #################### class shape_aspect(BaseEntityClass): '''Entity shape_aspect definition. :param name :type name:label :param description :type description:text :param of_shape :type of_shape:product_definition_shape :param product_definitional :type product_definitional:LOGICAL ''' def __init__( self , name,description,of_shape,product_definitional, ): self.name = name self.description = description self.of_shape = of_shape self.product_definitional = product_definitional @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def of_shape(): def fget( self ): return self._of_shape def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument of_shape is mantatory and can not be set to None') if not check_type(value,product_definition_shape): self._of_shape = product_definition_shape(value) else: self._of_shape = value return property(**locals()) @apply def product_definitional(): def fget( self ): return self._product_definitional def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument product_definitional is mantatory and can not be set to None') if not check_type(value,LOGICAL): self._product_definitional = LOGICAL(value) else: self._product_definitional = value return property(**locals()) #################### # ENTITY volume_measure_with_unit # #################### class volume_measure_with_unit(measure_with_unit): '''Entity volume_measure_with_unit definition. ''' def __init__( self , inherited0__value_component , inherited1__unit_component , ): measure_with_unit.__init__(self , inherited0__value_component , inherited1__unit_component , ) def wr1(self): eval_wr1_wr = ('CONFIG_CONTROL_DESIGN.VOLUME_UNIT' == TYPEOF(self.self.measure_with_unit.self.unit_component)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY advanced_face # #################### class advanced_face(face_surface): '''Entity advanced_face definition. ''' def __init__( self , inherited0__name , inherited1__bounds , inherited2__name , inherited3__face_geometry , inherited4__same_sense , ): face_surface.__init__(self , inherited0__name , inherited1__bounds , inherited2__name , inherited3__face_geometry , inherited4__same_sense , ) def wr1(self): eval_wr1_wr = (SIZEOF(['CONFIG_CONTROL_DESIGN.ELEMENTARY_SURFACE','CONFIG_CONTROL_DESIGN.B_SPLINE_SURFACE','CONFIG_CONTROL_DESIGN.SWEPT_SURFACE'] * TYPEOF(self.face_geometry)) == 1) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(None) == 0) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(None) == 0) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(None) == 0) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr def wr5(self): eval_wr5_wr = (SIZEOF(None) == 0) if not eval_wr5_wr: raise AssertionError('Rule wr5 violated') else: return eval_wr5_wr def wr6(self): eval_wr6_wr = (( not ('CONFIG_CONTROL_DESIGN.SWEPT_SURFACE' == TYPEOF(self.face_geometry))) or (SIZEOF(['CONFIG_CONTROL_DESIGN.LINE','CONFIG_CONTROL_DESIGN.CONIC','CONFIG_CONTROL_DESIGN.POLYLINE','CONFIG_CONTROL_DESIGN.B_SPLINE_CURVE'] * TYPEOF(self.face_geometry.self.swept_surface.self.swept_curve)) == 1)) if not eval_wr6_wr: raise AssertionError('Rule wr6 violated') else: return eval_wr6_wr def wr7(self): eval_wr7_wr = (SIZEOF(None) == 0) if not eval_wr7_wr: raise AssertionError('Rule wr7 violated') else: return eval_wr7_wr def wr8(self): eval_wr8_wr = (SIZEOF(None) == 0) if not eval_wr8_wr: raise AssertionError('Rule wr8 violated') else: return eval_wr8_wr def wr9(self): eval_wr9_wr = (SIZEOF(None) == 0) if not eval_wr9_wr: raise AssertionError('Rule wr9 violated') else: return eval_wr9_wr def wr10(self): eval_wr10_wr = (((( not ('CONFIG_CONTROL_DESIGN.SWEPT_SURFACE' == TYPEOF(self.face_geometry))) or ( not ('CONFIG_CONTROL_DESIGN.POLYLINE' == TYPEOF(self.face_geometry.self.swept_surface.self.swept_curve)))) or (SIZEOF(self.face_geometry.self.swept_surface.self.swept_curve.self.polyline.self.points) >= 3)) and (SIZEOF(None) == 0)) if not eval_wr10_wr: raise AssertionError('Rule wr10 violated') else: return eval_wr10_wr #################### # ENTITY security_classification_level # #################### class security_classification_level(BaseEntityClass): '''Entity security_classification_level definition. :param name :type name:label ''' def __init__( self , name, ): self.name = name @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) #################### # ENTITY approval_relationship # #################### class approval_relationship(BaseEntityClass): '''Entity approval_relationship definition. :param name :type name:label :param description :type description:text :param relating_approval :type relating_approval:approval :param related_approval :type related_approval:approval ''' def __init__( self , name,description,relating_approval,related_approval, ): self.name = name self.description = description self.relating_approval = relating_approval self.related_approval = related_approval @apply def name(): def fget( self ): return self._name def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument name is mantatory and can not be set to None') if not check_type(value,label): self._name = label(value) else: self._name = value return property(**locals()) @apply def description(): def fget( self ): return self._description def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument description is mantatory and can not be set to None') if not check_type(value,text): self._description = text(value) else: self._description = value return property(**locals()) @apply def relating_approval(): def fget( self ): return self._relating_approval def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument relating_approval is mantatory and can not be set to None') if not check_type(value,approval): self._relating_approval = approval(value) else: self._relating_approval = value return property(**locals()) @apply def related_approval(): def fget( self ): return self._related_approval def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument related_approval is mantatory and can not be set to None') if not check_type(value,approval): self._related_approval = approval(value) else: self._related_approval = value return property(**locals()) #################### # ENTITY polyline # #################### class polyline(bounded_curve): '''Entity polyline definition. :param points :type points:LIST(2,None,'cartesian_point', scope = schema_scope) ''' def __init__( self , inherited0__name , points, ): bounded_curve.__init__(self , inherited0__name , ) self.points = points @apply def points(): def fget( self ): return self._points def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument points is mantatory and can not be set to None') if not check_type(value,LIST(2,None,'cartesian_point', scope = schema_scope)): self._points = LIST(value) else: self._points = value return property(**locals()) #################### # ENTITY approval_person_organization # #################### class approval_person_organization(BaseEntityClass): '''Entity approval_person_organization definition. :param person_organization :type person_organization:person_organization_select :param authorized_approval :type authorized_approval:approval :param role :type role:approval_role ''' def __init__( self , person_organization,authorized_approval,role, ): self.person_organization = person_organization self.authorized_approval = authorized_approval self.role = role @apply def person_organization(): def fget( self ): return self._person_organization def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument person_organization is mantatory and can not be set to None') if not check_type(value,person_organization_select): self._person_organization = person_organization_select(value) else: self._person_organization = value return property(**locals()) @apply def authorized_approval(): def fget( self ): return self._authorized_approval def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument authorized_approval is mantatory and can not be set to None') if not check_type(value,approval): self._authorized_approval = approval(value) else: self._authorized_approval = value return property(**locals()) @apply def role(): def fget( self ): return self._role def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument role is mantatory and can not be set to None') if not check_type(value,approval_role): self._role = approval_role(value) else: self._role = value return property(**locals()) #################### # ENTITY surface_replica # #################### class surface_replica(surface): '''Entity surface_replica definition. :param parent_surface :type parent_surface:surface :param transformation :type transformation:cartesian_transformation_operator_3d ''' def __init__( self , inherited0__name , parent_surface,transformation, ): surface.__init__(self , inherited0__name , ) self.parent_surface = parent_surface self.transformation = transformation @apply def parent_surface(): def fget( self ): return self._parent_surface def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument parent_surface is mantatory and can not be set to None') if not check_type(value,surface): self._parent_surface = surface(value) else: self._parent_surface = value return property(**locals()) @apply def transformation(): def fget( self ): return self._transformation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument transformation is mantatory and can not be set to None') if not check_type(value,cartesian_transformation_operator_3d): self._transformation = cartesian_transformation_operator_3d(value) else: self._transformation = value return property(**locals()) def wr1(self): eval_wr1_wr = acyclic_surface_replica(self,self.parent_surface) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY security_classification_assignment # #################### class security_classification_assignment(BaseEntityClass): '''Entity security_classification_assignment definition. :param assigned_security_classification :type assigned_security_classification:security_classification ''' def __init__( self , assigned_security_classification, ): self.assigned_security_classification = assigned_security_classification @apply def assigned_security_classification(): def fget( self ): return self._assigned_security_classification def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument assigned_security_classification is mantatory and can not be set to None') if not check_type(value,security_classification): self._assigned_security_classification = security_classification(value) else: self._assigned_security_classification = value return property(**locals()) #################### # ENTITY cc_design_security_classification # #################### class cc_design_security_classification(security_classification_assignment): '''Entity cc_design_security_classification definition. :param items :type items:SET(1,None,'classified_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_security_classification , items, ): security_classification_assignment.__init__(self , inherited0__assigned_security_classification , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'classified_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) #################### # ENTITY faceted_brep_shape_representation # #################### class faceted_brep_shape_representation(shape_representation): '''Entity faceted_brep_shape_representation definition. ''' def __init__( self , inherited0__name , inherited1__items , inherited2__context_of_items , ): shape_representation.__init__(self , inherited0__name , inherited1__items , inherited2__context_of_items , ) def wr1(self): eval_wr1_wr = (SIZEOF(None) == 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = (SIZEOF(None) > 0) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr def wr3(self): eval_wr3_wr = (SIZEOF(None) == 0) if not eval_wr3_wr: raise AssertionError('Rule wr3 violated') else: return eval_wr3_wr def wr4(self): eval_wr4_wr = (SIZEOF(None) == 0) if not eval_wr4_wr: raise AssertionError('Rule wr4 violated') else: return eval_wr4_wr def wr5(self): eval_wr5_wr = (SIZEOF(None) == 0) if not eval_wr5_wr: raise AssertionError('Rule wr5 violated') else: return eval_wr5_wr def wr6(self): eval_wr6_wr = (SIZEOF(None) == 0) if not eval_wr6_wr: raise AssertionError('Rule wr6 violated') else: return eval_wr6_wr def wr7(self): eval_wr7_wr = (SIZEOF(None) == 0) if not eval_wr7_wr: raise AssertionError('Rule wr7 violated') else: return eval_wr7_wr #################### # ENTITY document_usage_constraint # #################### class document_usage_constraint(BaseEntityClass): '''Entity document_usage_constraint definition. :param source :type source:document :param subject_element :type subject_element:label :param subject_element_value :type subject_element_value:text ''' def __init__( self , source,subject_element,subject_element_value, ): self.source = source self.subject_element = subject_element self.subject_element_value = subject_element_value @apply def source(): def fget( self ): return self._source def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument source is mantatory and can not be set to None') if not check_type(value,document): self._source = document(value) else: self._source = value return property(**locals()) @apply def subject_element(): def fget( self ): return self._subject_element def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument subject_element is mantatory and can not be set to None') if not check_type(value,label): self._subject_element = label(value) else: self._subject_element = value return property(**locals()) @apply def subject_element_value(): def fget( self ): return self._subject_element_value def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument subject_element_value is mantatory and can not be set to None') if not check_type(value,text): self._subject_element_value = text(value) else: self._subject_element_value = value return property(**locals()) #################### # ENTITY vertex_point # #################### class vertex_point(vertex,geometric_representation_item): '''Entity vertex_point definition. :param vertex_geometry :type vertex_geometry:point ''' def __init__( self , inherited0__name , inherited1__name , vertex_geometry, ): vertex.__init__(self , inherited0__name , ) geometric_representation_item.__init__(self , inherited1__name , ) self.vertex_geometry = vertex_geometry @apply def vertex_geometry(): def fget( self ): return self._vertex_geometry def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument vertex_geometry is mantatory and can not be set to None') if not check_type(value,point): self._vertex_geometry = point(value) else: self._vertex_geometry = value return property(**locals()) #################### # ENTITY cc_design_date_and_time_assignment # #################### class cc_design_date_and_time_assignment(date_and_time_assignment): '''Entity cc_design_date_and_time_assignment definition. :param items :type items:SET(1,None,'date_time_item', scope = schema_scope) ''' def __init__( self , inherited0__assigned_date_and_time , inherited1__role , items, ): date_and_time_assignment.__init__(self , inherited0__assigned_date_and_time , inherited1__role , ) self.items = items @apply def items(): def fget( self ): return self._items def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument items is mantatory and can not be set to None') if not check_type(value,SET(1,None,'date_time_item', scope = schema_scope)): self._items = SET(value) else: self._items = value return property(**locals()) def wr1(self): eval_wr1_wr = cc_design_date_time_correlation(self) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY oriented_closed_shell # #################### class oriented_closed_shell(closed_shell): '''Entity oriented_closed_shell definition. :param closed_shell_element :type closed_shell_element:closed_shell :param orientation :type orientation:BOOLEAN :param connected_face_set_cfs_faces :type connected_face_set_cfs_faces:SET(1,None,'face', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__cfs_faces , closed_shell_element,orientation, ): closed_shell.__init__(self , inherited0__name , inherited1__cfs_faces , ) self.closed_shell_element = closed_shell_element self.orientation = orientation @apply def closed_shell_element(): def fget( self ): return self._closed_shell_element def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument closed_shell_element is mantatory and can not be set to None') if not check_type(value,closed_shell): self._closed_shell_element = closed_shell(value) else: self._closed_shell_element = value return property(**locals()) @apply def orientation(): def fget( self ): return self._orientation def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument orientation is mantatory and can not be set to None') if not check_type(value,BOOLEAN): self._orientation = BOOLEAN(value) else: self._orientation = value return property(**locals()) @apply def connected_face_set_cfs_faces(): def fget( self ): attribute_eval = conditional_reverse(self.self.orientation,self.self.closed_shell_element.self.cfs_faces) return attribute_eval def fset( self, value ): # DERIVED argument raise AssertionError('Argument connected_face_set_cfs_faces is DERIVED. It is computed and can not be set to any value') return property(**locals()) def wr1(self): eval_wr1_wr = ( not ('CONFIG_CONTROL_DESIGN.ORIENTED_CLOSED_SHELL' == TYPEOF(self.self.closed_shell_element))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY person_and_organization # #################### class person_and_organization(BaseEntityClass): '''Entity person_and_organization definition. :param the_person :type the_person:person :param the_organization :type the_organization:organization ''' def __init__( self , the_person,the_organization, ): self.the_person = the_person self.the_organization = the_organization @apply def the_person(): def fget( self ): return self._the_person def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument the_person is mantatory and can not be set to None') if not check_type(value,person): self._the_person = person(value) else: self._the_person = value return property(**locals()) @apply def the_organization(): def fget( self ): return self._the_organization def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument the_organization is mantatory and can not be set to None') if not check_type(value,organization): self._the_organization = organization(value) else: self._the_organization = value return property(**locals()) #################### # ENTITY cylindrical_surface # #################### class cylindrical_surface(elementary_surface): '''Entity cylindrical_surface definition. :param radius :type radius:positive_length_measure ''' def __init__( self , inherited0__name , inherited1__position , radius, ): elementary_surface.__init__(self , inherited0__name , inherited1__position , ) self.radius = radius @apply def radius(): def fget( self ): return self._radius def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument radius is mantatory and can not be set to None') if not check_type(value,positive_length_measure): self._radius = positive_length_measure(value) else: self._radius = value return property(**locals()) #################### # ENTITY local_time # #################### class local_time(BaseEntityClass): '''Entity local_time definition. :param hour_component :type hour_component:hour_in_day :param minute_component :type minute_component:minute_in_hour :param second_component :type second_component:second_in_minute :param zone :type zone:coordinated_universal_time_offset ''' def __init__( self , hour_component,minute_component,second_component,zone, ): self.hour_component = hour_component self.minute_component = minute_component self.second_component = second_component self.zone = zone @apply def hour_component(): def fget( self ): return self._hour_component def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument hour_component is mantatory and can not be set to None') if not check_type(value,hour_in_day): self._hour_component = hour_in_day(value) else: self._hour_component = value return property(**locals()) @apply def minute_component(): def fget( self ): return self._minute_component def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,minute_in_hour): self._minute_component = minute_in_hour(value) else: self._minute_component = value else: self._minute_component = value return property(**locals()) @apply def second_component(): def fget( self ): return self._second_component def fset( self, value ): if value != None: # OPTIONAL attribute if not check_type(value,second_in_minute): self._second_component = second_in_minute(value) else: self._second_component = value else: self._second_component = value return property(**locals()) @apply def zone(): def fget( self ): return self._zone def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument zone is mantatory and can not be set to None') if not check_type(value,coordinated_universal_time_offset): self._zone = coordinated_universal_time_offset(value) else: self._zone = value return property(**locals()) def wr1(self): eval_wr1_wr = valid_time(self) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY mass_unit # #################### class mass_unit(named_unit): '''Entity mass_unit definition. ''' def __init__( self , inherited0__dimensions , ): named_unit.__init__(self , inherited0__dimensions , ) def wr1(self): eval_wr1_wr = (((((((self.self.named_unit.self.dimensions.self.length_exponent == 0) and (self.self.named_unit.self.dimensions.self.mass_exponent == 1)) and (self.self.named_unit.self.dimensions.self.time_exponent == 0)) and (self.self.named_unit.self.dimensions.self.electric_current_exponent == 0)) and (self.self.named_unit.self.dimensions.self.thermodynamic_temperature_exponent == 0)) and (self.self.named_unit.self.dimensions.self.amount_of_substance_exponent == 0)) and (self.self.named_unit.self.dimensions.self.luminous_intensity_exponent == 0)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY vertex_shell # #################### class vertex_shell(topological_representation_item): '''Entity vertex_shell definition. :param vertex_shell_extent :type vertex_shell_extent:vertex_loop ''' def __init__( self , inherited0__name , vertex_shell_extent, ): topological_representation_item.__init__(self , inherited0__name , ) self.vertex_shell_extent = vertex_shell_extent @apply def vertex_shell_extent(): def fget( self ): return self._vertex_shell_extent def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument vertex_shell_extent is mantatory and can not be set to None') if not check_type(value,vertex_loop): self._vertex_shell_extent = vertex_loop(value) else: self._vertex_shell_extent = value return property(**locals()) #################### # ENTITY poly_loop # #################### class poly_loop(loop,geometric_representation_item): '''Entity poly_loop definition. :param polygon :type polygon:LIST(3,None,'cartesian_point', scope = schema_scope) ''' def __init__( self , inherited0__name , inherited1__name , polygon, ): loop.__init__(self , inherited0__name , ) geometric_representation_item.__init__(self , inherited1__name , ) self.polygon = polygon @apply def polygon(): def fget( self ): return self._polygon def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument polygon is mantatory and can not be set to None') if not check_type(value,LIST(3,None,'cartesian_point', scope = schema_scope)): self._polygon = LIST(value) else: self._polygon = value return property(**locals()) #################### # ENTITY wire_shell # #################### class wire_shell(topological_representation_item): '''Entity wire_shell definition. :param wire_shell_extent :type wire_shell_extent:SET(1,None,'loop', scope = schema_scope) ''' def __init__( self , inherited0__name , wire_shell_extent, ): topological_representation_item.__init__(self , inherited0__name , ) self.wire_shell_extent = wire_shell_extent @apply def wire_shell_extent(): def fget( self ): return self._wire_shell_extent def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument wire_shell_extent is mantatory and can not be set to None') if not check_type(value,SET(1,None,'loop', scope = schema_scope)): self._wire_shell_extent = SET(value) else: self._wire_shell_extent = value return property(**locals()) def wr1(self): eval_wr1_wr = ( not mixed_loop_type_set(self.wire_shell_extent)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY area_unit # #################### class area_unit(named_unit): '''Entity area_unit definition. ''' def __init__( self , inherited0__dimensions , ): named_unit.__init__(self , inherited0__dimensions , ) def wr1(self): eval_wr1_wr = (((((((self.self.named_unit.self.dimensions.self.length_exponent == 2) and (self.self.named_unit.self.dimensions.self.mass_exponent == 0)) and (self.self.named_unit.self.dimensions.self.time_exponent == 0)) and (self.self.named_unit.self.dimensions.self.electric_current_exponent == 0)) and (self.self.named_unit.self.dimensions.self.thermodynamic_temperature_exponent == 0)) and (self.self.named_unit.self.dimensions.self.amount_of_substance_exponent == 0)) and (self.self.named_unit.self.dimensions.self.luminous_intensity_exponent == 0)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY mapped_item # #################### class mapped_item(representation_item): '''Entity mapped_item definition. :param mapping_source :type mapping_source:representation_map :param mapping_target :type mapping_target:representation_item ''' def __init__( self , inherited0__name , mapping_source,mapping_target, ): representation_item.__init__(self , inherited0__name , ) self.mapping_source = mapping_source self.mapping_target = mapping_target @apply def mapping_source(): def fget( self ): return self._mapping_source def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument mapping_source is mantatory and can not be set to None') if not check_type(value,representation_map): self._mapping_source = representation_map(value) else: self._mapping_source = value return property(**locals()) @apply def mapping_target(): def fget( self ): return self._mapping_target def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument mapping_target is mantatory and can not be set to None') if not check_type(value,representation_item): self._mapping_target = representation_item(value) else: self._mapping_target = value return property(**locals()) def wr1(self): eval_wr1_wr = acyclic_mapped_representation(using_representations(self),[self]) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY shape_definition_representation # #################### class shape_definition_representation(property_definition_representation): '''Entity shape_definition_representation definition. ''' def __init__( self , inherited0__definition , inherited1__used_representation , ): property_definition_representation.__init__(self , inherited0__definition , inherited1__used_representation , ) def wr1(self): eval_wr1_wr = (('CONFIG_CONTROL_DESIGN.SHAPE_DEFINITION' == TYPEOF(self.self.definition.self.definition)) or ('CONFIG_CONTROL_DESIGN.PRODUCT_DEFINITION_SHAPE' == TYPEOF(self.self.definition))) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr def wr2(self): eval_wr2_wr = ('CONFIG_CONTROL_DESIGN.SHAPE_REPRESENTATION' == TYPEOF(self.self.used_representation)) if not eval_wr2_wr: raise AssertionError('Rule wr2 violated') else: return eval_wr2_wr #################### # ENTITY volume_unit # #################### class volume_unit(named_unit): '''Entity volume_unit definition. ''' def __init__( self , inherited0__dimensions , ): named_unit.__init__(self , inherited0__dimensions , ) def wr1(self): eval_wr1_wr = (((((((self.self.named_unit.self.dimensions.self.length_exponent == 3) and (self.self.named_unit.self.dimensions.self.mass_exponent == 0)) and (self.self.named_unit.self.dimensions.self.time_exponent == 0)) and (self.self.named_unit.self.dimensions.self.electric_current_exponent == 0)) and (self.self.named_unit.self.dimensions.self.thermodynamic_temperature_exponent == 0)) and (self.self.named_unit.self.dimensions.self.amount_of_substance_exponent == 0)) and (self.self.named_unit.self.dimensions.self.luminous_intensity_exponent == 0)) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY conical_surface # #################### class conical_surface(elementary_surface): '''Entity conical_surface definition. :param radius :type radius:length_measure :param semi_angle :type semi_angle:plane_angle_measure ''' def __init__( self , inherited0__name , inherited1__position , radius,semi_angle, ): elementary_surface.__init__(self , inherited0__name , inherited1__position , ) self.radius = radius self.semi_angle = semi_angle @apply def radius(): def fget( self ): return self._radius def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument radius is mantatory and can not be set to None') if not check_type(value,length_measure): self._radius = length_measure(value) else: self._radius = value return property(**locals()) @apply def semi_angle(): def fget( self ): return self._semi_angle def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument semi_angle is mantatory and can not be set to None') if not check_type(value,plane_angle_measure): self._semi_angle = plane_angle_measure(value) else: self._semi_angle = value return property(**locals()) def wr1(self): eval_wr1_wr = (self.radius >= 0) if not eval_wr1_wr: raise AssertionError('Rule wr1 violated') else: return eval_wr1_wr #################### # ENTITY global_unit_assigned_context # #################### class global_unit_assigned_context(representation_context): '''Entity global_unit_assigned_context definition. :param units :type units:SET(1,None,'unit', scope = schema_scope) ''' def __init__( self , inherited0__context_identifier , inherited1__context_type , units, ): representation_context.__init__(self , inherited0__context_identifier , inherited1__context_type , ) self.units = units @apply def units(): def fget( self ): return self._units def fset( self, value ): # Mandatory argument if value==None: raise AssertionError('Argument units is mantatory and can not be set to None') if not check_type(value,SET(1,None,'unit', scope = schema_scope)): self._units = SET(value) else: self._units = value return property(**locals()) #################### # FUNCTION build_2axes # #################### def build_2axes(ref_direction,): ''' :param ref_direction :type ref_direction:direction ''' return [d,orthogonal_complement(d)] #################### # FUNCTION item_in_context # #################### def item_in_context(item,cntxt,): ''' :param item :type item:representation_item :param cntxt :type cntxt:representation_context ''' if (SIZEOF(USEDIN(item,'CONFIG_CONTROL_DESIGN.REPRESENTATION.ITEMS') * cntxt.representations_in_context) > 0): return TRUE else: y = None if (SIZEOF(y) > 0): for i in range(1,HIINDEX(y),1): if (item_in_context(y[i],cntxt)): return TRUE return FALSE #################### # FUNCTION gbsf_check_point # #################### def gbsf_check_point(pnt,): ''' :param pnt :type pnt:point ''' if ('CONFIG_CONTROL_DESIGN.CARTESIAN_POINT' == TYPEOF(pnt)): return TRUE else: if ('CONFIG_CONTROL_DESIGN.POINT_ON_CURVE' == TYPEOF(pnt)): return gbsf_check_curve(pnt.point_on_curve.basis_curve) else: if ('CONFIG_CONTROL_DESIGN.POINT_ON_SURFACE' == TYPEOF(pnt)): return gbsf_check_surface(pnt.point_on_surface.basis_surface) else: if ('CONFIG_CONTROL_DESIGN.DEGENERATE_PCURVE' == TYPEOF(pnt)): return gbsf_check_curve(pnt.degenerate_pcurve.reference_to_curve.representation.items[1]) and gbsf_check_surface(pnt.degenerate_pcurve.basis_surface) return FALSE #################### # FUNCTION build_axes # #################### def build_axes(axis,ref_direction,): ''' :param axis :type axis:direction :param ref_direction :type ref_direction:direction ''' d1 = NVL(normalise(axis),dummy_gri == direction([0,0,1])) d2 = first_proj_axis(d1,ref_direction) return [d2,normalise(cross_product(d1,d2)).orientation,d1] #################### # FUNCTION edge_reversed # #################### def edge_reversed(an_edge,): ''' :param an_edge :type an_edge:edge ''' if ('CONFIG_CONTROL_DESIGN.ORIENTED_EDGE' == TYPEOF(an_edge)): the_reverse = (dummy_tri == edge(an_edge.edge_end,an_edge.edge_start)) == oriented_edge(an_edge.oriented_edge.edge_element, not an_edge.oriented_edge.orientation) else: the_reverse = (dummy_tri == edge(an_edge.edge_end,an_edge.edge_start)) == oriented_edge(an_edge,FALSE) return the_reverse #################### # FUNCTION cc_design_person_and_organization_correlation # #################### def cc_design_person_and_organization_correlation(e,): ''' :param e :type e:cc_design_person_and_organization_assignment ''' po_role = e.person_and_organization_assignment.role.name case_selector = po_role if case_selector == 'request_recipient': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'initiator': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'creator': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'part_supplier': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'design_supplier': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'design_owner': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'configuration_manager': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'contractor': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'classification_officer': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE else: return TRUE return TRUE #################### # FUNCTION constraints_composite_curve_on_surface # #################### def constraints_composite_curve_on_surface(c,): ''' :param c :type c:composite_curve_on_surface ''' for k in range(1,n_segments,1): if ((( not ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(c.composite_curve.segments[k].parent_curve))) and ( not ('CONFIG_CONTROL_DESIGN.SURFACE_CURVE' == TYPEOF(c.composite_curve.segments[k].parent_curve)))) and ( not ('CONFIG_CONTROL_DESIGN.COMPOSITE_CURVE_ON_SURFACE' == TYPEOF(c.composite_curve.segments[k].parent_curve)))): return FALSE return TRUE #################### # FUNCTION acyclic_mapped_representation # #################### def acyclic_mapped_representation(parent_set,children_set,): ''' :param parent_set :type parent_set:(null) :param children_set :type children_set:(null) ''' x = None if (SIZEOF(x) > 0): for i in range(1,HIINDEX(x),1): if (x[i].mapped_item.mapping_source.mapped_representation == parent_set): return FALSE if ( not acyclic_mapped_representation(parent_set + x[i].mapped_item.mapping_source.mapped_representation,x[i].mapped_item.mapping_source.mapped_representation.items)): return FALSE x = children_set - x if (SIZEOF(x) > 0): for i in range(1,HIINDEX(x),1): y = None if ( not acyclic_mapped_representation(parent_set,y)): return FALSE return TRUE #################### # FUNCTION conditional_reverse # #################### def conditional_reverse(p,an_item,): ''' :param p :type p:BOOLEAN :param an_item :type an_item:reversible_topology ''' if (p): return an_item else: return topology_reversed(an_item) #################### # FUNCTION valid_measure_value # #################### def valid_measure_value(m,): ''' :param m :type m:measure_value ''' if ('REAL' == TYPEOF(m)): return m > 0 else: if ('INTEGER' == TYPEOF(m)): return m > 0 else: return TRUE #################### # FUNCTION gbsf_check_curve # #################### def gbsf_check_curve(cv,): ''' :param cv :type cv:curve ''' if (SIZEOF(['CONFIG_CONTROL_DESIGN.BOUNDED_CURVE','CONFIG_CONTROL_DESIGN.CONIC','CONFIG_CONTROL_DESIGN.CURVE_REPLICA','CONFIG_CONTROL_DESIGN.LINE','CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D'] * TYPEOF(cv)) > 1): return FALSE else: if (SIZEOF(['CONFIG_CONTROL_DESIGN.CIRCLE','CONFIG_CONTROL_DESIGN.ELLIPSE'] * TYPEOF(cv)) == 1): return TRUE else: if ((('CONFIG_CONTROL_DESIGN.B_SPLINE_CURVE' == TYPEOF(cv)) and (cv.b_spline_curve.self_intersect == FALSE)) or (cv.b_spline_curve.self_intersect == UNKNOWN)): return TRUE else: if ((('CONFIG_CONTROL_DESIGN.COMPOSITE_CURVE' == TYPEOF(cv)) and (cv.composite_curve.self_intersect == FALSE)) or (cv.composite_curve.self_intersect == UNKNOWN)): return SIZEOF(None) == 0 else: if ('CONFIG_CONTROL_DESIGN.CURVE_REPLICA' == TYPEOF(cv)): return gbsf_check_curve(cv.curve_replica.parent_curve) else: if ((('CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D' == TYPEOF(cv)) and ((cv.offset_curve_3d.self_intersect == FALSE) or (cv.offset_curve_3d.self_intersect == UNKNOWN))) and ( not ('CONFIG_CONTROL_DESIGN.POLYLINE' == TYPEOF(cv.basis_curve)))): return gbsf_check_curve(cv.offset_curve_3d.basis_curve) else: if ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(cv)): return gbsf_check_curve(cv.pcurve.reference_to_curve.representation.items[1]) and gbsf_check_surface(cv.pcurve.basis_surface) else: if ('CONFIG_CONTROL_DESIGN.POLYLINE' == TYPEOF(cv)): if (SIZEOF(cv.polyline.points) >= 3): return TRUE else: if ('CONFIG_CONTROL_DESIGN.SURFACE_CURVE' == TYPEOF(cv)): if (gbsf_check_curve(cv.surface_curve.curve_3d)): for i in range(1,SIZEOF(cv.surface_curve.associated_geometry),1): if ('CONFIG_CONTROL_DESIGN.SURFACE' == TYPEOF(cv.surface_curve.associated_geometry[i])): if ( not gbsf_check_surface(cv.surface_curve.associated_geometry[i])): return FALSE else: if ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(cv.surface_curve.associated_geometry[i])): if ( not gbsf_check_curve(cv.surface_curve.associated_geometry[i])): return FALSE return TRUE else: if ('CONFIG_CONTROL_DESIGN.TRIMMED_CURVE' == TYPEOF(cv)): if (SIZEOF(['CONFIG_CONTROL_DESIGN.LINE','CONFIG_CONTROL_DESIGN.PARABOLA','CONFIG_CONTROL_DESIGN.HYPERBOLA'] * TYPEOF(cv.trimmed_curve.basis_curve)) == 1): return TRUE else: return gbsf_check_curve(cv.trimmed_curve.basis_curve) return FALSE #################### # FUNCTION unique_version_change_order # #################### def unique_version_change_order(c,): ''' :param c :type c:action ''' for i in range(1,SIZEOF(ords.requests),1): assign = assign + None for k in range(1,SIZEOF(assign),1): versions = versions + assign[k].items return SIZEOF(None) == 0 #################### # FUNCTION base_axis # #################### def base_axis(dim,axis1,axis2,axis3,): ''' :param dim :type dim:INTEGER :param axis1 :type axis1:direction :param axis2 :type axis2:direction :param axis3 :type axis3:direction ''' if (dim == 3): d1 = NVL(normalise(axis3),dummy_gri == direction([0,0,1])) d2 = first_proj_axis(d1,axis1) u = [d2,second_proj_axis(d1,d2,axis2),d1] else: if (EXISTS(axis1)): d1 = normalise(axis1) u = [d1,orthogonal_complement(d1)] if (EXISTS(axis2)): factor = dot_product(axis2,u[2]) if (factor < 0): u[2].direction_ratios[1] = -u[2].direction_ratios[1] u[2].direction_ratios[2] = -u[2].direction_ratios[2] else: if (EXISTS(axis2)): d1 = normalise(axis2) u = [orthogonal_complement(d1),d1] u[1].direction_ratios[1] = -u[1].direction_ratios[1] u[1].direction_ratios[2] = -u[1].direction_ratios[2] else: u = [dummy_gri == direction([1,0]),dummy_gri == direction([0,1])] return u #################### # FUNCTION get_basis_surface # #################### def get_basis_surface(c,): ''' :param c :type c:curve_on_surface ''' surfs = [] if ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(c)): surfs = [c.pcurve.basis_surface] else: if ('CONFIG_CONTROL_DESIGN.SURFACE_CURVE' == TYPEOF(c)): n = SIZEOF(c.surface_curve.associated_geometry) for i in range(1,n,1): surfs = surfs + associated_surface(c.surface_curve.associated_geometry[i]) if ('CONFIG_CONTROL_DESIGN.COMPOSITE_CURVE_ON_SURFACE' == TYPEOF(c)): n = SIZEOF(c.composite_curve.segments) surfs = get_basis_surface(c.composite_curve.segments[1].parent_curve) if (n > 1): for i in range(2,n,1): surfs = surfs * get_basis_surface(c.composite_curve.segments[i].parent_curve) return surfs #################### # FUNCTION cc_design_date_time_correlation # #################### def cc_design_date_time_correlation(e,): ''' :param e :type e:cc_design_date_and_time_assignment ''' dt_role = e.date_and_time_assignment.role.name case_selector = dt_role if case_selector == 'creation_date': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'request_date': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'release_date': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'start_date': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'sign_off_date': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'contract_date': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'certification_date': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'classification_date': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE elif case_selector == 'declassification_date': if (SIZEOF(e.items) != SIZEOF(None)): return FALSE else: return TRUE return TRUE #################### # FUNCTION list_face_loops # #################### def list_face_loops(f,): ''' :param f :type f:face ''' for i in range(1,SIZEOF(f.bounds),1): loops = loops + f.bounds[i].bound return loops #################### # FUNCTION list_of_topology_reversed # #################### def list_of_topology_reversed(a_list,): ''' :param a_list :type a_list:list_of_reversible_topology_item ''' the_reverse = [] for i in range(1,SIZEOF(a_list),1): the_reverse = topology_reversed(a_list[i]) + the_reverse return the_reverse #################### # FUNCTION msf_curve_check # #################### def msf_curve_check(cv,): ''' :param cv :type cv:curve ''' if (SIZEOF(['CONFIG_CONTROL_DESIGN.BOUNDED_CURVE','CONFIG_CONTROL_DESIGN.CONIC','CONFIG_CONTROL_DESIGN.CURVE_REPLICA','CONFIG_CONTROL_DESIGN.LINE','CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D'] * TYPEOF(cv)) > 1): return FALSE else: if ((('CONFIG_CONTROL_DESIGN.B_SPLINE_CURVE' == TYPEOF(cv)) and (cv.b_spline_curve.self_intersect == FALSE)) or (cv.b_spline_curve.self_intersect == UNKNOWN)): return TRUE else: if (SIZEOF(['CONFIG_CONTROL_DESIGN.CONIC','CONFIG_CONTROL_DESIGN.LINE'] * TYPEOF(cv)) == 1): return TRUE else: if ('CONFIG_CONTROL_DESIGN.CURVE_REPLICA' == TYPEOF(cv)): return msf_curve_check(cv.curve_replica.parent_curve) else: if ((('CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D' == TYPEOF(cv)) and ((cv.offset_curve_3d.self_intersect == FALSE) or (cv.offset_curve_3d.self_intersect == UNKNOWN))) and ( not ('CONFIG_CONTROL_DESIGN.POLYLINE' == TYPEOF(cv.basis_curve)))): return msf_curve_check(cv.offset_curve_3d.basis_curve) else: if ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(cv)): return msf_curve_check(cv.pcurve.reference_to_curve.representation.items[1]) and msf_surface_check(cv.pcurve.basis_surface) else: if ('CONFIG_CONTROL_DESIGN.SURFACE_CURVE' == TYPEOF(cv)): if (msf_curve_check(cv.surface_curve.curve_3d)): for i in range(1,SIZEOF(cv.surface_curve.associated_geometry),1): if ('CONFIG_CONTROL_DESIGN.SURFACE' == TYPEOF(cv.surface_curve.associated_geometry[i])): if ( not msf_surface_check(cv.surface_curve.associated_geometry[i])): return FALSE else: if ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(cv.surface_curve.associated_geometry[i])): if ( not msf_curve_check(cv.surface_curve.associated_geometry[i])): return FALSE return TRUE else: if ('CONFIG_CONTROL_DESIGN.POLYLINE' == TYPEOF(cv)): if (SIZEOF(cv.polyline.points) >= 3): return TRUE return FALSE #################### # FUNCTION shell_reversed # #################### def shell_reversed(a_shell,): ''' :param a_shell :type a_shell:shell ''' if ('CONFIG_CONTROL_DESIGN.OPEN_SHELL' == TYPEOF(a_shell)): return open_shell_reversed(a_shell) else: if ('CONFIG_CONTROL_DESIGN.CLOSED_SHELL' == TYPEOF(a_shell)): return closed_shell_reversed(a_shell) else: return None #################### # FUNCTION topology_reversed # #################### def topology_reversed(an_item,): ''' :param an_item :type an_item:reversible_topology ''' if ('CONFIG_CONTROL_DESIGN.EDGE' == TYPEOF(an_item)): return edge_reversed(an_item) if ('CONFIG_CONTROL_DESIGN.PATH' == TYPEOF(an_item)): return path_reversed(an_item) if ('CONFIG_CONTROL_DESIGN.FACE_BOUND' == TYPEOF(an_item)): return face_bound_reversed(an_item) if ('CONFIG_CONTROL_DESIGN.FACE' == TYPEOF(an_item)): return face_reversed(an_item) if ('CONFIG_CONTROL_DESIGN.SHELL' == TYPEOF(an_item)): return shell_reversed(an_item) if ('SET' == TYPEOF(an_item)): return set_of_topology_reversed(an_item) if ('LIST' == TYPEOF(an_item)): return list_of_topology_reversed(an_item) return None #################### # FUNCTION first_proj_axis # #################### def first_proj_axis(z_axis,arg,): ''' :param z_axis :type z_axis:direction :param arg :type arg:direction ''' if ( not EXISTS(z_axis)): return None else: z = normalise(z_axis) if ( not EXISTS(arg)): if (z.direction_ratios != [1,0,0]): v = dummy_gri == direction([1,0,0]) else: v = dummy_gri == direction([0,1,0]) else: if (arg.dim != 3): return None if (cross_product(arg,z).magnitude == 0): return None else: v = normalise(arg) x_vec = scalar_times_vector(dot_product(v,z),z) x_axis = vector_difference(v,x_vec).orientation x_axis = normalise(x_axis) return x_axis #################### # FUNCTION orthogonal_complement # #################### def orthogonal_complement(vec,): ''' :param vec :type vec:direction ''' if ((vec.dim != 2) or ( not EXISTS(vec))): return None else: result = dummy_gri == direction([-vec.direction_ratios[2],vec.direction_ratios[1]]) return result #################### # FUNCTION make_array_of_array # #################### def make_array_of_array(lis,low1,u1,low2,u2,): ''' :param lis :type lis:(null) :param low1 :type low1:INTEGER :param u1 :type u1:INTEGER :param low2 :type low2:INTEGER :param u2 :type u2:INTEGER ''' if (((u1 - low1) + 1) != SIZEOF(lis)): return None if (((u2 - low2) + 1) != SIZEOF(lis[1])): return None res = [list_to_array(lis[1],low2,u2),(u1 - low1) + 1] for i in range(2,HIINDEX(lis),1): if (((u2 - low2) + 1) != SIZEOF(lis[i])): return None res[(low1 + i) - 1] = list_to_array(lis[i],low2,u2) return res #################### # FUNCTION second_proj_axis # #################### def second_proj_axis(z_axis,x_axis,arg,): ''' :param z_axis :type z_axis:direction :param x_axis :type x_axis:direction :param arg :type arg:direction ''' if ( not EXISTS(arg)): v = dummy_gri == direction([0,1,0]) else: v = arg temp = scalar_times_vector(dot_product(v,z_axis),z_axis) y_axis = vector_difference(v,temp) temp = scalar_times_vector(dot_product(v,x_axis),x_axis) y_axis = vector_difference(y_axis,temp) y_axis = normalise(y_axis) return y_axis.orientation #################### # FUNCTION bag_to_set # #################### def bag_to_set(the_bag,): ''' :param the_bag :type the_bag:(null) ''' if (SIZEOF(the_bag) > 0): for i in range(1,HIINDEX(the_bag),1): the_set = the_set + the_bag[i] return the_set #################### # FUNCTION valid_wireframe_edge_curve # #################### def valid_wireframe_edge_curve(crv,): ''' :param crv :type crv:curve ''' if (SIZEOF(['CONFIG_CONTROL_DESIGN.LINE','CONFIG_CONTROL_DESIGN.CONIC','CONFIG_CONTROL_DESIGN.B_SPLINE_CURVE','CONFIG_CONTROL_DESIGN.POLYLINE'] * TYPEOF(crv)) == 1): return TRUE else: if ('CONFIG_CONTROL_DESIGN.CURVE_REPLICA' == TYPEOF(crv)): return valid_wireframe_edge_curve(crv.curve_replica.parent_curve) else: if ('CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D' == TYPEOF(crv)): return valid_wireframe_edge_curve(crv.offset_curve_3d.basis_curve) return FALSE #################### # FUNCTION acyclic_product_category_relationship # #################### def acyclic_product_category_relationship(relation,children,): ''' :param relation :type relation:product_category_relationship :param children :type children:(null) ''' for i in range(1,HIINDEX(children),1): if (relation.category == children[i]): return FALSE x = bag_to_set(USEDIN(relation.category,'CONFIG_CONTROL_DESIGN.' + 'PRODUCT_CATEGORY_RELATIONSHIP.SUB_CATEGORY')) local_children = children + relation.category if (SIZEOF(x) > 0): for i in range(1,HIINDEX(x),1): if ( not acyclic_product_category_relationship(x[i],local_children)): return FALSE return TRUE #################### # FUNCTION surface_weights_positive # #################### def surface_weights_positive(b,): ''' :param b :type b:rational_b_spline_surface ''' for i in range(0,b.u_upper,1): for j in range(0,b.v_upper,1): if (b.weights[i][j] <= 0): result = FALSE return result return result #################### # FUNCTION vector_difference # #################### def vector_difference(arg1,arg2,): ''' :param arg1 :type arg1:vector_or_direction :param arg2 :type arg2:vector_or_direction ''' if ((( not EXISTS(arg1)) or ( not EXISTS(arg2))) or (arg1.dim != arg2.dim)): return None else: # begin/end block if ('CONFIG_CONTROL_DESIGN.VECTOR' == TYPEOF(arg1)): mag1 = arg1.magnitude vec1 = arg1.orientation else: mag1 = 1 vec1 = arg1 if ('CONFIG_CONTROL_DESIGN.VECTOR' == TYPEOF(arg2)): mag2 = arg2.magnitude vec2 = arg2.orientation else: mag2 = 1 vec2 = arg2 vec1 = normalise(vec1) vec2 = normalise(vec2) ndim = SIZEOF(vec1.direction_ratios) mag = 0 res = dummy_gri == direction(vec1.direction_ratios) for i in range(1,ndim,1): res.direction_ratios[i] = (mag1 * vec1.direction_ratios[i]) + (mag2 * vec2.direction_ratios[i]) mag = mag + (res.direction_ratios[i] * res.direction_ratios[i]) if (mag > 0): result = dummy_gri == vector(res,SQRT(mag)) else: result = dummy_gri == vector(vec1,0) return result #################### # FUNCTION acyclic_product_definition_relationship # #################### def acyclic_product_definition_relationship(relation,relatives,specific_relation,): ''' :param relation :type relation:product_definition_relationship :param relatives :type relatives:(null) :param specific_relation :type specific_relation:STRING ''' if (relation.relating_product_definition == relatives): return FALSE x = None for i in range(1,HIINDEX(x),1): if ( not acyclic_product_definition_relationship(x[i],relatives + relation.relating_product_definition,specific_relation)): return FALSE return TRUE #################### # FUNCTION constraints_geometry_shell_based_wireframe_model # #################### def constraints_geometry_shell_based_wireframe_model(m,): ''' :param m :type m:shell_based_wireframe_model ''' for j in range(1,SIZEOF(m.sbwm_boundary),1): if (( not ('CONFIG_CONTROL_DESIGN.WIRE_SHELL' == TYPEOF(m.sbwm_boundary[j]))) and ( not ('CONFIG_CONTROL_DESIGN.VERTEX_SHELL' == TYPEOF(m.sbwm_boundary[j])))): result = FALSE return result return result #################### # FUNCTION list_to_set # #################### def list_to_set(l,): ''' :param l :type l:(null) ''' for i in range(1,SIZEOF(l),1): s = s + l[i] return s #################### # FUNCTION valid_calendar_date # #################### def valid_calendar_date(date,): ''' :param date :type date:calendar_date ''' if ( not ((1 <= date.day_component) and (date.day_component <= 31))): return FALSE case_selector = date.month_component if case_selector == 4: return (1 <= date.day_component) and (date.day_component <= 30) elif case_selector == 6: return (1 <= date.day_component) and (date.day_component <= 30) elif case_selector == 9: return (1 <= date.day_component) and (date.day_component <= 30) elif case_selector == 11: return (1 <= date.day_component) and (date.day_component <= 30) elif case_selector == 2: # begin/end block if (leap_year(date.year_component)): return (1 <= date.day_component) and (date.day_component <= 29) else: return (1 <= date.day_component) and (date.day_component <= 28) else: return TRUE #################### # FUNCTION valid_wireframe_vertex_point # #################### def valid_wireframe_vertex_point(pnt,): ''' :param pnt :type pnt:point ''' if ('CONFIG_CONTROL_DESIGN.CARTESIAN_POINT' == TYPEOF(pnt)): return TRUE else: if ('CONFIG_CONTROL_DESIGN.POINT_REPLICA' == TYPEOF(pnt)): return valid_wireframe_vertex_point(pnt.point_replica.parent_pt) return FALSE #################### # FUNCTION list_to_array # #################### def list_to_array(lis,low,u,): ''' :param lis :type lis:(null) :param low :type low:INTEGER :param u :type u:INTEGER ''' n = SIZEOF(lis) if (n != ((u - low) + 1)): return None else: res = [lis[1],n] for i in range(2,n,1): res[(low + i) - 1] = lis[i] return res #################### # FUNCTION using_items # #################### def using_items(item,checked_items,): ''' :param item :type item:founded_item_select :param checked_items :type checked_items:(null) ''' result_items = [] new_check_items = checked_items + item next_items = None if (SIZEOF(next_items) > 0): for i in range(1,HIINDEX(next_items),1): if ( not (next_items[i] == new_check_items)): result_items = (result_items + next_items[i]) + using_items(next_items[i],new_check_items) return result_items #################### # FUNCTION constraints_geometry_shell_based_surface_model # #################### def constraints_geometry_shell_based_surface_model(m,): ''' :param m :type m:shell_based_surface_model ''' for j in range(1,SIZEOF(m.sbsm_boundary),1): if (( not ('CONFIG_CONTROL_DESIGN.OPEN_SHELL' == TYPEOF(m.sbsm_boundary[j]))) and ( not ('CONFIG_CONTROL_DESIGN.CLOSED_SHELL' == TYPEOF(m.sbsm_boundary[j])))): result = FALSE return result return result #################### # FUNCTION face_bound_reversed # #################### def face_bound_reversed(a_face_bound,): ''' :param a_face_bound :type a_face_bound:face_bound ''' if ('CONFIG_CONTROL_DESIGN.FACE_OUTER_BOUND' == TYPEOF(a_face_bound)): the_reverse = (dummy_tri == face_bound(a_face_bound.face_bound.bound, not a_face_bound.face_bound.orientation)) == face_outer_bound() else: the_reverse = dummy_tri == face_bound(a_face_bound.bound, not a_face_bound.orientation) return the_reverse #################### # FUNCTION set_of_topology_reversed # #################### def set_of_topology_reversed(a_set,): ''' :param a_set :type a_set:set_of_reversible_topology_item ''' the_reverse = [] for i in range(1,SIZEOF(a_set),1): the_reverse = the_reverse + topology_reversed(a_set[i]) return the_reverse #################### # FUNCTION dimension_of # #################### def dimension_of(item,): ''' :param item :type item:geometric_representation_item ''' x = using_representations(item) y = x[1].context_of_items return y.geometric_representation_context.coordinate_space_dimension #################### # FUNCTION scalar_times_vector # #################### def scalar_times_vector(scalar,vec,): ''' :param scalar :type scalar:REAL :param vec :type vec:vector_or_direction ''' if (( not EXISTS(scalar)) or ( not EXISTS(vec))): return None else: if ('CONFIG_CONTROL_DESIGN.VECTOR' == TYPEOF(vec)): v = dummy_gri == direction(vec.orientation.direction_ratios) mag = scalar * vec.magnitude else: v = dummy_gri == direction(vec.direction_ratios) mag = scalar if (mag < 0): for i in range(1,SIZEOF(v.direction_ratios),1): v.direction_ratios[i] = -v.direction_ratios[i] mag = -mag result = dummy_gri == vector(normalise(v),mag) return result #################### # FUNCTION dimensions_for_si_unit # #################### def dimensions_for_si_unit(n,): ''' :param n :type n:si_unit_name ''' case_selector = n if case_selector == metre: return dimensional_exponents(1,0,0,0,0,0,0) elif case_selector == gram: return dimensional_exponents(0,1,0,0,0,0,0) elif case_selector == second: return dimensional_exponents(0,0,1,0,0,0,0) elif case_selector == ampere: return dimensional_exponents(0,0,0,1,0,0,0) elif case_selector == kelvin: return dimensional_exponents(0,0,0,0,1,0,0) elif case_selector == mole: return dimensional_exponents(0,0,0,0,0,1,0) elif case_selector == candela: return dimensional_exponents(0,0,0,0,0,0,1) elif case_selector == radian: return dimensional_exponents(0,0,0,0,0,0,0) elif case_selector == steradian: return dimensional_exponents(0,0,0,0,0,0,0) elif case_selector == hertz: return dimensional_exponents(0,0,-1,0,0,0,0) elif case_selector == newton: return dimensional_exponents(1,1,-2,0,0,0,0) elif case_selector == pascal: return dimensional_exponents(-1,1,-2,0,0,0,0) elif case_selector == joule: return dimensional_exponents(2,1,-2,0,0,0,0) elif case_selector == watt: return dimensional_exponents(2,1,-3,0,0,0,0) elif case_selector == coulomb: return dimensional_exponents(0,0,1,1,0,0,0) elif case_selector == volt: return dimensional_exponents(2,1,-3,-1,0,0,0) elif case_selector == farad: return dimensional_exponents(-2,-1,4,1,0,0,0) elif case_selector == ohm: return dimensional_exponents(2,1,-3,-2,0,0,0) elif case_selector == siemens: return dimensional_exponents(-2,-1,3,2,0,0,0) elif case_selector == weber: return dimensional_exponents(2,1,-2,-1,0,0,0) elif case_selector == tesla: return dimensional_exponents(0,1,-2,-1,0,0,0) elif case_selector == henry: return dimensional_exponents(2,1,-2,-2,0,0,0) elif case_selector == degree_celsius: return dimensional_exponents(0,0,0,0,1,0,0) elif case_selector == lumen: return dimensional_exponents(0,0,0,0,0,0,1) elif case_selector == lux: return dimensional_exponents(-2,0,0,0,0,0,1) elif case_selector == becquerel: return dimensional_exponents(0,0,-1,0,0,0,0) elif case_selector == gray: return dimensional_exponents(2,0,-2,0,0,0,0) elif case_selector == sievert: return dimensional_exponents(2,0,-2,0,0,0,0) #################### # FUNCTION assembly_shape_is_defined # #################### def assembly_shape_is_defined(assy,schma,): ''' :param assy :type assy:next_assembly_usage_occurrence :param schma :type schma:STRING ''' pr1_set = bag_to_set(USEDIN(assy.related_product_definition,schma + '.PROPERTY_DEFINITION.DEFINITION')) for i in range(1,HIINDEX(pr1_set),1): sdr_set = sdr_set + None pdrel_set = bag_to_set(USEDIN(assy.related_product_definition,(schma + '.PRODUCT_DEFINITION_RELATIONSHIP.') + 'RELATED_PRODUCT_DEFINITION')) for j in range(1,HIINDEX(pdrel_set),1): pr2_set = pr2_set + USEDIN(pdrel_set[j],schma + '.PROPERTY_DEFINITION.DEFINITION') for i in range(1,HIINDEX(pr2_set),1): sdr_set = sdr_set + None if (SIZEOF(sdr_set) > 0): for i in range(1,HIINDEX(sdr_set),1): srr_set = None if (SIZEOF(srr_set) > 0): for j in range(1,HIINDEX(srr_set),1): if (SIZEOF(None * None) >= 1): if (SIZEOF(None) > 0): return FALSE return TRUE #################### # FUNCTION open_shell_reversed # #################### def open_shell_reversed(a_shell,): ''' :param a_shell :type a_shell:open_shell ''' if ('CONFIG_CONTROL_DESIGN.ORIENTED_OPEN_SHELL' == TYPEOF(a_shell)): the_reverse = ((dummy_tri == connected_face_set(a_shell.connected_face_set.cfs_faces)) == open_shell()) == oriented_open_shell(a_shell.oriented_open_shell.open_shell_element, not a_shell.oriented_open_shell.orientation) else: the_reverse = ((dummy_tri == connected_face_set(a_shell.connected_face_set.cfs_faces)) == open_shell()) == oriented_open_shell(a_shell,FALSE) return the_reverse #################### # FUNCTION acyclic_surface_replica # #################### def acyclic_surface_replica(rep,parent,): ''' :param rep :type rep:surface_replica :param parent :type parent:surface ''' if ( not ('CONFIG_CONTROL_DESIGN.SURFACE_REPLICA' == TYPEOF(parent))): return TRUE if (parent == rep): return FALSE else: return acyclic_surface_replica(rep,parent.surface_replica.parent_surface) #################### # FUNCTION gbsf_check_surface # #################### def gbsf_check_surface(sf,): ''' :param sf :type sf:surface ''' if ((('CONFIG_CONTROL_DESIGN.B_SPLINE_SURFACE' == TYPEOF(sf)) and (sf.b_spline_surface.self_intersect == FALSE)) or (sf.b_spline_surface.self_intersect == UNKNOWN)): return TRUE else: if (SIZEOF(['CONFIG_CONTROL_DESIGN.SPHERICAL_SURFACE','CONFIG_CONTROL_DESIGN.TOROIDAL_SURFACE'] * TYPEOF(sf)) == 1): return TRUE else: if ('CONFIG_CONTROL_DESIGN.CURVE_BOUNDED_SURFACE' == TYPEOF(sf)): if (SIZEOF(['CONFIG_CONTROL_DESIGN.CONICAL_SURFACE','CONFIG_CONTROL_DESIGN.CYLINDRICAL_SURFACE','CONFIG_CONTROL_DESIGN.PLANE'] * TYPEOF(sf.curve_bounded_surface.basis_surface)) == 1): return SIZEOF(None) == 0 else: if (gbsf_check_surface(sf.curve_bounded_surface.basis_surface)): return SIZEOF(None) == 0 else: if ((('CONFIG_CONTROL_DESIGN.OFFSET_SURFACE' == TYPEOF(sf)) and (sf.offset_surface.self_intersect == FALSE)) or (sf.offset_surface.self_intersect == UNKNOWN)): return gbsf_check_surface(sf.offset_surface.basis_surface) else: if ('CONFIG_CONTROL_DESIGN.RECTANGULAR_COMPOSITE_SURFACE' == TYPEOF(sf)): for i in range(1,SIZEOF(sf.rectangular_composite_surface.segments),1): for j in range(1,SIZEOF(sf.rectangular_composite_surface.segments[i]),1): if ( not gbsf_check_surface(sf.rectangular_composite_surface.segments[i][j].parent_surface)): return FALSE return TRUE else: if ('CONFIG_CONTROL_DESIGN.RECTANGULAR_TRIMMED_SURFACE' == TYPEOF(sf)): if (SIZEOF(['CONFIG_CONTROL_DESIGN.CONICAL_SURFACE','CONFIG_CONTROL_DESIGN.CYLINDRICAL_SURFACE','CONFIG_CONTROL_DESIGN.PLANE'] * TYPEOF(sf.rectangular_trimmed_surface.basis_surface)) == 1): return TRUE else: return gbsf_check_surface(sf.rectangular_trimmed_surface.basis_surface) else: if ('CONFIG_CONTROL_DESIGN.SURFACE_REPLICA' == TYPEOF(sf)): return gbsf_check_surface(sf.surface_replica.parent_surface) else: if ('CONFIG_CONTROL_DESIGN.SWEPT_SURFACE' == TYPEOF(sf)): return gbsf_check_curve(sf.swept_surface.swept_curve) return FALSE #################### # FUNCTION msf_surface_check # #################### def msf_surface_check(surf,): ''' :param surf :type surf:surface ''' if ('CONFIG_CONTROL_DESIGN.ELEMENTARY_SURFACE' == TYPEOF(surf)): return TRUE else: if ('CONFIG_CONTROL_DESIGN.SWEPT_SURFACE' == TYPEOF(surf)): return msf_curve_check(surf.swept_surface.swept_curve) else: if ((('CONFIG_CONTROL_DESIGN.OFFSET_SURFACE' == TYPEOF(surf)) and (surf.offset_surface.self_intersect == FALSE)) or (surf.offset_surface.self_intersect == UNKNOWN)): return msf_surface_check(surf.offset_surface.basis_surface) else: if ('CONFIG_CONTROL_DESIGN.SURFACE_REPLICA' == TYPEOF(surf)): return msf_surface_check(surf.surface_replica.parent_surface) else: if ((('CONFIG_CONTROL_DESIGN.B_SPLINE_SURFACE' == TYPEOF(surf)) and (surf.b_spline_surface.self_intersect == FALSE)) or (surf.b_spline_surface.self_intersect == UNKNOWN)): return TRUE return FALSE #################### # FUNCTION normalise # #################### def normalise(arg,): ''' :param arg :type arg:vector_or_direction ''' if ( not EXISTS(arg)): result = None else: ndim = arg.dim if ('CONFIG_CONTROL_DESIGN.VECTOR' == TYPEOF(arg)): # begin/end block v = dummy_gri == direction(arg.orientation.direction_ratios) if (arg.magnitude == 0): return None else: vec = dummy_gri == vector(v,1) else: v = dummy_gri == direction(arg.direction_ratios) mag = 0 for i in range(1,ndim,1): mag = mag + (v.direction_ratios[i] * v.direction_ratios[i]) if (mag > 0): mag = SQRT(mag) for i in range(1,ndim,1): v.direction_ratios[i] = v.direction_ratios[i] / mag if ('CONFIG_CONTROL_DESIGN.VECTOR' == TYPEOF(arg)): vec.orientation = v result = vec else: result = v else: return None return result #################### # FUNCTION msb_shells # #################### def msb_shells(brep,): ''' :param brep :type brep:manifold_solid_brep ''' if (SIZEOF(None) >= 1): return brep.brep_with_voids.voids + brep.outer else: return [brep.outer] #################### # FUNCTION mixed_loop_type_set # #################### def mixed_loop_type_set(l,): ''' :param l :type l:(null) ''' if (SIZEOF(l) <= 1): return FALSE poly_loop_type = 'CONFIG_CONTROL_DESIGN.POLY_LOOP' == TYPEOF(l[1]) for i in range(2,SIZEOF(l),1): if (('CONFIG_CONTROL_DESIGN.POLY_LOOP' == TYPEOF(l[i])) != poly_loop_type): return TRUE return FALSE #################### # FUNCTION derive_dimensional_exponents # #################### def derive_dimensional_exponents(x,): ''' :param x :type x:unit ''' result = x.dimensions return result #################### # FUNCTION curve_weights_positive # #################### def curve_weights_positive(b,): ''' :param b :type b:rational_b_spline_curve ''' for i in range(0,b.upper_index_on_control_points,1): if (b.weights[i] <= 0): result = FALSE return result return result #################### # FUNCTION valid_geometrically_bounded_wf_point # #################### def valid_geometrically_bounded_wf_point(pnt,): ''' :param pnt :type pnt:point ''' if ('CONFIG_CONTROL_DESIGN.CARTESIAN_POINT' == TYPEOF(pnt)): return TRUE else: if ('CONFIG_CONTROL_DESIGN.POINT_ON_CURVE' == TYPEOF(pnt)): return valid_geometrically_bounded_wf_curve(pnt.point_on_curve.basis_curve) else: if ('CONFIG_CONTROL_DESIGN.POINT_REPLICA' == TYPEOF(pnt)): return valid_geometrically_bounded_wf_point(pnt.point_replica.parent_pt) return FALSE #################### # FUNCTION path_head_to_tail # #################### def path_head_to_tail(a_path,): ''' :param a_path :type a_path:path ''' n = SIZEOF(a_path.edge_list) for i in range(2,n,1): p = p and (a_path.edge_list[i - 1].edge_end == a_path.edge_list[i].edge_start) return p #################### # FUNCTION path_reversed # #################### def path_reversed(a_path,): ''' :param a_path :type a_path:path ''' if ('CONFIG_CONTROL_DESIGN.ORIENTED_PATH' == TYPEOF(a_path)): the_reverse = (dummy_tri == path(list_of_topology_reversed(a_path.edge_list))) == oriented_path(a_path.oriented_path.path_element, not a_path.oriented_path.orientation) else: the_reverse = (dummy_tri == path(list_of_topology_reversed(a_path.edge_list))) == oriented_path(a_path,FALSE) return the_reverse #################### # FUNCTION leap_year # #################### def leap_year(year,): ''' :param year :type year:INTEGER ''' if ((((year % 4) == 0) and ((year % 100) != 0)) or ((year % 400) == 0)): return TRUE else: return FALSE #################### # FUNCTION face_reversed # #################### def face_reversed(a_face,): ''' :param a_face :type a_face:face ''' if ('CONFIG_CONTROL_DESIGN.ORIENTED_FACE' == TYPEOF(a_face)): the_reverse = (dummy_tri == face(set_of_topology_reversed(a_face.bounds))) == oriented_face(a_face.oriented_face.face_element, not a_face.oriented_face.orientation) else: the_reverse = (dummy_tri == face(set_of_topology_reversed(a_face.bounds))) == oriented_face(a_face,FALSE) return the_reverse #################### # FUNCTION constraints_param_b_spline # #################### def constraints_param_b_spline(degree,up_knots,up_cp,knot_mult,knots,): ''' :param degree :type degree:INTEGER :param up_knots :type up_knots:INTEGER :param up_cp :type up_cp:INTEGER :param knot_mult :type knot_mult:(null) :param knots :type knots:(null) ''' sum = knot_mult[1] for i in range(2,up_knots,1): sum = sum + knot_mult[i] if ((((degree < 1) or (up_knots < 2)) or (up_cp < degree)) or (sum != ((degree + up_cp) + 2))): result = FALSE return result k = knot_mult[1] if ((k < 1) or (k > (degree + 1))): result = FALSE return result for i in range(2,up_knots,1): if ((knot_mult[i] < 1) or (knots[i] <= knots[i - 1])): result = FALSE return result k = knot_mult[i] if ((i < up_knots) and (k > degree)): result = FALSE return result if ((i == up_knots) and (k > (degree + 1))): result = FALSE return result return result #################### # FUNCTION using_representations # #################### def using_representations(item,): ''' :param item :type item:founded_item_select ''' results = [] result_bag = USEDIN(item,'CONFIG_CONTROL_DESIGN.REPRESENTATION.ITEMS') if (SIZEOF(result_bag) > 0): for i in range(1,HIINDEX(result_bag),1): results = results + result_bag[i] intermediate_items = using_items(item,[]) if (SIZEOF(intermediate_items) > 0): for i in range(1,HIINDEX(intermediate_items),1): result_bag = USEDIN(intermediate_items[i],'CONFIG_CONTROL_DESIGN.REPRESENTATION.ITEMS') if (SIZEOF(result_bag) > 0): for j in range(1,HIINDEX(result_bag),1): results = results + result_bag[j] return results #################### # FUNCTION associated_surface # #################### def associated_surface(arg,): ''' :param arg :type arg:pcurve_or_surface ''' if ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(arg)): surf = arg.basis_surface else: surf = arg return surf #################### # FUNCTION acyclic_point_replica # #################### def acyclic_point_replica(rep,parent,): ''' :param rep :type rep:point_replica :param parent :type parent:point ''' if ( not ('CONFIG_CONTROL_DESIGN.POINT_REPLICA' == TYPEOF(parent))): return TRUE if (parent == rep): return FALSE else: return acyclic_point_replica(rep,parent.point_replica.parent_pt) #################### # FUNCTION cross_product # #################### def cross_product(arg1,arg2,): ''' :param arg1 :type arg1:direction :param arg2 :type arg2:direction ''' if (((( not EXISTS(arg1)) or (arg1.dim == 2)) or ( not EXISTS(arg2))) or (arg2.dim == 2)): return None else: # begin/end block v1 = normalise(arg1).direction_ratios v2 = normalise(arg2).direction_ratios res = dummy_gri == direction([(v1[2] * v2[3]) - (v1[3] * v2[2]),(v1[3] * v2[1]) - (v1[1] * v2[3]),(v1[1] * v2[2]) - (v1[2] * v2[1])]) mag = 0 for i in range(1,3,1): mag = mag + (res.direction_ratios[i] * res.direction_ratios[i]) if (mag > 0): result = dummy_gri == vector(res,SQRT(mag)) else: result = dummy_gri == vector(arg1,0) return result #################### # FUNCTION valid_units # #################### def valid_units(m,): ''' :param m :type m:measure_with_unit ''' if ('CONFIG_CONTROL_DESIGN.LENGTH_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(1,0,0,0,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.MASS_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,1,0,0,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.TIME_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,0,1,0,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.ELECTRIC_CURRENT_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,0,0,1,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.THERMODYNAMIC_TEMPERATURE_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,0,0,0,1,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.AMOUNT_OF_SUBSTANCE_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,0,0,0,0,1,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.LUMINOUS_INTENSITY_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,0,0,0,0,0,1)): return FALSE if ('CONFIG_CONTROL_DESIGN.PLANE_ANGLE_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,0,0,0,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.SOLID_ANGLE_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,0,0,0,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.AREA_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(2,0,0,0,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.VOLUME_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(3,0,0,0,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.RATIO_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,0,0,0,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.POSITIVE_LENGTH_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(1,0,0,0,0,0,0)): return FALSE if ('CONFIG_CONTROL_DESIGN.POSITIVE_PLANE_ANGLE_MEASURE' == TYPEOF(m.value_component)): if (derive_dimensional_exponents(m.unit_component) != dimensional_exponents(0,0,0,0,0,0,0)): return FALSE return TRUE #################### # FUNCTION constraints_rectangular_composite_surface # #################### def constraints_rectangular_composite_surface(s,): ''' :param s :type s:rectangular_composite_surface ''' for i in range(1,s.n_u,1): for j in range(1,s.n_v,1): if ( not (('CONFIG_CONTROL_DESIGN.B_SPLINE_SURFACE' == TYPEOF(s.segments[i][j].parent_surface)) or ('CONFIG_CONTROL_DESIGN.RECTANGULAR_TRIMMED_SURFACE' == TYPEOF(s.segments[i][j].parent_surface)))): return FALSE for i in range(1,s.n_u - 1,1): for j in range(1,s.n_v,1): if (s.segments[i][j].u_transition == discontinuous): return FALSE for i in range(1,s.n_u,1): for j in range(1,s.n_v - 1,1): if (s.segments[i][j].v_transition == discontinuous): return FALSE return TRUE #################### # FUNCTION closed_shell_reversed # #################### def closed_shell_reversed(a_shell,): ''' :param a_shell :type a_shell:closed_shell ''' if ('CONFIG_CONTROL_DESIGN.ORIENTED_CLOSED_SHELL' == TYPEOF(a_shell)): the_reverse = ((dummy_tri == connected_face_set(a_shell.connected_face_set.cfs_faces)) == closed_shell()) == oriented_closed_shell(a_shell.oriented_closed_shell.closed_shell_element, not a_shell.oriented_closed_shell.orientation) else: the_reverse = ((dummy_tri == connected_face_set(a_shell.connected_face_set.cfs_faces)) == closed_shell()) == oriented_closed_shell(a_shell,FALSE) return the_reverse #################### # FUNCTION boolean_choose # #################### def boolean_choose(b,choice1,choice2,): ''' :param b :type b:BOOLEAN :param choice1 :type choice1:(null) :param choice2 :type choice2:(null) ''' if (b): return choice1 else: return choice2 #################### # FUNCTION valid_time # #################### def valid_time(time,): ''' :param time :type time:local_time ''' if (EXISTS(time.second_component)): return EXISTS(time.minute_component) else: return TRUE #################### # FUNCTION valid_geometrically_bounded_wf_curve # #################### def valid_geometrically_bounded_wf_curve(crv,): ''' :param crv :type crv:curve ''' if (SIZEOF(['CONFIG_CONTROL_DESIGN.POLYLINE','CONFIG_CONTROL_DESIGN.B_SPLINE_CURVE','CONFIG_CONTROL_DESIGN.ELLIPSE','CONFIG_CONTROL_DESIGN.CIRCLE'] * TYPEOF(crv)) == 1): return TRUE else: if ('CONFIG_CONTROL_DESIGN.TRIMMED_CURVE' == TYPEOF(crv)): if (SIZEOF(['CONFIG_CONTROL_DESIGN.LINE','CONFIG_CONTROL_DESIGN.PARABOLA','CONFIG_CONTROL_DESIGN.HYPERBOLA'] * TYPEOF(crv.trimmed_curve.basis_curve)) == 1): return TRUE else: return valid_geometrically_bounded_wf_curve(crv.trimmed_curve.basis_curve) else: if ('CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D' == TYPEOF(crv)): return valid_geometrically_bounded_wf_curve(crv.offset_curve_3d.basis_curve) else: if ('CONFIG_CONTROL_DESIGN.CURVE_REPLICA' == TYPEOF(crv)): return valid_geometrically_bounded_wf_curve(crv.curve_replica.parent_curve) else: if ('CONFIG_CONTROL_DESIGN.COMPOSITE_CURVE' == TYPEOF(crv)): return SIZEOF(None) == 0 return FALSE #################### # FUNCTION dot_product # #################### def dot_product(arg1,arg2,): ''' :param arg1 :type arg1:direction :param arg2 :type arg2:direction ''' if (( not EXISTS(arg1)) or ( not EXISTS(arg2))): scalar = None else: if (arg1.dim != arg2.dim): scalar = None else: # begin/end block vec1 = normalise(arg1) vec2 = normalise(arg2) ndim = arg1.dim scalar = 0 for i in range(1,ndim,1): scalar = scalar + (vec1.direction_ratios[i] * vec2.direction_ratios[i]) return scalar #################### # FUNCTION acyclic_curve_replica # #################### def acyclic_curve_replica(rep,parent,): ''' :param rep :type rep:curve_replica :param parent :type parent:curve ''' if ( not ('CONFIG_CONTROL_DESIGN.CURVE_REPLICA' == TYPEOF(parent))): return TRUE if (parent == rep): return FALSE else: return acyclic_curve_replica(rep,parent.curve_replica.parent_curve) #################### # RULE change_request_requires_approval # #################### change_request_requires_approval = Rule() #################### # RULE restrict_date_time_role # #################### restrict_date_time_role = Rule() #################### # RULE versioned_action_request_requires_status # #################### versioned_action_request_requires_status = Rule() #################### # RULE acu_requires_security_classification # #################### acu_requires_security_classification = Rule() #################### # RULE no_shape_for_supplied_part # #################### no_shape_for_supplied_part = Rule() #################### # RULE dependent_instantiable_person_and_organization_role # #################### dependent_instantiable_person_and_organization_role = Rule() #################### # RULE product_definition_requires_date_time # #################### product_definition_requires_date_time = Rule() #################### # RULE compatible_dimension # #################### compatible_dimension = Rule() #################### # RULE product_version_requires_approval # #################### product_version_requires_approval = Rule() #################### # RULE change_requires_approval # #################### change_requires_approval = Rule() #################### # RULE product_requires_version # #################### product_requires_version = Rule() #################### # RULE product_definition_requires_person_organization # #################### product_definition_requires_person_organization = Rule() #################### # RULE product_concept_requires_configuration_item # #################### product_concept_requires_configuration_item = Rule() #################### # RULE certification_requires_date_time # #################### certification_requires_date_time = Rule() #################### # RULE certification_requires_approval # #################### certification_requires_approval = Rule() #################### # RULE subtype_mandatory_effectivity # #################### subtype_mandatory_effectivity = Rule() #################### # RULE versioned_action_request_requires_solution # #################### versioned_action_request_requires_solution = Rule() #################### # RULE effectivity_requires_approval # #################### effectivity_requires_approval = Rule() #################### # RULE unique_version_change_order_rule # #################### unique_version_change_order_rule = Rule() #################### # RULE dependent_instantiable_named_unit # #################### dependent_instantiable_named_unit = Rule() #################### # RULE subtype_mandatory_product_definition_formation # #################### subtype_mandatory_product_definition_formation = Rule() #################### # RULE approval_requires_approval_person_organization # #################### approval_requires_approval_person_organization = Rule() #################### # RULE approvals_are_assigned # #################### approvals_are_assigned = Rule() #################### # RULE start_work_requires_approval # #################### start_work_requires_approval = Rule() #################### # RULE approval_person_organization_constraints # #################### approval_person_organization_constraints = Rule() #################### # RULE configuration_item_requires_approval # #################### configuration_item_requires_approval = Rule() #################### # RULE contract_requires_person_organization # #################### contract_requires_person_organization = Rule() #################### # RULE dependent_instantiable_date_time_role # #################### dependent_instantiable_date_time_role = Rule() #################### # RULE restrict_product_category_value # #################### restrict_product_category_value = Rule() #################### # RULE start_work_requires_date_time # #################### start_work_requires_date_time = Rule() #################### # RULE product_requires_product_category # #################### product_requires_product_category = Rule() #################### # RULE dependent_instantiable_representation_item # #################### dependent_instantiable_representation_item = Rule() #################### # RULE change_request_requires_person_organization # #################### change_request_requires_person_organization = Rule() #################### # RULE product_definition_requires_approval # #################### product_definition_requires_approval = Rule() #################### # RULE subtype_mandatory_representation_context # #################### subtype_mandatory_representation_context = Rule() #################### # RULE security_classification_requires_date_time # #################### security_classification_requires_date_time = Rule() #################### # RULE security_classification_optional_date_time # #################### security_classification_optional_date_time = Rule() #################### # RULE as_required_quantity # #################### as_required_quantity = Rule() #################### # RULE start_request_requires_approval # #################### start_request_requires_approval = Rule() #################### # RULE geometric_representation_item_3d # #################### geometric_representation_item_3d = Rule() #################### # RULE application_context_requires_ap_definition # #################### application_context_requires_ap_definition = Rule() #################### # RULE subtype_mandatory_representation # #################### subtype_mandatory_representation = Rule() #################### # RULE change_requires_date_time # #################### change_requires_date_time = Rule() #################### # RULE dependent_instantiable_action_directive # #################### dependent_instantiable_action_directive = Rule() #################### # RULE restrict_security_classification_level # #################### restrict_security_classification_level = Rule() #################### # RULE approval_requires_approval_date_time # #################### approval_requires_approval_date_time = Rule() #################### # RULE subtype_mandatory_product_definition_usage # #################### subtype_mandatory_product_definition_usage = Rule() #################### # RULE restrict_approval_status # #################### restrict_approval_status = Rule() #################### # RULE change_request_requires_date_time # #################### change_request_requires_date_time = Rule() #################### # RULE dependent_instantiable_contract_type # #################### dependent_instantiable_contract_type = Rule() #################### # RULE contract_requires_approval # #################### contract_requires_approval = Rule() #################### # RULE restrict_document_type # #################### restrict_document_type = Rule() #################### # RULE dependent_instantiable_certification_type # #################### dependent_instantiable_certification_type = Rule() #################### # RULE design_context_for_property # #################### design_context_for_property = Rule() #################### # RULE product_version_requires_person_organization # #################### product_version_requires_person_organization = Rule() #################### # RULE dependent_instantiable_approval_status # #################### dependent_instantiable_approval_status = Rule() #################### # RULE subtype_mandatory_shape_representation # #################### subtype_mandatory_shape_representation = Rule() #################### # RULE dependent_instantiable_date # #################### dependent_instantiable_date = Rule() #################### # RULE configuration_item_requires_person_organization # #################### configuration_item_requires_person_organization = Rule() #################### # RULE dependent_instantiable_document_type # #################### dependent_instantiable_document_type = Rule() #################### # RULE restrict_contract_type # #################### restrict_contract_type = Rule() #################### # RULE subtype_mandatory_product_context # #################### subtype_mandatory_product_context = Rule() #################### # RULE dependent_instantiable_parametric_representation_context # #################### dependent_instantiable_parametric_representation_context = Rule() #################### # RULE security_classification_requires_person_organization # #################### security_classification_requires_person_organization = Rule() #################### # RULE dependent_instantiable_shape_representation # #################### dependent_instantiable_shape_representation = Rule() #################### # RULE restrict_action_request_status # #################### restrict_action_request_status = Rule() #################### # RULE restrict_certification_type # #################### restrict_certification_type = Rule() #################### # RULE subtype_mandatory_action # #################### subtype_mandatory_action = Rule() #################### # RULE product_requires_person_organization # #################### product_requires_person_organization = Rule() #################### # RULE product_version_requires_security_classification # #################### product_version_requires_security_classification = Rule() #################### # RULE document_to_product_definition # #################### document_to_product_definition = Rule() #################### # RULE start_request_requires_date_time # #################### start_request_requires_date_time = Rule() #################### # RULE dependent_instantiable_security_classification_level # #################### dependent_instantiable_security_classification_level = Rule() #################### # RULE global_unit_assignment # #################### global_unit_assignment = Rule() #################### # RULE restrict_person_organization_role # #################### restrict_person_organization_role = Rule() #################### # RULE coordinated_assembly_and_shape # #################### coordinated_assembly_and_shape = Rule() #################### # RULE start_request_requires_person_organization # #################### start_request_requires_person_organization = Rule() #################### # RULE no_shape_for_make_from # #################### no_shape_for_make_from = Rule() #################### # RULE approval_date_time_constraints # #################### approval_date_time_constraints = Rule() #################### # RULE security_classification_requires_approval # #################### security_classification_requires_approval = Rule()
lgpl-2.1
-7,461,532,435,308,213,000
28.23059
582
0.667368
false
jasonwbw/JustAPlaceholder
feature/ngram.py
1
3229
# -*- coding: utf-8 -*- """ __file__ ngram.py __description__ This file provides functions to compute n-gram & n-term. __author__ Chenglong Chen < [email protected] > __append__ Copy from project: Kaggle_CrowdFlower """ def getUnigram(words): """ Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of unigram """ assert type(words) == list return words def getBigram(words, join_string, skip=0): """ Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of bigram, e.g., ['I_am', 'am_Denny'] I use _ as join_string for this example. """ assert type(words) == list L = len(words) if L > 1: lst = [] for i in range(L-1): for k in range(1,skip+2): if i+k < L: lst.append( join_string.join([words[i], words[i+k]]) ) else: # set it as unigram lst = getUnigram(words) return lst def getTrigram(words, join_string, skip=0): """ Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of trigram, e.g., ['I_am_Denny'] I use _ as join_string for this example. """ assert type(words) == list L = len(words) if L > 2: lst = [] for i in range(L-2): for k1 in range(1,skip+2): for k2 in range(1,skip+2): if i+k1 < L and i+k1+k2 < L: lst.append( join_string.join([words[i], words[i+k1], words[i+k1+k2]]) ) else: # set it as bigram lst = getBigram(words, join_string, skip) return lst def getFourgram(words, join_string): """ Input: a list of words, e.g., ['I', 'am', 'Denny', 'boy'] Output: a list of trigram, e.g., ['I_am_Denny_boy'] I use _ as join_string for this example. """ assert type(words) == list L = len(words) if L > 3: lst = [] for i in xrange(L-3): lst.append( join_string.join([words[i], words[i+1], words[i+2], words[i+3]]) ) else: # set it as bigram lst = getTrigram(words, join_string) return lst def getBiterm(words, join_string): """ Input: a list of words, e.g., ['I', 'am', 'Denny', 'boy'] Output: a list of biterm, e.g., ['I_am', 'I_Denny', 'I_boy', 'am_Denny', 'am_boy', 'Denny_boy'] I use _ as join_string for this example. """ assert type(words) == list L = len(words) if L > 1: lst = [] for i in range(L-1): for j in range(i+1,L): lst.append( join_string.join([words[i], words[j]]) ) else: # set it as unigram lst = getUnigram(words) return lst def getTriterm(words, join_string): """ Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of triterm, e.g., ['I_am_Denny', 'I_Denny_am', 'am_I_Denny', 'am_Denny_I', 'Denny_I_am', 'Denny_am_I'] I use _ as join_string for this example. """ assert type(words) == list L = len(words) if L > 2: lst = [] for i in xrange(L-2): for j in xrange(i+1,L-1): for k in xrange(j+1,L): lst.append( join_string.join([words[i], words[j], words[k]]) ) else: # set it as biterm lst = getBiterm(words, join_string) return lst
apache-2.0
5,809,933,177,496,598,000
25.916667
103
0.534841
false
prarthitm/edxplatform
openedx/tests/xblock_integration/test_recommender.py
11
30576
""" This test file will run through some XBlock test scenarios regarding the recommender system """ from copy import deepcopy import json import itertools import StringIO import unittest from ddt import ddt, data from nose.plugins.attrib import attr from django.conf import settings from django.core.urlresolvers import reverse from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase from lms.djangoapps.courseware.tests.factories import GlobalStaffFactory from openedx.core.lib.url_utils import quote_slashes class TestRecommender(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Check that Recommender state is saved properly """ STUDENTS = [ {'email': '[email protected]', 'password': 'foo'}, {'email': '[email protected]', 'password': 'foo'} ] XBLOCK_NAMES = ['recommender', 'recommender_second'] @classmethod def setUpClass(cls): # Nose runs setUpClass methods even if a class decorator says to skip # the class: https://github.com/nose-devs/nose/issues/946 # So, skip the test class here if we are not in the LMS. if settings.ROOT_URLCONF != 'lms.urls': raise unittest.SkipTest('Test only valid in lms') super(TestRecommender, cls).setUpClass() cls.course = CourseFactory.create( display_name='Recommender_Test_Course' ) with cls.store.bulk_operations(cls.course.id, emit_signals=False): cls.chapter = ItemFactory.create( parent=cls.course, display_name='Overview' ) cls.section = ItemFactory.create( parent=cls.chapter, display_name='Welcome' ) cls.unit = ItemFactory.create( parent=cls.section, display_name='New Unit' ) cls.xblock = ItemFactory.create( parent=cls.unit, category='recommender', display_name='recommender' ) cls.xblock2 = ItemFactory.create( parent=cls.unit, category='recommender', display_name='recommender_second' ) cls.course_url = reverse( 'courseware_section', kwargs={ 'course_id': cls.course.id.to_deprecated_string(), 'chapter': 'Overview', 'section': 'Welcome', } ) cls.resource_urls = [ ( "https://courses.edx.org/courses/MITx/3.091X/" "2013_Fall/courseware/SP13_Week_4/" "SP13_Periodic_Trends_and_Bonding/" ), ( "https://courses.edx.org/courses/MITx/3.091X/" "2013_Fall/courseware/SP13_Week_4/SP13_Covalent_Bonding/" ) ] cls.test_recommendations = { cls.resource_urls[0]: { "title": "Covalent bonding and periodic trends", "url": cls.resource_urls[0], "description": ( "http://people.csail.mit.edu/swli/edx/" "recommendation/img/videopage1.png" ), "descriptionText": ( "short description for Covalent bonding " "and periodic trends" ) }, cls.resource_urls[1]: { "title": "Polar covalent bonds and electronegativity", "url": cls.resource_urls[1], "description": ( "http://people.csail.mit.edu/swli/edx/" "recommendation/img/videopage2.png" ), "descriptionText": ( "short description for Polar covalent " "bonds and electronegativity" ) } } def setUp(self): super(TestRecommender, self).setUp() for idx, student in enumerate(self.STUDENTS): username = "u{}".format(idx) self.create_account(username, student['email'], student['password']) self.activate_user(student['email']) self.logout() self.staff_user = GlobalStaffFactory() def get_handler_url(self, handler, xblock_name=None): """ Get url for the specified xblock handler """ if xblock_name is None: xblock_name = TestRecommender.XBLOCK_NAMES[0] return reverse('xblock_handler', kwargs={ 'course_id': self.course.id.to_deprecated_string(), 'usage_id': quote_slashes(self.course.id.make_usage_key('recommender', xblock_name).to_deprecated_string()), 'handler': handler, 'suffix': '' }) def enroll_student(self, email, password): """ Student login and enroll for the course """ self.login(email, password) self.enroll(self.course, verify=True) def enroll_staff(self, staff): """ Staff login and enroll for the course """ email = staff.email password = 'test' self.login(email, password) self.enroll(self.course, verify=True) def initialize_database_by_id(self, handler, resource_id, times, xblock_name=None): """ Call a ajax event (vote, delete, endorse) on a resource by its id several times """ if xblock_name is None: xblock_name = TestRecommender.XBLOCK_NAMES[0] url = self.get_handler_url(handler, xblock_name) for _ in range(times): self.client.post(url, json.dumps({'id': resource_id}), '') def call_event(self, handler, resource, xblock_name=None): """ Call a ajax event (add, edit, flag, etc.) by specifying the resource it takes """ if xblock_name is None: xblock_name = TestRecommender.XBLOCK_NAMES[0] url = self.get_handler_url(handler, xblock_name) return self.client.post(url, json.dumps(resource), '') def check_event_response_by_key(self, handler, resource, resp_key, resp_val, xblock_name=None): """ Call the event specified by the handler with the resource, and check whether the key (resp_key) in response is as expected (resp_val) """ if xblock_name is None: xblock_name = TestRecommender.XBLOCK_NAMES[0] resp = json.loads(self.call_event(handler, resource, xblock_name).content) self.assertEqual(resp[resp_key], resp_val) self.assert_request_status_code(200, self.course_url) def check_event_response_by_http_status(self, handler, resource, http_status_code, xblock_name=None): """ Call the event specified by the handler with the resource, and check whether the http_status in response is as expected """ if xblock_name is None: xblock_name = TestRecommender.XBLOCK_NAMES[0] resp = self.call_event(handler, resource, xblock_name) self.assertEqual(resp.status_code, http_status_code) self.assert_request_status_code(200, self.course_url) @attr(shard=1) class TestRecommenderCreateFromEmpty(TestRecommender): """ Check whether we can add resources to an empty database correctly """ def test_add_resource(self): """ Verify the addition of new resource is handled correctly """ self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password']) # Check whether adding new resource is successful for resource_id, resource in self.test_recommendations.iteritems(): for xblock_name in self.XBLOCK_NAMES: result = self.call_event('add_resource', resource, xblock_name) expected_result = { 'upvotes': 0, 'downvotes': 0, 'id': resource_id } for field in resource: expected_result[field] = resource[field] self.assertDictEqual(json.loads(result.content), expected_result) self.assert_request_status_code(200, self.course_url) @attr(shard=1) class TestRecommenderResourceBase(TestRecommender): """Base helper class for tests with resources.""" def setUp(self): super(TestRecommenderResourceBase, self).setUp() self.resource_id = self.resource_urls[0] self.resource_id_second = self.resource_urls[1] self.non_existing_resource_id = 'An non-existing id' self.set_up_resources() def set_up_resources(self): """ Set up resources and enroll staff """ self.logout() self.enroll_staff(self.staff_user) # Add resources, assume correct here, tested in test_add_resource for resource, xblock_name in itertools.product(self.test_recommendations.values(), self.XBLOCK_NAMES): self.call_event('add_resource', resource, xblock_name) def generate_edit_resource(self, resource_id): """ Based on the given resource (specified by resource_id), this function generate a new one for testing 'edit_resource' event """ resource = {"id": resource_id} edited_recommendations = { key: value + " edited" for key, value in self.test_recommendations[self.resource_id].iteritems() } resource.update(edited_recommendations) return resource @attr(shard=1) class TestRecommenderWithResources(TestRecommenderResourceBase): """ Check whether we can add/edit/flag/export resources correctly """ def test_add_redundant_resource(self): """ Verify the addition of a redundant resource (url) is rejected """ for suffix in ['', '#IAmSuffix', '%23IAmSuffix']: resource = deepcopy(self.test_recommendations[self.resource_id]) resource['url'] += suffix self.check_event_response_by_http_status('add_resource', resource, 409) def test_add_removed_resource(self): """ Verify the addition of a removed resource (url) is rejected """ self.call_event('remove_resource', {"id": self.resource_id, 'reason': ''}) for suffix in ['', '#IAmSuffix', '%23IAmSuffix']: resource = deepcopy(self.test_recommendations[self.resource_id]) resource['url'] += suffix self.check_event_response_by_http_status('add_resource', resource, 405) def test_edit_resource_non_existing(self): """ Edit a non-existing resource """ self.check_event_response_by_http_status( 'edit_resource', self.generate_edit_resource(self.non_existing_resource_id), 400 ) def test_edit_redundant_resource(self): """ Check whether changing the url to the one of 'another' resource is rejected """ for suffix in ['', '#IAmSuffix', '%23IAmSuffix']: resource = self.generate_edit_resource(self.resource_id) resource['url'] = self.resource_id_second + suffix self.check_event_response_by_http_status('edit_resource', resource, 409) def test_edit_removed_resource(self): """ Check whether changing the url to the one of a removed resource is rejected """ self.call_event('remove_resource', {"id": self.resource_id_second, 'reason': ''}) for suffix in ['', '#IAmSuffix', '%23IAmSuffix']: resource = self.generate_edit_resource(self.resource_id) resource['url'] = self.resource_id_second + suffix self.check_event_response_by_http_status('edit_resource', resource, 405) def test_edit_resource(self): """ Check whether changing the content of resource is successful """ self.check_event_response_by_http_status( 'edit_resource', self.generate_edit_resource(self.resource_id), 200 ) def test_edit_resource_same_url(self): """ Check whether changing the content (except for url) of resource is successful """ resource = self.generate_edit_resource(self.resource_id) for suffix in ['', '#IAmSuffix', '%23IAmSuffix']: resource['url'] = self.resource_id + suffix self.check_event_response_by_http_status('edit_resource', resource, 200) def test_edit_then_add_resource(self): """ Check whether we can add back an edited resource """ self.call_event('edit_resource', self.generate_edit_resource(self.resource_id)) # Test self.check_event_response_by_key( 'add_resource', self.test_recommendations[self.resource_id], 'id', self.resource_id ) def test_edit_resources_in_different_xblocks(self): """ Check whether changing the content of resource is successful in two different xblocks """ resource = self.generate_edit_resource(self.resource_id) for xblock_name in self.XBLOCK_NAMES: self.check_event_response_by_http_status('edit_resource', resource, 200, xblock_name) def test_flag_resource_wo_reason(self): """ Flag a resource as problematic, without providing the reason """ resource = {'id': self.resource_id, 'isProblematic': True, 'reason': ''} # Test self.check_event_response_by_key('flag_resource', resource, 'reason', '') def test_flag_resource_w_reason(self): """ Flag a resource as problematic, with providing the reason """ resource = {'id': self.resource_id, 'isProblematic': True, 'reason': 'reason 0'} # Test self.check_event_response_by_key('flag_resource', resource, 'reason', 'reason 0') def test_flag_resource_change_reason(self): """ Flag a resource as problematic twice, with different reasons """ resource = {'id': self.resource_id, 'isProblematic': True, 'reason': 'reason 0'} self.call_event('flag_resource', resource) # Test resource['reason'] = 'reason 1' resp = json.loads(self.call_event('flag_resource', resource).content) self.assertEqual(resp['oldReason'], 'reason 0') self.assertEqual(resp['reason'], 'reason 1') self.assert_request_status_code(200, self.course_url) def test_flag_resources_in_different_xblocks(self): """ Flag resources as problematic in two different xblocks """ resource = {'id': self.resource_id, 'isProblematic': True, 'reason': 'reason 0'} # Test for xblock_name in self.XBLOCK_NAMES: self.check_event_response_by_key('flag_resource', resource, 'reason', 'reason 0', xblock_name) def test_flag_resources_by_different_users(self): """ Different users can't see the flag result of each other """ resource = {'id': self.resource_id, 'isProblematic': True, 'reason': 'reason 0'} self.call_event('flag_resource', resource) self.logout() self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password']) # Test resp = json.loads(self.call_event('flag_resource', resource).content) # The second user won't see the reason provided by the first user self.assertNotIn('oldReason', resp) self.assertEqual(resp['reason'], 'reason 0') self.assert_request_status_code(200, self.course_url) def test_export_resources(self): """ Test the function for exporting all resources from the Recommender. """ self.call_event('remove_resource', {"id": self.resource_id, 'reason': ''}) self.call_event('endorse_resource', {"id": self.resource_id_second, 'reason': ''}) # Test resp = json.loads(self.call_event('export_resources', {}).content) self.assertIn(self.resource_id_second, resp['export']['recommendations']) self.assertNotIn(self.resource_id, resp['export']['recommendations']) self.assertIn(self.resource_id_second, resp['export']['endorsed_recommendation_ids']) self.assertIn(self.resource_id, resp['export']['removed_recommendations']) self.assert_request_status_code(200, self.course_url) @attr(shard=1) @ddt class TestRecommenderVoteWithResources(TestRecommenderResourceBase): """ Check whether we can vote resources correctly """ @data( {'event': 'recommender_upvote'}, {'event': 'recommender_downvote'} ) def test_vote_resource_non_existing(self, test_case): """ Vote a non-existing resource """ resource = {"id": self.non_existing_resource_id, 'event': test_case['event']} self.check_event_response_by_http_status('handle_vote', resource, 400) @data( {'event': 'recommender_upvote', 'new_votes': 1}, {'event': 'recommender_downvote', 'new_votes': -1} ) def test_vote_resource_once(self, test_case): """ Vote a resource """ resource = {"id": self.resource_id, 'event': test_case['event']} self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes']) @data( {'event': 'recommender_upvote', 'new_votes': 0}, {'event': 'recommender_downvote', 'new_votes': 0} ) def test_vote_resource_twice(self, test_case): """ Vote a resource twice """ resource = {"id": self.resource_id, 'event': test_case['event']} self.call_event('handle_vote', resource) # Test self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes']) @data( {'event': 'recommender_upvote', 'new_votes': 1}, {'event': 'recommender_downvote', 'new_votes': -1} ) def test_vote_resource_thrice(self, test_case): """ Vote a resource thrice """ resource = {"id": self.resource_id, 'event': test_case['event']} for _ in range(2): self.call_event('handle_vote', resource) # Test self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes']) @data( {'event': 'recommender_upvote', 'event_second': 'recommender_downvote', 'new_votes': -1}, {'event': 'recommender_downvote', 'event_second': 'recommender_upvote', 'new_votes': 1} ) def test_switch_vote_resource(self, test_case): """ Switch the vote of a resource """ resource = {"id": self.resource_id, 'event': test_case['event']} self.call_event('handle_vote', resource) # Test resource['event'] = test_case['event_second'] self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes']) @data( {'event': 'recommender_upvote', 'new_votes': 1}, {'event': 'recommender_downvote', 'new_votes': -1} ) def test_vote_different_resources(self, test_case): """ Vote two different resources """ resource = {"id": self.resource_id, 'event': test_case['event']} self.call_event('handle_vote', resource) # Test resource['id'] = self.resource_id_second self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes']) @data( {'event': 'recommender_upvote', 'new_votes': 1}, {'event': 'recommender_downvote', 'new_votes': -1} ) def test_vote_resources_in_different_xblocks(self, test_case): """ Vote two resources in two different xblocks """ resource = {"id": self.resource_id, 'event': test_case['event']} self.call_event('handle_vote', resource) # Test self.check_event_response_by_key( 'handle_vote', resource, 'newVotes', test_case['new_votes'], self.XBLOCK_NAMES[1] ) @data( {'event': 'recommender_upvote', 'new_votes': 2}, {'event': 'recommender_downvote', 'new_votes': -2} ) def test_vote_resource_by_different_users(self, test_case): """ Vote resource by two different users """ resource = {"id": self.resource_id, 'event': test_case['event']} self.call_event('handle_vote', resource) self.logout() self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password']) # Test self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes']) @attr(shard=1) @ddt class TestRecommenderStaffFeedbackWithResources(TestRecommenderResourceBase): """ Check whether we can remove/endorse resources correctly """ @data('remove_resource', 'endorse_resource') def test_remove_or_endorse_resource_non_existing(self, test_case): """ Remove/endorse a non-existing resource """ resource = {"id": self.non_existing_resource_id, 'reason': ''} self.check_event_response_by_http_status(test_case, resource, 400) @data( {'times': 1, 'key': 'status', 'val': 'endorsement'}, {'times': 2, 'key': 'status', 'val': 'undo endorsement'}, {'times': 3, 'key': 'status', 'val': 'endorsement'} ) def test_endorse_resource_multiple_times(self, test_case): """ Endorse a resource once/twice/thrice """ resource = {"id": self.resource_id, 'reason': ''} for _ in range(test_case['times'] - 1): self.call_event('endorse_resource', resource) # Test self.check_event_response_by_key('endorse_resource', resource, test_case['key'], test_case['val']) @data( {'times': 1, 'status': 200}, {'times': 2, 'status': 400}, {'times': 3, 'status': 400} ) def test_remove_resource_multiple_times(self, test_case): """ Remove a resource once/twice/thrice """ resource = {"id": self.resource_id, 'reason': ''} for _ in range(test_case['times'] - 1): self.call_event('remove_resource', resource) # Test self.check_event_response_by_http_status('remove_resource', resource, test_case['status']) @data( {'handler': 'remove_resource', 'status': 200}, {'handler': 'endorse_resource', 'key': 'status', 'val': 'endorsement'} ) def test_remove_or_endorse_different_resources(self, test_case): """ Remove/endorse two different resources """ self.call_event(test_case['handler'], {"id": self.resource_id, 'reason': ''}) # Test resource = {"id": self.resource_id_second, 'reason': ''} if test_case['handler'] == 'remove_resource': self.check_event_response_by_http_status(test_case['handler'], resource, test_case['status']) else: self.check_event_response_by_key(test_case['handler'], resource, test_case['key'], test_case['val']) @data( {'handler': 'remove_resource', 'status': 200}, {'handler': 'endorse_resource', 'key': 'status', 'val': 'endorsement'} ) def test_remove_or_endorse_resources_in_different_xblocks(self, test_case): """ Remove/endorse two resources in two different xblocks """ self.call_event(test_case['handler'], {"id": self.resource_id, 'reason': ''}) # Test resource = {"id": self.resource_id, 'reason': ''} if test_case['handler'] == 'remove_resource': self.check_event_response_by_http_status( test_case['handler'], resource, test_case['status'], self.XBLOCK_NAMES[1] ) else: self.check_event_response_by_key( test_case['handler'], resource, test_case['key'], test_case['val'], self.XBLOCK_NAMES[1] ) @data( {'handler': 'remove_resource', 'status': 400}, {'handler': 'endorse_resource', 'status': 400} ) def test_remove_or_endorse_resource_by_student(self, test_case): """ Remove/endorse resource by a student """ self.logout() self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password']) # Test resource = {"id": self.resource_id, 'reason': ''} self.check_event_response_by_http_status(test_case['handler'], resource, test_case['status']) @attr(shard=1) @ddt class TestRecommenderFileUploading(TestRecommender): """ Check whether we can handle file uploading correctly """ def setUp(self): super(TestRecommenderFileUploading, self).setUp() self.initial_configuration = { 'flagged_accum_resources': {}, 'endorsed_recommendation_reasons': [], 'endorsed_recommendation_ids': [], 'removed_recommendations': {}, 'recommendations': self.test_recommendations[self.resource_urls[0]] } def attempt_upload_file_and_verify_result(self, test_case, event_name, content=None): """ Running on a test case, creating a temp file, uploading it by calling the corresponding ajax event, and verifying that upload happens or is rejected as expected. """ if 'magic_number' in test_case: f_handler = StringIO.StringIO(test_case['magic_number'].decode('hex')) elif content is not None: f_handler = StringIO.StringIO(json.dumps(content, sort_keys=True)) else: f_handler = StringIO.StringIO('') f_handler.content_type = test_case['mimetypes'] f_handler.name = 'file' + test_case['suffixes'] url = self.get_handler_url(event_name) resp = self.client.post(url, {'file': f_handler}) self.assertEqual(resp.status_code, test_case['status']) self.assert_request_status_code(200, self.course_url) @data( { 'suffixes': '.csv', 'magic_number': 'ffff', 'mimetypes': 'text/plain', 'status': 415 }, # Upload file with wrong extension name { 'suffixes': '.gif', 'magic_number': '89504e470d0a1a0a', 'mimetypes': 'image/gif', 'status': 415 }, # Upload file with wrong magic number { 'suffixes': '.jpg', 'magic_number': '89504e470d0a1a0a', 'mimetypes': 'image/jpeg', 'status': 415 }, # Upload file with wrong magic number { 'suffixes': '.png', 'magic_number': '474946383761', 'mimetypes': 'image/png', 'status': 415 }, # Upload file with wrong magic number { 'suffixes': '.jpg', 'magic_number': '474946383761', 'mimetypes': 'image/jpeg', 'status': 415 }, # Upload file with wrong magic number { 'suffixes': '.png', 'magic_number': 'ffd8ffd9', 'mimetypes': 'image/png', 'status': 415 }, # Upload file with wrong magic number { 'suffixes': '.gif', 'magic_number': 'ffd8ffd9', 'mimetypes': 'image/gif', 'status': 415 } ) def test_upload_screenshot_wrong_file_type(self, test_case): """ Verify the file uploading fails correctly when file with wrong type (extension/magic number) is provided """ self.enroll_staff(self.staff_user) # Upload file with wrong extension name or magic number self.attempt_upload_file_and_verify_result(test_case, 'upload_screenshot') @data( { 'suffixes': '.png', 'magic_number': '89504e470d0a1a0a', 'mimetypes': 'image/png', 'status': 200 }, { 'suffixes': '.gif', 'magic_number': '474946383961', 'mimetypes': 'image/gif', 'status': 200 }, { 'suffixes': '.gif', 'magic_number': '474946383761', 'mimetypes': 'image/gif', 'status': 200 }, { 'suffixes': '.jpg', 'magic_number': 'ffd8ffd9', 'mimetypes': 'image/jpeg', 'status': 200 } ) def test_upload_screenshot_correct_file_type(self, test_case): """ Verify the file type checking in the file uploading method is successful. """ self.enroll_staff(self.staff_user) # Upload file with correct extension name and magic number self.attempt_upload_file_and_verify_result(test_case, 'upload_screenshot') @data( { 'suffixes': '.json', 'mimetypes': 'application/json', 'status': 403 } ) def test_import_resources_by_student(self, test_case): """ Test the function for importing all resources into the Recommender by a student. """ self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password']) self.attempt_upload_file_and_verify_result(test_case, 'import_resources', self.initial_configuration) @data( { 'suffixes': '.csv', 'mimetypes': 'application/json', 'status': 415 }, # Upload file with wrong extension name { 'suffixes': '.json', 'mimetypes': 'application/json', 'status': 200 } ) def test_import_resources(self, test_case): """ Test the function for importing all resources into the Recommender. """ self.enroll_staff(self.staff_user) self.attempt_upload_file_and_verify_result(test_case, 'import_resources', self.initial_configuration) @data( { 'suffixes': '.json', 'mimetypes': 'application/json', 'status': 415 } ) def test_import_resources_wrong_format(self, test_case): """ Test the function for importing empty dictionary into the Recommender. This should fire an error. """ self.enroll_staff(self.staff_user) self.attempt_upload_file_and_verify_result(test_case, 'import_resources', {})
agpl-3.0
5,832,969,663,170,268,000
36.982609
120
0.581927
false
aam-at/tensorflow
tensorflow/python/ops/distributions/normal.py
23
9823
# 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. # ============================================================================== """The Normal (Gaussian) distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.ops import random_ops from tensorflow.python.ops.distributions import distribution from tensorflow.python.ops.distributions import kullback_leibler from tensorflow.python.ops.distributions import special_math from tensorflow.python.util import deprecation from tensorflow.python.util.tf_export import tf_export __all__ = [ "Normal", "NormalWithSoftplusScale", ] @tf_export(v1=["distributions.Normal"]) class Normal(distribution.Distribution): """The Normal distribution with location `loc` and `scale` parameters. #### Mathematical details The probability density function (pdf) is, ```none pdf(x; mu, sigma) = exp(-0.5 (x - mu)**2 / sigma**2) / Z Z = (2 pi sigma**2)**0.5 ``` where `loc = mu` is the mean, `scale = sigma` is the std. deviation, and, `Z` is the normalization constant. The Normal distribution is a member of the [location-scale family]( https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be constructed as, ```none X ~ Normal(loc=0, scale=1) Y = loc + scale * X ``` #### Examples Examples of initialization of one or a batch of distributions. ```python import tensorflow_probability as tfp tfd = tfp.distributions # Define a single scalar Normal distribution. dist = tfd.Normal(loc=0., scale=3.) # Evaluate the cdf at 1, returning a scalar. dist.cdf(1.) # Define a batch of two scalar valued Normals. # The first has mean 1 and standard deviation 11, the second 2 and 22. dist = tfd.Normal(loc=[1, 2.], scale=[11, 22.]) # Evaluate the pdf of the first distribution on 0, and the second on 1.5, # returning a length two tensor. dist.prob([0, 1.5]) # Get 3 samples, returning a 3 x 2 tensor. dist.sample([3]) ``` Arguments are broadcast when possible. ```python # Define a batch of two scalar valued Normals. # Both have mean 1, but different standard deviations. dist = tfd.Normal(loc=1., scale=[11, 22.]) # Evaluate the pdf of both distributions on the same point, 3.0, # returning a length 2 tensor. dist.prob(3.0) ``` """ @deprecation.deprecated( "2019-01-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.distributions`.", warn_once=True) def __init__(self, loc, scale, validate_args=False, allow_nan_stats=True, name="Normal"): """Construct Normal distributions with mean and stddev `loc` and `scale`. The parameters `loc` and `scale` must be shaped in a way that supports broadcasting (e.g. `loc + scale` is a valid operation). Args: loc: Floating point tensor; the means of the distribution(s). scale: Floating point tensor; the stddevs of the distribution(s). Must contain only positive values. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Raises: TypeError: if `loc` and `scale` have different `dtype`. """ parameters = dict(locals()) with ops.name_scope(name, values=[loc, scale]) as name: with ops.control_dependencies([check_ops.assert_positive(scale)] if validate_args else []): self._loc = array_ops.identity(loc, name="loc") self._scale = array_ops.identity(scale, name="scale") check_ops.assert_same_float_dtype([self._loc, self._scale]) super(Normal, self).__init__( dtype=self._scale.dtype, reparameterization_type=distribution.FULLY_REPARAMETERIZED, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, graph_parents=[self._loc, self._scale], name=name) @staticmethod def _param_shapes(sample_shape): return dict( zip(("loc", "scale"), ([ops.convert_to_tensor( sample_shape, dtype=dtypes.int32)] * 2))) @property def loc(self): """Distribution parameter for the mean.""" return self._loc @property def scale(self): """Distribution parameter for standard deviation.""" return self._scale def _batch_shape_tensor(self): return array_ops.broadcast_dynamic_shape( array_ops.shape(self.loc), array_ops.shape(self.scale)) def _batch_shape(self): return array_ops.broadcast_static_shape( self.loc.get_shape(), self.scale.get_shape()) def _event_shape_tensor(self): return constant_op.constant([], dtype=dtypes.int32) def _event_shape(self): return tensor_shape.TensorShape([]) def _sample_n(self, n, seed=None): shape = array_ops.concat([[n], self.batch_shape_tensor()], 0) sampled = random_ops.random_normal( shape=shape, mean=0., stddev=1., dtype=self.loc.dtype, seed=seed) return sampled * self.scale + self.loc def _log_prob(self, x): return self._log_unnormalized_prob(x) - self._log_normalization() def _log_cdf(self, x): return special_math.log_ndtr(self._z(x)) def _cdf(self, x): return special_math.ndtr(self._z(x)) def _log_survival_function(self, x): return special_math.log_ndtr(-self._z(x)) def _survival_function(self, x): return special_math.ndtr(-self._z(x)) def _log_unnormalized_prob(self, x): return -0.5 * math_ops.square(self._z(x)) def _log_normalization(self): return 0.5 * math.log(2. * math.pi) + math_ops.log(self.scale) def _entropy(self): # Use broadcasting rules to calculate the full broadcast scale. scale = self.scale * array_ops.ones_like(self.loc) return 0.5 * math.log(2. * math.pi * math.e) + math_ops.log(scale) def _mean(self): return self.loc * array_ops.ones_like(self.scale) def _quantile(self, p): return self._inv_z(special_math.ndtri(p)) def _stddev(self): return self.scale * array_ops.ones_like(self.loc) def _mode(self): return self._mean() def _z(self, x): """Standardize input `x` to a unit normal.""" with ops.name_scope("standardize", values=[x]): return (x - self.loc) / self.scale def _inv_z(self, z): """Reconstruct input `x` from a its normalized version.""" with ops.name_scope("reconstruct", values=[z]): return z * self.scale + self.loc class NormalWithSoftplusScale(Normal): """Normal with softplus applied to `scale`.""" @deprecation.deprecated( "2019-01-01", "Use `tfd.Normal(loc, tf.nn.softplus(scale)) " "instead.", warn_once=True) def __init__(self, loc, scale, validate_args=False, allow_nan_stats=True, name="NormalWithSoftplusScale"): parameters = dict(locals()) with ops.name_scope(name, values=[scale]) as name: super(NormalWithSoftplusScale, self).__init__( loc=loc, scale=nn.softplus(scale, name="softplus_scale"), validate_args=validate_args, allow_nan_stats=allow_nan_stats, name=name) self._parameters = parameters @kullback_leibler.RegisterKL(Normal, Normal) def _kl_normal_normal(n_a, n_b, name=None): """Calculate the batched KL divergence KL(n_a || n_b) with n_a and n_b Normal. Args: n_a: instance of a Normal distribution object. n_b: instance of a Normal distribution object. name: (optional) Name to use for created operations. default is "kl_normal_normal". Returns: Batchwise KL(n_a || n_b) """ with ops.name_scope(name, "kl_normal_normal", [n_a.loc, n_b.loc]): one = constant_op.constant(1, dtype=n_a.dtype) two = constant_op.constant(2, dtype=n_a.dtype) half = constant_op.constant(0.5, dtype=n_a.dtype) s_a_squared = math_ops.square(n_a.scale) s_b_squared = math_ops.square(n_b.scale) ratio = s_a_squared / s_b_squared return (math_ops.squared_difference(n_a.loc, n_b.loc) / (two * s_b_squared) + half * (ratio - one - math_ops.log(ratio)))
apache-2.0
-7,849,228,935,168,344,000
32.298305
80
0.657742
false
AlexCatarino/Lean
Algorithm.Python/BrokerageModelAlgorithm.py
3
3724
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from AlgorithmImports import * ### <summary> ### Demonstrate the usage of the BrokerageModel property to help improve backtesting ### accuracy through simulation of a specific brokerage's rules around restrictions ### on submitting orders as well as fee structure. ### </summary> ### <meta name="tag" content="trading and orders" /> ### <meta name="tag" content="brokerage models" /> class BrokerageModelAlgorithm(QCAlgorithm): def Initialize(self): self.SetCash(100000) # Set Strategy Cash self.SetStartDate(2013,10,7) # Set Start Date self.SetEndDate(2013,10,11) # Set End Date self.AddEquity("SPY", Resolution.Second) # there's two ways to set your brokerage model. The easiest would be to call # SetBrokerageModel( BrokerageName ); // BrokerageName is an enum # SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage); # SetBrokerageModel(BrokerageName.Default); # the other way is to call SetBrokerageModel( IBrokerageModel ) with your # own custom model. I've defined a simple extension to the default brokerage # model to take into account a requirement to maintain 500 cash in the account at all times self.SetBrokerageModel(MinimumAccountBalanceBrokerageModel(self,500.00)) self.last = 1 def OnData(self, slice): # Simple buy and hold template if not self.Portfolio.Invested: self.SetHoldings("SPY", self.last) if self.Portfolio["SPY"].Quantity == 0: # each time we fail to purchase we'll decrease our set holdings percentage self.Debug(str(self.Time) + " - Failed to purchase stock") self.last *= 0.95 else: self.Debug("{} - Purchased Stock @ SetHoldings( {} )".format(self.Time, self.last)) class MinimumAccountBalanceBrokerageModel(DefaultBrokerageModel): '''Custom brokerage model that requires clients to maintain a minimum cash balance''' def __init__(self, algorithm, minimumAccountBalance): self.algorithm = algorithm self.minimumAccountBalance = minimumAccountBalance def CanSubmitOrder(self,security, order, message): '''Prevent orders which would bring the account below a minimum cash balance''' message = None # we want to model brokerage requirement of minimumAccountBalance cash value in account orderCost = order.GetValue(security) cash = self.algorithm.Portfolio.Cash cashAfterOrder = cash - orderCost if cashAfterOrder < self.minimumAccountBalance: # return a message describing why we're not allowing this order message = BrokerageMessageEvent(BrokerageMessageType.Warning, "InsufficientRemainingCapital", "Account must maintain a minimum of ${0} USD at all times. Order ID: {1}".format(self.minimumAccountBalance, order.Id)) self.algorithm.Error(str(message)) return False return True
apache-2.0
8,779,866,055,156,949,000
50.722222
225
0.698174
false
apache/bloodhound
bloodhound_multiproduct/multiproduct/ticket/query.py
2
16071
# -*- coding: UTF-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import with_statement import re from itertools import groupby from math import ceil from datetime import datetime, timedelta from genshi.builder import tag from trac.core import TracError from trac.db import get_column_names from trac.mimeview.api import Mimeview from trac.ticket.api import TicketSystem from trac.ticket.query import Query, QueryModule, TicketQueryMacro, QueryValueError from trac.util.datefmt import from_utimestamp, utc, to_timestamp from trac.util.text import shorten_line from trac.web import parse_arg_list, arg_list_to_args from trac.web.chrome import Chrome, add_stylesheet, add_link, web_context, \ add_script_data, add_script, add_ctxtnav, add_warning from trac.resource import Resource from multiproduct.dbcursor import GLOBAL_PRODUCT from multiproduct.env import lookup_product_env, resolve_product_href, \ ProductEnvironment from multiproduct.util.translation import _, tag_ class ProductQuery(Query): """Product Overrides for TracQuery. This class allows for writing TracQuery expressions matching resources beyond product boundaries. """ def _count(self, sql, args): if isinstance(self.env, ProductEnvironment): return super(ProductQuery, self)._count(sql, args) cnt = self.env.db_direct_query("SELECT COUNT(*) FROM (%s) AS x" % sql, args)[0][0] # "AS x" is needed for MySQL ("Subqueries in the FROM Clause") self.env.log.debug("Count results in Query: %d", cnt) return cnt def get_columns(self): super(ProductQuery, self).get_columns() if not 'product' in self.cols and self.group != 'product': # make sure 'product' is always present # (needed for product context, href, permission checks ...) # but don't implicitly include it if items are grouped by product self.cols.insert(0, 'product') return self.cols def _get_ticket_href(self, prefix, tid): try: env = lookup_product_env(self.env, prefix) except LookupError: return '#invalid-product-' + prefix else: href = resolve_product_href(env, self.env) return href.ticket(tid) def get_href(self, href, id=None, order=None, desc=None, format=None, max=None, page=None): from multiproduct.hooks import ProductizedHref return super(ProductQuery, self).get_href( ProductizedHref(href, self.env.href.base), id, order, desc, format, max, page) def execute(self, req=None, db=None, cached_ids=None, authname=None, tzinfo=None, href=None, locale=None): """Retrieve the list of matching tickets. :since 1.0: the `db` parameter is no longer needed and will be removed in version 1.1.1 """ with self.env.db_direct_query as db: cursor = db.cursor() self.num_items = 0 sql, args = self.get_sql(req, cached_ids, authname, tzinfo, locale) if sql.startswith('SELECT ') and not sql.startswith('SELECT DISTINCT '): sql = 'SELECT DISTINCT * FROM (' + sql + ') AS subquery' if isinstance(self.env, ProductEnvironment): sql = sql + """ WHERE product='%s'""" % (self.env.product.prefix, ) self.num_items = self._count(sql, args) if self.num_items <= self.max: self.has_more_pages = False if self.has_more_pages: max = self.max if self.group: max += 1 sql = sql + " LIMIT %d OFFSET %d" % (max, self.offset) if self.page > int(ceil(float(self.num_items) / self.max)) and \ self.num_items != 0: raise TracError(_("Page %(page)s is beyond the number of " "pages in the query", page=self.page)) # self.env.log.debug("SQL: " + sql % tuple([repr(a) for a in args])) cursor.execute(sql, args) columns = get_column_names(cursor) fields = [] for column in columns: fields += [f for f in self.fields if f['name'] == column] or \ [None] results = [] product_idx = columns.index('product') column_indices = range(len(columns)) for row in cursor: result = {} for i in column_indices: name, field, val = columns[i], fields[i], row[i] if name == 'reporter': val = val or 'anonymous' elif name == 'id': val = int(val) result['href'] = self._get_ticket_href( row[product_idx], val) elif name in self.time_fields: val = from_utimestamp(val) elif field and field['type'] == 'checkbox': try: val = bool(int(val)) except (TypeError, ValueError): val = False elif val is None: val = '' result[name] = val results.append(result) cursor.close() return results import trac.ticket.query trac.ticket.query.Query = ProductQuery trac.ticket.Query = ProductQuery class ProductQueryModule(QueryModule): def process_request(self, req, env=None): tmpenv = self.env if isinstance(self.env, ProductEnvironment) and env is not None: self.env = env result = super(ProductQueryModule, self).process_request(req) self.env = tmpenv return result trac.ticket.query.QueryModule = ProductQueryModule trac.ticket.QueryModule = ProductQueryModule class ProductTicketQueryMacro(TicketQueryMacro): """TracQuery macro retrieving results across product boundaries. """ @staticmethod def parse_args(content): """Parse macro arguments and translate them to a query string.""" clauses = [{}] argv = [] kwargs = {} for arg in TicketQueryMacro._comma_splitter.split(content): arg = arg.replace(r'\,', ',') m = re.match(r'\s*[^=]+=', arg) if m: kw = arg[:m.end() - 1].strip() value = arg[m.end():] if kw in ('order', 'max', 'format', 'col', 'product'): kwargs[kw] = value else: clauses[-1][kw] = value elif arg.strip() == 'or': clauses.append({}) else: argv.append(arg) clauses = filter(None, clauses) if len(argv) > 0 and not 'format' in kwargs: # 0.10 compatibility hack kwargs['format'] = argv[0] if 'order' not in kwargs: kwargs['order'] = 'id' if 'max' not in kwargs: kwargs['max'] = '0' # unlimited by default format = kwargs.pop('format', 'list').strip().lower() if format in ('list', 'compact'): # we need 'status' and 'summary' if 'col' in kwargs: kwargs['col'] = 'status|summary|' + kwargs['col'] else: kwargs['col'] = 'status|summary' query_string = '&or&'.join('&'.join('%s=%s' % item for item in clause.iteritems()) for clause in clauses) return query_string, kwargs, format def expand_macro(self, formatter, name, content): req = formatter.req query_string, kwargs, format = self.parse_args(content) if query_string: query_string += '&' query_string += '&'.join('%s=%s' % item for item in kwargs.iteritems()) env = ProductEnvironment.lookup_global_env(self.env) query = ProductQuery.from_string(env, query_string) if format == 'count': cnt = query.count(req) return tag.span(cnt, title='%d tickets for which %s' % (cnt, query_string), class_='query_count') tickets = query.execute(req) if format == 'table': data = query.template_data(formatter.context, tickets, req=formatter.context.req) add_stylesheet(req, 'common/css/report.css') return Chrome(env).render_template( req, 'query_results.html', data, None, fragment=True) if format == 'progress': from trac.ticket.roadmap import (RoadmapModule, apply_ticket_permissions, get_ticket_stats, grouped_stats_data) add_stylesheet(req, 'common/css/roadmap.css') def query_href(extra_args, group_value=None): q = ProductQuery.from_string(env, query_string) if q.group: extra_args[q.group] = group_value q.group = None for constraint in q.constraints: constraint.update(extra_args) if not q.constraints: q.constraints.append(extra_args) return q.get_href(formatter.context) chrome = Chrome(env) tickets = apply_ticket_permissions(env, req, tickets) stats_provider = RoadmapModule(env).stats_provider by = query.group if not by: stat = get_ticket_stats(stats_provider, tickets) data = { 'stats': stat, 'stats_href': query_href(stat.qry_args), 'interval_hrefs': [query_href(interval['qry_args']) for interval in stat.intervals], 'legend': True, } return tag.div( chrome.render_template(req, 'progress_bar.html', data, None, fragment=True), class_='trac-progress') def per_group_stats_data(gstat, group_name): return { 'stats': gstat, 'stats_href': query_href(gstat.qry_args, group_name), 'interval_hrefs': [query_href(interval['qry_args'], group_name) for interval in gstat.intervals], 'percent': '%d / %d' % (gstat.done_count, gstat.count), 'legend': False, } groups = grouped_stats_data(env, stats_provider, tickets, by, per_group_stats_data) data = { 'groups': groups, 'grouped_by': by, 'summary': _("Ticket completion status for each %(group)s", group=by), } return tag.div( chrome.render_template(req, 'progress_bar_grouped.html', data, None, fragment=True), class_='trac-groupprogress') # Formats above had their own permission checks, here we need to # do it explicitly: tickets = [t for t in tickets if 'TICKET_VIEW' in req.perm('ticket', t['id'])] if not tickets: return tag.span(_("No results"), class_='query_no_results') # Cache resolved href targets hrefcache = {} def ticket_anchor(ticket): try: pvalue = ticket.get('product') or GLOBAL_PRODUCT envhref = hrefcache[pvalue] except KeyError: try: env = lookup_product_env(self.env, prefix=pvalue, name=pvalue) except LookupError: return tag.a('#%s' % ticket['id'], class_='missing product') hrefcache[pvalue] = envhref = \ resolve_product_href(to_env=env, at_env=self.env) return tag.a('#%s' % ticket['id'], class_=ticket['status'], href=envhref.ticket(int(ticket['id'])), title=shorten_line(ticket['summary'])) def ticket_groups(): groups = [] for v, g in groupby(tickets, lambda t: t[query.group]): q = ProductQuery.from_string(env, query_string) # produce the hint for the group q.group = q.groupdesc = None order = q.order q.order = None title = _("%(groupvalue)s %(groupname)s tickets matching " "%(query)s", groupvalue=v, groupname=query.group, query=q.to_string()) # produce the href for the query corresponding to the group for constraint in q.constraints: constraint[str(query.group)] = v q.order = order href = q.get_href(formatter.context) groups.append((v, [t for t in g], href, title)) return groups if format == 'compact': if query.group: groups = [(v, ' ', tag.a('#%s' % u',\u200b'.join(str(t['id']) for t in g), href=href, class_='query', title=title)) for v, g, href, title in ticket_groups()] return tag(groups[0], [(', ', g) for g in groups[1:]]) else: alist = [ticket_anchor(ticket) for ticket in tickets] return tag.span(alist[0], *[(', ', a) for a in alist[1:]]) else: if query.group: return tag.div( [(tag.p(tag_('%(groupvalue)s %(groupname)s tickets:', groupvalue=tag.a(v, href=href, class_='query', title=title), groupname=query.group)), tag.dl([(tag.dt(ticket_anchor(t)), tag.dd(t['summary'])) for t in g], class_='wiki compact')) for v, g, href, title in ticket_groups()]) else: return tag.div(tag.dl([(tag.dt(ticket_anchor(ticket)), tag.dd(ticket['summary'])) for ticket in tickets], class_='wiki compact')) def is_inline(self, content): query_string, kwargs, format = self.parse_args(content) return format in ('count', 'compact')
apache-2.0
3,705,360,368,367,781,400
40.851563
84
0.510111
false
samwisehawkins/wrftools
util/generate_job_scripts.py
1
2032
""" Generate inital job scripts from a configuration file Config comes from a file, specified as --config argument. Some configuration options (listed below) can also be given at the command line, where they will override the configuration file. Usage: generate_job_scripts.py [--config=<file>] [options] Options: --config=<file> yaml/json file specifying configuration options --template-dir=<dir> directory containing job template --target-dir=<dir> directory to write scripts into --log.level=<level> log level info, debug or warn (see python logging modules) --log.format=<fmt> log format code (see python logging module) --log.file=<file> optional log file --help display documentation The above options can all be given at the command line. Jobs must be specified inside a configuration file. See config/templater.yaml for an example""" LOGGER="wrftools" import os import sys import loghelper as loghelper import confighelper as conf from wrftools import templater as tm def main(): # merge command-line and file-specified arguments config = conf.config(__doc__, sys.argv[1:]) logger = loghelper.create(LOGGER, log_level=config.get('log.level'), log_fmt=config.get('log.format')) if config.get('log.file'): log_file = config['log.file'] logger.addHandler(loghelper.file_handler(log_file, config['log.level'], config['log.format'])) jobs = config['jobs'] for key in sorted(jobs.keys()): entry = jobs[key] template = entry['template'] target = entry['target'] logger.debug("filling template %s ----> %s" % (template, target)) path,name = os.path.split(target) if not os.path.exists(path): os.makedirs(path) replacements = entry['replacements'] tm.fill_template(template,target,replacements) if '__main__' in __name__: main()
mit
-7,365,955,544,928,536,000
34.321429
137
0.641732
false
arkem/pyflag
src/pyflag/DB.py
1
43125
#!/usr/bin/env python # ****************************************************** # Copyright 2004: Commonwealth of Australia. # # Developed by the Computer Network Vulnerability Team, # Information Security Group. # Department of Defence. # # Michael Cohen <[email protected]> # # ****************************************************** # Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$ # ****************************************************** # # * This program is free software; you can redistribute it and/or # * modify it under the terms of the GNU General Public License # * as published by the Free Software Foundation; either version 2 # * of the License, or (at your option) any later version. # * # * This program is distributed in the hope that it will be useful, # * but WITHOUT ANY WARRANTY; without even the implied warranty of # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # * GNU General Public License for more details. # * # * You should have received a copy of the GNU General Public License # * along with this program; if not, write to the Free Software # * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ****************************************************** """ This module contains db related functions """ import MySQLdb,re import MySQLdb.cursors import _mysql import pyflag.conf config = pyflag.conf.ConfObject() import pyflag.pyflaglog as pyflaglog import time,types from Queue import Queue, Full, Empty from MySQLdb.constants import FIELD_TYPE, FLAG import threading ## This store stores information about indexes import Store DBIndex_Cache=Store.Store() db_connections=0 mysql_connection_args = None ## Declare the configuration parameters we need here: config.add_option("FLAGDB", default='pyflag', help="Default pyflag database name") config.add_option("DBUSER", default='root', help="Username to connect to db with") config.add_option("DBPASSWD", default=None, help="Password to connect to the database") config.add_option("STRICTSQL", default=False, action='store_true', metavar = "true/false", help="database warnings are fatal") config.add_option("DBHOST", default='localhost', help="database host to connect to") config.add_option("DBPORT", default=3306, type='int', help="database port to connect to") config.add_option("DBUNIXSOCKET", default="/var/run/mysqld/mysqld.sock", help="path to mysql socket") config.add_option("DBCACHE_AGE", default=60, type='int', help="The length of time table searches remain cached") config.add_option("DBCACHE_LENGTH", default=1024, type='int', help="Number of rows to cache for table searches") config.add_option("MASS_INSERT_THRESHOLD", default=300, type='int', help="Number of rows where the mass insert buffer will be flushed.") config.add_option("TABLE_QUERY_TIMEOUT", default=10, type='int', help="The table widget will timeout queries after this many seconds") config.add_option("SQL_CACHE_MODE", default="realtime", help="The SQL Cache mode (can be realtime, periodic, all) see the wiki page for explaination") config.add_option("DB_SS_CURSOR", default=False, action='store_true', help = "Enable server side database cursors") import types import MySQLdb.converters conv = MySQLdb.converters.conversions.copy() ## Remove those conversions which we do not want: del conv[FIELD_TYPE.TIMESTAMP] del conv[FIELD_TYPE.DATETIME] del conv[FIELD_TYPE.DECIMAL] del conv[FIELD_TYPE.NEWDECIMAL] del conv[FIELD_TYPE.TIME] del conv[FIELD_TYPE.DATE] del conv[FIELD_TYPE.YEAR] def escape(result, quote='\''): result = result.replace("\\","\\\\") for q in quote: result = result.replace(q,'\\'+q) result = result.replace("\n","\\n") result = result.replace("\r","\\r") result = result.replace("\t","\\t") result = result.replace("\x00","\\0") return result def glob2re(glob): """ Convert a shell wildcard to a mysql compatible regex for use with rlike """ # special chars are *, ? which are replaced by ".*" and "." respectively (if not escaped) # inverse set syntax is also converted from [!abc] to [^abc] regex = glob regex = re.sub("(?<!\\\)\*", ".*", regex) regex = re.sub("(?<!\\\)\?", ".", regex) regex = re.sub("(?<!\\\)\[!", "[^", regex) return regex class DBError(Exception): """ Generic Database Exception """ pass def force_unicode(string): """ Make sure the string is unicode where its supposed to be """ if isinstance(string, str): try: return unicode(string) except: #print "String %r should be unicode" % string pass return unicode(string, "utf-8", "ignore") return unicode(string) def force_string(string): if isinstance(string, unicode): return string.encode("utf-8","ignore") return str(string) expand_re = re.compile("%(r|s|b)") def expand(format, params): """ This version of the expand function returns a unicode object after properly expanding the params into it. NOTE The Python % operator is evil - do not use it because it forces the decoding of its parameters into unicode when any of the args are unicode (it upcasts them). This is a very unsafe operation to automatically do because the default codec is ascii which will raise when a string contains a non ascii char. This is basically a time bomb which will blow when you least expect it. Never use %, use this function instead. This function will return a unicode object. """ format = unicode(format) d = dict(count = 0) if isinstance(params, basestring): params = (params,) try: params[0] except: params = (params,) def cb(m): x = params[d['count']] if m.group(1)=="s": result = u"%s" % (force_unicode(params[d['count']])) ## Raw escaping elif m.group(1)=='r': result = u"'%s'" % escape(force_unicode(params[d['count']]), quote="'") d['count'] +=1 return result result = expand_re.sub(cb,format) return result def db_expand(sql, params): """ A utility function for interpolating into the query string. This class implements the correct interpolation so that %s is not escaped and %r is escaped in the mysql interpolation. @Note: We cant use the MySQLdb native interpolation because it has a brain dead way of interpolating - it always escapes _ALL_ parameters and always adds quotes around anything. So for example: >>> MySQLdb.execute('select blah from %s where id=%r',table,id) Does not work as it should, since the table name is always enclosed in quotes which is incorrect. NOTE: expand always returns a string not a unicode object because we might need to mix different encodings - for example we might have some binary data and utf8 strings mixed together in the return string. If we returned a unicode string it will be encoded to utf8 when sending to the server and the binary data will be corrupted. """ sql = str(sql) d = dict(count = 0) if isinstance(params, basestring): params = (params,) try: params[0] except: params = (params,) def cb(m): x = params[d['count']] if m.group(1)=="s": #result = u"%s" % (force_unicode(params[d['count']])) result = force_string(x) ## Raw escaping elif m.group(1)=='r': result = force_string(x) result = "'%s'" % escape(result, quote="'") #result = u"'%s'" % escape(force_unicode(params[d['count']]), quote="'") #result = u"'%s'" % escape(force_unicode(params[d['count']])) ## This needs to be binary escaped: elif m.group(1)=='b': #data = params[d['count']].decode("latin1") data = params[d['count']] #data = ''.join(r"\\x%02X" % ord(x) for x in params[d['count']]) #data = params[d['count']] result = "_binary'%s'" % escape(data) #print result.encode("ascii","ignore") d['count'] +=1 return result result = expand_re.sub(cb,sql) return result class PyFlagDirectCursor(MySQLdb.cursors.DictCursor): ignore_warnings = False def execute(self, string): pyflaglog.log(pyflaglog.VERBOSE_DEBUG, string) return MySQLdb.cursors.DictCursor.execute(self, string) def _warning_check(self): last = self._last_executed if self._warnings and not self.ignore_warnings: self.execute("SHOW WARNINGS") while 1: a=self.fetchone() if not a: break pyflaglog.log(pyflaglog.WARNINGS,"query %r: %s" % (last[:100],a['Message'])) class PyFlagCursor(MySQLdb.cursors.SSDictCursor): """ This cursor combines client side and server side result storage. We store a limited cache of rows client side, and fetch rows from the server when needed. """ ignore_warnings = False logged = True def __init__(self, connection): MySQLdb.cursors.SSDictCursor.__init__(self, connection) self.py_row_cache = [] ## Maximum size of client cache self.py_cache_size = 10 self._last_executed = None self._last_executed_sequence = [] ## By default queries are allowed to take a long time self.timeout = 0 def kill_connection(self, what=''): dbh = DBO() try: dbh.execute("kill %s %s" % (what,self.connection.thread_id())) except: pass def execute(self,string): self.py_row_cache = [] self.py_cache_size = 10 self._last_executed = string self._last_executed_sequence.append(string) self._last_executed_sequence = self._last_executed_sequence[:-3] def cancel(): pyflaglog.log(pyflaglog.WARNINGS, "Killing query in thread %s because it took too long" % self.connection.thread_id()) self.kill_connection('query') if self.timeout: t = threading.Timer(self.timeout, cancel) t.start() try: pyflaglog.log(pyflaglog.VERBOSE_DEBUG, string) MySQLdb.cursors.SSDictCursor.execute(self,string) finally: t.cancel() t.join() pass else: if self.logged: pyflaglog.log(pyflaglog.VERBOSE_DEBUG, string) MySQLdb.cursors.SSDictCursor.execute(self,string) def fetchone(self): """ Updates the row cache if needed otherwise returns a single row from it. """ self._check_executed() if len(self.py_row_cache)==0: self.py_row_cache = list(self._fetch_row(self.py_cache_size)) try: result = self.py_row_cache.pop(0) self.rownumber = self.rownumber + 1 return result except IndexError: return None def close(self): self.connection = None def _warning_check(self): """ We need to override this because for some cases it issues a SHOW WARNINGS query. Which will raise an 'out of sync error' when we operate in SS. This is a most sane approach - when warnings are detected, we simply try to drain the resultsets and then read the warnings. """ if self.ignore_warnings: return ## We have warnings to show if self._warnings: last_executed = [ x[:500] for x in self._last_executed_sequence] results = list(self._fetch_row(1000)) if len(results)<1000: self.execute("SHOW WARNINGS") while 1: a=self.fetchone() if not a: break pyflaglog.log(pyflaglog.DEBUG,"Mysql warnings: query %r: %s" % (last_executed,a)) else: pyflaglog.log(pyflaglog.DEBUG,"Mysql issued warnings but we are unable to drain result queue") ## If we have strict SQL we abort on warnings: if config.STRICTSQL: raise DBError(a) self.py_row_cache.extend(results) def mysql_connect(case): """ Connect specified case and return a new connection handle """ global db_connections, mysql_connection_args ## If we already know the connection args we just go for it if mysql_connection_args: mysql_connection_args['db'] = case dbh=MySQLdb.Connection(**mysql_connection_args) dbh.autocommit(True) return dbh mysql_connection_args = dict(user = config.DBUSER, db = case, host=config.DBHOST, port=config.DBPORT, conv = conv, use_unicode = True, charset='utf8' ) if config.DBPASSWD: mysql_connection_args['passwd'] = config.DBPASSWD if config.STRICTSQL: mysql_connection_args['sql_mode'] = "STRICT_ALL_TABLES" if config.DB_SS_CURSOR: mysql_connection_args['cursorclass'] = PyFlagCursor else: mysql_connection_args['cursorclass'] = PyFlagDirectCursor mysql_connection_args['cursorclass']._last_executed_sequence = [] try: #Try to connect over TCP dbh = MySQLdb.Connect(**mysql_connection_args) except Exception,e: ## or maybe over the socket? mysql_connection_args['unix_socket'] = config.DBUNIXSOCKET del mysql_connection_args['host'] del mysql_connection_args['port'] dbh = MySQLdb.Connect(**mysql_connection_args) dbh.autocommit(True) return dbh class Pool(Queue): """ Pyflag needs to maintain multiple simulataneous connections to the database sometimes. To avoid having to reconnect on each occasion, we keep a pool of connection objects. This allows connections to be placed back in the pool after DBO destruction for reuse by other DBOs. Note that since we use the Queue class we are thread safe here. I.e. we guarantee that the same connection will never be shared by two different threads. Note that connections are not placed back on the queue until all references to them are GCed. This means that we still need to be relatively concervative in creating new DBOs and prefer to reuse existing ones whenever possible (of course we need to create new ones if the connection state is important (e.g. iterating through a resultset while doing some different db activity). The pool maintains a cache of case parameters, which we get from the meta table. If these change, The cache needs to be expired. """ def __init__(self, case, poolsize=0): self.case=case self.indexes = {} self._parameters = {} Queue.__init__(self, poolsize) def parameter(self, string): try: return self._parameters[string] except KeyError: dbh = self.get() c=dbh.cursor() c.execute("select value from meta where property = %r limit 1" % string) row = c.fetchone() try: return row['value'] except: return None def parameter_flush(self): """ Expire the parameter cache """ self._parameters = {} def put(self, dbh): pyflaglog.log(pyflaglog.VERBOSE_DEBUG, "Returning dbh to pool %s" % self.case) Queue.put(self,dbh) def get(self, block=1): """Get an object from the pool or a new one if empty.""" try: try: result=self.empty() and mysql_connect(self.case) or Queue.get(self, block) pyflaglog.log(pyflaglog.VERBOSE_DEBUG, "Getting dbh from pool %s" % self.case) except Empty: result = mysql_connect(self.case) return result except Exception,e: ## We just failed to connect - i bet the cached variables ## are totally wrong - invalidate the cache: global mysql_connection_args mysql_connection_args = None raise DBError("Unable to connect - does the DB Exist?: %s" % e) class PooledDBO: """ Class controlling access to DB handles We implement a pool of connection threads. This gives us both worlds - the advantage of reusing connection handles without running the risk of exhausting them, as well as the ability to issue multiple simultaneous queries from different threads. @cvar DBH: A store containing cached database connection objects @cvar lock: an array of unique locks that each thread must hold before executing new SQL @ivar temp_tables: A variable that keeps track of temporary tables so they may be dropped when this object gets gc'ed """ temp_tables = [] transaction = False ## This stores references to the pools DBH = Store.Store(max_size=10) def get_dbh(self, case): try: pool = self.DBH.get(case) except KeyError: pool = Pool(case) self.DBH.put(pool, key=case) self.dbh = pool.get() ## Ensure the tz is properly reset before handing out dbh: c = self.dbh.cursor() try: c.execute("select value from meta where property ='TZ' limit 1") row = c.fetchone() if row: c.execute(db_expand('set time_zone = %r', row['value'])) except Exception,e: pass def __init__(self,case=None): """ Constructor for DB access. Note that this object implements database connection caching and so should be instantiated whenever needed. If case is None, the handler returned is for the default flag DB @arg case: Case database to connect to. May be None in which case it connects to the default flag database """ if not case: case = config.FLAGDB self.get_dbh(case) self.temp_tables = [] self.case = case self.cursor = self.dbh.cursor() self.tranaction = False def start_transaction(self): self.execute("start transaction") self.tranaction = True def end_transaction(self): self.execute("commit") self.tranaction = False def clone(self): """ Returns a new database object for the same case database """ return self.__class__(self.case) def execute(self,query_str, *params): """ SQL execution method. This functions executes the SQL in this object's cursor context. the query must be given as a string with with %s or %r escape characters, and the correct number of strings in the params list. @note: Just as a reminder - using %r will escape the corresponding string in a manner that is adequate for mysql, it will also automatically insert quotes around the string. On the other hand using %s will not escape the strings. >>> a.execute('select * from %s where id=%r' , ('table','person')) @arg query_str: A format string with only %r and %s format sequences @arg params: A list of strings which will be formatted into query_str. If there is only one format string and the programmer is truely lazy, a string is ok. """ try: params[0].__iter__ params = params[0] except (AttributeError,IndexError): pass if params: string = db_expand(query_str, params) else: string = query_str try: self.cursor.execute(string) #If anything went wrong we raise it as a DBError except Exception,e: str = "%s" % e if 'cursor closed' in str or \ 'Commands out of sync' in str or \ 'server has gone away' in str or \ 'Lost connection' in str: pyflaglog.log(pyflaglog.VERBOSE_DEBUG, "Got DB Error: %s" % (str)) ## We terminate the current connection and reconnect ## to the DB pyflaglog.log(pyflaglog.DEBUG, "Killing connection because %s. Last query was %s" % (e,self.cursor._last_executed_sequence)) try: self.cursor.kill_connection() del self.dbh except AttributeError: pass global db_connections db_connections -=1 self.get_dbh(self.case) #self.dbh.ignore_warnings = self.cursor.ignore_warnings self.cursor = self.dbh.cursor() ## Redo the query with the new connection - if we fail ## again, we just raise - otherwise we risk running ## into recursion issues: return self.cursor.execute(string) elif not str.startswith('Records'): raise DBError(e) def expire_cache(self): """ Expires the cache if needed """ ## Expire the cache if needed self.start_transaction() try: self.execute("select * from sql_cache where timestamp < date_sub(now(), interval %r minute) for update", config.DBCACHE_AGE) ## Make a copy to maintain the cursor tables = [ row['id'] for row in self ] for table_id in tables: self.execute("delete from sql_cache where id = %r" , table_id) self.execute("delete from sql_cache_tables where sql_id = %r" , table_id) self.execute("drop table if exists `cache_%s`" , table_id) finally: self.end_transaction() def cached_execute(self, sql, limit=0, length=50): """ Executes the sql statement using the cache. strategy: Check the sql_cache table for the row, if it does not exist, make it if its in progress, spin for a while if its cached return it. """ if config.SQL_CACHE_MODE=="realtime": self.expire_cache() self.execute("""select * from sql_cache where query = %r and `limit` <= %r and `limit` + `length` >= %r order by id limit 1 for update""", (sql, limit, limit + length)) row = self.fetch() if not row: ## Row does not exist - make it return self._make_sql_cache_entry(sql, limit, length) elif row['status'] == 'dirty': if config.SQL_CACHE_MODE == "realtime": ## Row is dirty - make it self._make_sql_cache_entry(sql, limit, length) else: ## We dont care about dirty rows now return self.execute("select * from cache_%s limit %s,%s", (row['id'], limit - row['limit'], length)) elif row['status'] == 'cached': return self.execute("select * from cache_%s limit %s,%s", (row['id'], limit - row['limit'], length)) elif row['status'] == 'progress': ## Spin until its ready count = config.TABLE_QUERY_TIMEOUT while count > 0: self.execute("select * from sql_cache where id=%r and status!='progress' limit 1", row['id']) row2=self.fetch() if row2: return self.execute("select * from cache_%s limit %s,%s", (row['id'], limit - row['limit'], length)) time.sleep(1) count -= 1 pyflaglog.log(pyflaglog.DEBUG,"Waiting for query to complete for %u" % count) raise DBError("Query still executing - try again soon") def _make_sql_cache_entry(self, sql, limit, length): ## Query is not in cache - create a new cache entry: We create ## the cache centered on the required range - this allows ## quick paging forward and backwards. lower_limit = max(limit - config.DBCACHE_LENGTH/2,0) ## Determine which tables are involved: self.execute("explain %s", sql) tables = [ row['table'] for row in self if row['table'] ] if not tables: ## Should not happen - the query does not affect any tables?? return self.execute("%s limit %s,%s",sql, limit, length) self.insert('sql_cache', query = sql, _timestamp='now()', limit = lower_limit, length = config.DBCACHE_LENGTH, status = 'progress', _fast = True ) ## Create the new table id = self.autoincrement() ## Store the tables in the sql_cache_tables: for t in tables: self.insert('sql_cache_tables', sql_id = id, table_name = t, _fast = True) ## Now comes the tricky part def run_query(): dbh = DBO(self.case) dbh.discard = True try: dbh.execute("create table cache_%s %s limit %s,%s", (id,sql, lower_limit, config.DBCACHE_LENGTH)) for row in dbh: pass dbh.execute("update sql_cache set status='cached' where id=%r" , id) dbh.execute("commit") except Exception,e: ## Make sure we remove the progress status from the ## table dbh.execute("delete from sql_cache where id=%r", id) raise ## We start by launching a worker thread worker = threading.Thread(target=run_query) worker.start() ## Wait for the worker to finish worker.join(config.TABLE_QUERY_TIMEOUT) if worker.isAlive(): raise DBError("Query still executing - try again soon") for i in range(config.TABLE_QUERY_TIMEOUT): try: return self.execute("select * from cache_%s limit %s,%s", (id,limit - lower_limit,length)) except DBError,e: ## Sometimes it takes a while for the table to be ## available to the two threads. (Is this normal - ## this seems like a weird race?) if "doesn't exist" in e.__str__(): time.sleep(1) else: break raise e def __iter__(self): return self def invalidate(self,table): """ Invalidate all copies of the cache which relate to this table """ if config.SQL_CACHE_MODE=='realtime': self.execute("start transaction") try: try: self.execute("select sql_id from sql_cache_tables where `table_name`=%r for update", table) except Exception, e: pass ids = [row['sql_id'] for row in self] for id in ids: self.execute("delete from sql_cache where id=%r", id) self.execute("delete from sql_cache_tables where sql_id=%r", id) self.execute("drop table if exists cache_%s", id) finally: self.end_transaction() def _calculate_set(self, **fields): """ Calculates the required set clause from the fields provided """ tmp = [] sql = [] for k,v in fields.items(): if k.startswith("__"): sql.append('`%s`=%b') k=k[2:] elif k.startswith("_"): sql.append('`%s`=%s') k=k[1:] else: sql.append('`%s`=%r') tmp.extend([k,v]) return (','.join(sql), tmp) def update(self, table, where='1', _fast=False, **fields): sql , args = self._calculate_set(**fields) sql = "update %s set " + sql + " where %s " ## We are about to invalidate the table: if not _fast: self.invalidate(table) self.execute(sql, [table,] + args + [where,]) def drop(self, table): self.invalidate(table) self.execute("drop table if exists `%s`", table) def delete(self, table, where='0', _fast=False): sql = "delete from %s where %s" ## We are about to invalidate the table: if not _fast: self.invalidate(table) self.execute(sql, (table, where)) def insert(self, table, _fast=False, **fields): """ A helper function to make inserting a little more readable. This is especially good for lots of fields. Special case: Normally fields are automatically escaped using %r, but if the field starts with _, it will be inserted using %s and _ removed. Note that since the introduction of the cached_execute functionality it is mandatory to use the insert, mass_insert or update methods to ensure the cache is properly invalidated rather than use raw SQL. """ sql , args = self._calculate_set(**fields) sql = "insert into `%s` set " + sql ## We are about to invalidate the table: if not _fast: self.invalidate(table) self.execute(sql, [table,]+args) def mass_insert_start(self, table, _fast=False): self.mass_insert_cache = {} self.mass_insert_table = table self.mass_insert_row_count = 0 self.mass_insert_fast = _fast def mass_insert(self, args=None, **columns): """ Starts a mass insert operation. When done adding rows, call commit_mass_insert to finalise the insert. """ if args: columns = args for k,v in columns.items(): ## _field means to pass the field if k.startswith("__"): v=db_expand("%b", (v,)) k=k[2:] elif k.startswith('_'): k=k[1:] else: v=db_expand("%r", (v,)) try: self.mass_insert_cache[k][self.mass_insert_row_count]=v except: self.mass_insert_cache[k]={ self.mass_insert_row_count: v} self.mass_insert_row_count+=1 if self.mass_insert_row_count > config.MASS_INSERT_THRESHOLD: self.mass_insert_commit() self.mass_insert_start(self.mass_insert_table, _fast=self.mass_insert_fast) def mass_insert_commit(self): try: keys = self.mass_insert_cache.keys() except AttributeError: ## We called commit without start return if len(keys)==0: return args = [] values = [] for i in range(self.mass_insert_row_count): for k in keys: try: args.append(self.mass_insert_cache[k][i]) except KeyError: args.append('NULL') values.append(",".join(["%s"] * len(keys))) sql = "insert ignore into `%s` (%s) values (%s)" % (self.mass_insert_table, ','.join(["`%s`" % c for c in keys]), "),(".join(values)) if not self.mass_insert_fast: self.invalidate(self.mass_insert_table) self.execute(sql,*args) ## Ensure the cache is now empty: self.mass_insert_start(self.mass_insert_table, _fast=self.mass_insert_fast) def autoincrement(self): """ Returns the value of the last autoincremented key """ return self.cursor.connection.insert_id() def next(self): """ The db object supports an iterator so that callers can simply iterate over the result set. Each iteration returns a hash as obtained from fetch. """ result = self.fetch() if not result: raise StopIteration return result def fetch(self): """ Returns the next cursor row as a dictionary. It is encouraged to use this function over cursor.fetchone to ensure that if columns get reordered in the future code does not break. The result of this function is a dictionary with keys being the column names and values being the values """ return self.cursor.fetchone() def check_index(self, table, key, length=None): """ This checks the database to ensure that the said table has an index on said key. If an index is missing, we create it here, so we always ensure an index exists once we return. """ ## We implement a local cache to ensure that we dont hit the ## DB all the time: cache_key = "%s/%s" % (self.case,table) try: ## These should be the fields with the indexes on them: fields = DBIndex_Cache.get(cache_key) except KeyError: self.execute("show index from `%s`",table) fields = [ row['Key_name'] for row in self] DBIndex_Cache.put(fields, key=cache_key) ## Now fields is an array stored in the Store - we can append ## to it directly because we also hold a reference here and it ## will affect the next value gotten from the Store: if key not in fields: if length: sql="(`%s`(%s))" % (key,length) else: sql="(`%s`)" % (key) pyflaglog.log(pyflaglog.VERBOSE_DEBUG,"Oops... No index found in table %s on field %s - Generating index, this may take a while" %(table,key)) ## Index not found, we make it here: self.execute("Alter table `%s` add index%s",(table,sql)) ## Add to cache: fields.append(key) def get_meta(self, property, table='meta',**args): """ Returns the value for the given property in meta table selected database Only returns first value """ self.execute("select value from `%s` where property=%r limit 1", (table,property)) row = self.fetch() return row and row.get('value') def set_meta(self, property,value, table='meta',force_create=False, **args): """ Sets the value in meta table """ prevvalue = self.get_meta(property, table, **args) if (prevvalue != None) and (not force_create): self.execute("update `%s` set property=%r,value=%r where property=%r", (table, property,value, property)) else: self.execute("insert into `%s` set property=%r,value=%r", (table, property,value)) def MakeSQLSafe(self,string): """ Returns a version of string, which is SQL safe. String will be converted to a form which is suitable to be used as the name of a table for example. """ import re return re.sub('[^a-zA-Z0-9]','_',string) def get_temp(self): """ Gets a unique name for a table. This can be used to create temporary tables - since flag is multi-threaded, normal mysql temporary tables remain within the same thread. Use this function to get names for temporary tables which can be shared between all threads. Note that each DBO object maintains a list of temporary tables, and drops those when gc'd so users of this class do not need to clean temporary tables up. The result from this function is guaranteed to not exist - so a create temporary table (or even a create table) call should work. """ thread_name = threading.currentThread().getName() thread_name = thread_name.replace('-','_') count = 1 while 1: test_name = "%s_%s%s" % (thread_name, int(time.mktime(time.gmtime())),count) ## Check if the table already exists: self.execute('show table status like %r',test_name) rs = [ r for r in self ] if not rs: self.temp_tables.append(test_name) return test_name count+=1 ## This flag controls if we shall discard our dbh from the ## pool. Normally dbhs are returned to the pool upon destructions ## but this can cause problems e.g. when we fork - so we have this ## as a way to stop the dbh from returning to the pool discard = False def __del__(self): """ Destructor that gets called when this object is gced """ try: try: self.cursor.ignore_warnings = True for i in self.temp_tables: self.drop(i) except: pass if self.transaction: self.end_transaction() ## Ensure that our mass insert case is comitted in case ## users forgot to flush it: self.mass_insert_commit() self.cursor.ignore_warnings = False ##key = "%s/%s" % (self.case, threading.currentThread().getName()) key = "%s" % (self.case) if self.DBH and not self.discard: pool = self.DBH.get(key) pool.put(self.dbh) except (TypeError,AssertionError,AttributeError, KeyError),e: #print "dbh desctrucr: %s " % e pass except Exception,e: import pyflag.FlagFramework as FlagFramework print FlagFramework.get_bt_string(e) class DirectDBO(PooledDBO): """ A class which just makes a new connection for each handle """ dbh = None def get_dbh(self, case): try: self.dbh = mysql_connect(case) except Exception,e: ## We just failed to connect - i bet the cached variables ## are totally wrong - invalidate the cache: global mysql_connection_args mysql_connection_args = None raise DBError("Unable to connects - does the DB Exist?: %s" % e) def __xxxdel__(self): if self.transaction: self.end_transaction() try: for i in self.temp_tables: self.drop(i) except: pass self.mass_insert_commit() if self.dbh: self.dbh.close() config.add_option("DB_CONNECTION_TYPE", default="direct", help="Type of database connections (direct, pooled)") DBO = DirectDBO if config.DB_CONNECTION_TYPE == 'pooled': print "You have selected pooled" DBO = PooledDBO def escape_column_name(name): """ This is a handy utility to properly escape column names taking into account possible table names. """ names = name.split(".") return '.'.join(["`%s`" % x for x in names]) def check_column_in_table(case, table, column_name, sql): """ This function checks that the column_name is defined in table and adds it if not. This is mostly used for schema migrations for later versions of pyflag. """ dbh = DBO(case) try: dbh.execute("select `%s` from `%s` limit 1", column_name, table) row= dbh.fetch() except: dbh.execute("alter table `%s` add `%s` %s", table, column_name, sql) ## The following are utilitiy functions which can be used to manage ## schema changes def convert_to_unicode(case, table): """ This function checks to see if the table is utf8 and if not we make it that. This is used to upgrade old tables in the pyflag db which happen to not be unicode. New tables should be automatically utf8. """ try: dbh = DBO(case) dbh.execute("show create table %s", table) row = dbh.fetch() statement = row['Create Table'].splitlines() last_line = statement[-1] m = re.search("CHARSET=([^ ]+)",last_line) if m and m.group(1).lower() != "utf8": dbh.execute("alter table %s convert to charset 'utf8'", table) except: pass if __name__=="__main__": config.set_usage(usage = "PyFlag Database Cache manager." " (You must run this if you choose periodic caching).") config.add_option("period", default=60, type='int', help = "Number of minutes to wait between cache refreshes") config.parse_options() while 1: pdbh = DBO() pdbh.execute("select value from meta where property='flag_db'") for row in pdbh: try: case = row['value'] dbh = DBO(case) dbh2 = DBO(case) dbh.execute("select * from sql_cache") for row in dbh: pyflaglog.log(pyflaglog.DEBUG, expand("Refreshing cache for %s %s: %s", (case, row['timestamp'], row['query']))) dbh2.insert("sql_cache", query = row['query'], status = 'progress', limit = row['limit'], length = row['length'], _fast = True) new_id = dbh2.autoincrement() dbh2.execute("create table cache_%s %s limit %s,%s", (new_id, row['query'], row['limit'], row['length'])) dbh2.execute("update sql_cache set status='cached' where id=%r" , new_id) dbh2.delete("sql_cache", where = "id = %s" % row['id']) dbh2.execute("commit") ## Now prune any cache tables dbh.execute("show tables") for row in dbh: table = row.values()[0] m=re.match("cache_(\d+)", table) if m: dbh2.execute("select * from sql_cache where id=%r", m.group(1)) if not dbh2.fetch(): dbh2.execute("drop table %s" % table) pyflaglog.log(pyflaglog.DEBUG, "Dropping expired table %s" % table) except Exception,e: pyflaglog.log(pyflaglog.ERROR, "Error: %s" % e) pyflaglog.log(pyflaglog.DEBUG, "Waiting for %s minutes" % config.PERIOD) time.sleep(config.PERIOD * 60)
gpl-2.0
-8,212,436,472,952,405,000
37.029101
250
0.565751
false
mitchellzen/pops
satchmo/apps/satchmo_store/shop/templatetags/satchmo_category.py
8
10996
from django.core.cache import cache from django.contrib.sites.models import Site from django.template import Library, Node, Variable from django.template import TemplateSyntaxError, VariableDoesNotExist from product.models import Category, CategoryAttribute from satchmo_utils.templatetags import get_filter_args from django.utils.translation import get_language import logging import re log = logging.getLogger('shop.templatetags') try: from xml.etree.ElementTree import Element, SubElement, tostring except ImportError: from elementtree.ElementTree import Element, SubElement, tostring register = Library() def recurse_for_children(current_node, parent_node, active_cat, show_empty=True): child_count = current_node.child.active().count() if show_empty or child_count > 0 or current_node.product_set.count() > 0: li_id = 'category-%s' % current_node.id li_attrs = {'id': li_id } temp_parent = SubElement(parent_node, 'li', li_attrs) attrs = {'href': current_node.get_absolute_url()} link = SubElement(temp_parent, 'a', attrs) link.text = current_node.translated_name() if child_count > 0: new_parent = SubElement(temp_parent, 'ul') children = current_node.child.active() for child in children: recurse_for_children(child, new_parent, active_cat) @register.simple_tag def category_tree(id=None): """ Creates an unnumbered list of the categories. Example:: <ul> <li>Books <ul> <li>Science Fiction <ul> <li>Space stories</li> <li>Robot stories</li> </ul> </li> <li>Non-fiction</li> </ul> </ul> """ active_cat = None if id: try: active_cat = Category.objects.active().get(id=id) except Category.DoesNotExist: active_cat = None # We call the category on every page so we will cache # The actual structure to save db hits lang = get_language() current_site = Site.objects.get_current() cache_key = "cat-%s-%s" % (current_site.id, lang) existing_tree = cache.get(cache_key, None) if existing_tree is None: root = Element("ul") for cats in Category.objects.root_categories(): recurse_for_children(cats, root, active_cat) existing_tree = root cache.set(cache_key, existing_tree) # If we have an active cat, search through and identify it # This search is less expensive than the multiple db calls if active_cat: active_cat_id = "category-%s" % active_cat.id for li in existing_tree.getiterator("li"): if li.attrib["id"] == active_cat_id: link = li.find("a") link.attrib["class"] = "current" break return tostring(existing_tree, 'utf-8') class CategoryListNode(Node): """Template Node tag which pushes the category list into the context""" def __init__(self, slug, var, nodelist): self.var = var self.slug = slug self.nodelist = nodelist def render(self, context): if self.slug: try: cat = Category.objects.active().get(slug__iexact=self.slug.resolve(context)) cats = cat.child.all() except (Category.DoesNotExist, VariableDoesNotExist): log.warn("No category found for slug: %s", self.slug) cats = [] else: cats = Category.objects.root_categories() context[self.var] = cats context.push() context[self.var] = cats output = self.nodelist.render(context) context.pop() return output @register.tag def category_list(parser, token): """Push the category list into the context using the given variable name. Sample usage:: {% category_list slug as var %} or {% category_list as var %} """ args = token.split_contents() ct = len(args) if not ct in (3,4): raise TemplateSyntaxError("%r tag expecting '[slug] as varname', got: %s" % (args[0], args)) if ct == 3: slug = None var = args[2] else: slug = Variable(args[1]) var = args[3] nodelist = parser.parse(('endcategory_list',)) parser.delete_first_token() return CategoryListNode(slug, var, nodelist) class SetVariableInContextNode(Node): def __init__(self, var, val): self.var = var self.val = val def render(self, context): context[self.var] = self.val return '' @register.tag def categories_for_slugs(parser, token): """ Usage: {% categories_for_slugs "slug[,slug...]" as varname %} Sets the variable *varname* in the context to a list of categories, given by the list of slugs. Useful if you want to specify a custom list of categories and override the default category listing from satchmo. Example usage:: {% categories_for_slug "hats,boots,accessories" as categories %} <ul> {% for child in categories.child.active %} <li><a href="{{ child.get_absolute_url }}">{{ child.translated_name }}</a></li> {% endfor %} </ul> """ try: # Splitting by None == splitting by spaces. tag_name, arg = token.contents.split(None, 1) except ValueError: raise TemplateSyntaxError, "%r tag requires arguments" \ % token.contents.split()[0] m = re.search(r'"([^ "]+)" as (\w+)', arg) if not m: raise TemplateSyntaxError, "%r tag had invalid arguments" \ % tag_name cat_slugs, var = m.groups() cats=[] for cat_slug in cat_slugs.split(','): try: cat = Category.objects.get(slug__iexact=cat_slug) except Category.DoesNotExist: log.warn("No category found for slug: %s", cat_slug) cat = None cats.append(cat) return SetVariableInContextNode(var, cats) @register.filter def product_category_siblings(product, args=""): args, kwargs = get_filter_args(args, keywords=('variations', 'include_self'), boolargs=('variations', 'include_self'), stripquotes=True) sibs = product.get_category.product_set.all().order_by('ordering', 'name') if not kwargs.get('variations', True): sibs = [sib for sib in sibs if not sib.has_variants] if not kwargs.get('include_self', True): sibs = [sib for sib in sibs if not sib == product] return sibs class AllProductsForVariableSlugNode(Node): """ Sets the variable *var* in the context to result of category.active_products(include_children=True) where category is the instance of Category with the slug specified in the context variable *slug_var*. """ def __init__(self, slug_var, var): self.slug_var = slug_var self.var = var def render(self, context): try: slug = self.slug_var.resolve(context) except VariableDoesNotExist: log.error("The variable '%s' was not found in the context.", self.slug_var) return '' try: cat = Category.objects.active().get(slug__iexact=slug) except Category.DoesNotExist: log.error("No category found for slug: %s" % slug) return '' context[self.var] = cat.active_products(include_children=True) return '' class AllProductsForSlugNode(Node): """ Sets the variable *var* in the context to result of category.active_products(include_children=True) where category is the instance of Category with the slug *slug*. """ def __init__(self, slug, var): self.slug = slug self.var = var def render(self, context): try: cat = Category.objects.active().get(slug__iexact=self.slug) except Category.DoesNotExist: log.error("No category found for slug: %s" % self.slug) return '' context[self.var] = cat.active_products(include_children=True) return '' class AllProductsNode(Node): """ Sets the variable *var* in the context to result of category.active_products(include_children=True) where category is the variable *category* in the context. """ def __init__(self, var): self.var = var def render(self, context): cat = context.get('category') if not cat: log.error("The variable 'category' was not found in the context.") context[self.var] = cat.active_products(include_children=True) return '' @register.tag def all_products_for_category(parser, token): """ Usage: 1. {% all_products_for_category as varname %} 2. {% all_products_for_category for slug_var as varname %} 3. {% all_products_for_category for "slug" as varname %} Sets the variable *varname* in the context to a list of all products that are active in *category*, and is equivalent to the result of: category.active_products(include_children=True) where *category* is: 1. the 'category' variable in the context, for usage 1. 2. the instance of Category with the slug in the context variable *slug_var*, for usage 2. 3. the instance of Category with the slug *slug*, for usage 3. """ try: # Splitting by None == splitting by spaces. tag_name, arg = token.contents.split(None, 1) except ValueError: raise TemplateSyntaxError, "%r tag requires arguments" \ % token.contents.split()[0] m = re.search(r'(.*?)as (\w+)$', arg) # First, get the varname - the easiest if not m: raise TemplateSyntaxError, "Variable name was not specified for %r tag" \ % tag_name arg, var = m.groups() # Now, try and determine usage case the user wants if not arg: # We're of the first case. return AllProductsNode(var) m = re.search(r'^for (.+?)$', arg.strip()) if not m: raise TemplateSyntaxError, "Invalid arguments for %r tag" \ % tag_name arg = m.group(1) if arg[0] == '"' and arg[-1] == '"': # We're of the third case. cat_var = arg[1:-1] return AllProductsForSlugNode(arg[1:-1], var) elif arg: # We're of the second case. return AllProductsForVariableSlugNode(Variable(arg), var) raise TemplateSyntaxError, "Invalid arguments for %r tag" \ % tag_name @register.filter def attribute(category, attr_name): """ usage: {{ category|attribute:"attr-name" }} prints the attribute named `attr-name`'s value """ try: return category.categoryattribute_set.get(option__name=attr_name).value except CategoryAttribute.DoesNotExist: return ""
bsd-3-clause
8,595,469,009,251,158,000
29.974648
100
0.603583
false
Sharecare/cyclops
app/objects.py
1
1631
import json import time import logging import pprint pp = pprint.PrettyPrinter(indent=4) logger = logging.getLogger(__name__) # a monitor object defines a particular unit of work. it is # made up of the following: # name: the name for the monitor # check: the worker to perform the check against # interval: how often within the hour to perform the check # destination: where we point the check to # args: arbitrary info passed to the worker when performing the check class Monitor: def __init__(self, config, destination, destconfig): self.config = config.copy() self.whenMap = {} self.config['destination'] = destination self.config['destconfig'] = destconfig.copy() # build a dictionary for each minute in the hour that the # check should be performed count = 60 / config['interval'] for i in range(count): self.whenMap[i * config['interval']] = True def get(self): return(self.config) def getPriority(self): if self.config.has_key('priority'): return(int(self.config['priority'])) else: return(20) # if the current minute is found in the interval dictinary, # then we should be running in this minute def shouldRun(self, now): try: if self.whenMap[now]: return(True) except: pass return(False) # build a response object based on what we get back from a worker performing a check class PollResponse: def __init__(self, config, msg): self.response = {'time': time.time(), 'msg': msg, 'config': config} def get(self): return(self.response)
apache-2.0
3,837,949,277,895,527,000
27.12069
84
0.659105
false
acsone/partner-contact
partner_relations/tests/test_partner_relation_common.py
5
4380
# -*- coding: utf-8 -*- # Copyright 2016 Therp BV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests import common class TestPartnerRelationCommon(common.TransactionCase): def setUp(self): super(TestPartnerRelationCommon, self).setUp() self.partner_model = self.env['res.partner'] self.category_model = self.env['res.partner.category'] self.type_model = self.env['res.partner.relation.type'] self.selection_model = self.env['res.partner.relation.type.selection'] self.relation_model = self.env['res.partner.relation'] self.relation_all_model = self.env['res.partner.relation.all'] self.partner_01_person = self.partner_model.create({ 'name': 'Test User 1', 'is_company': False, 'ref': 'PR01', }) self.partner_02_company = self.partner_model.create({ 'name': 'Test Company', 'is_company': True, 'ref': 'PR02', }) # Create partners with specific categories: self.category_01_ngo = self.category_model.create({ 'name': 'NGO', }) self.partner_03_ngo = self.partner_model.create({ 'name': 'Test NGO', 'is_company': True, 'ref': 'PR03', 'category_id': [(4, self.category_01_ngo.id)], }) self.category_02_volunteer = self.category_model.create({ 'name': 'Volunteer', }) self.partner_04_volunteer = self.partner_model.create({ 'name': 'Test Volunteer', 'is_company': False, 'ref': 'PR04', 'category_id': [(4, self.category_02_volunteer.id)], }) # Create a new relation type withouth categories: (self.type_company2person, self.selection_company2person, self.selection_person2company) = ( self._create_relation_type_selection({ 'name': 'mixed', 'name_inverse': 'mixed_inverse', 'contact_type_left': 'c', 'contact_type_right': 'p', }) ) # Create a new relation type with categories: (self.type_ngo2volunteer, self.selection_ngo2volunteer, self.selection_volunteer2ngo) = ( self._create_relation_type_selection({ 'name': 'NGO has volunteer', 'name_inverse': 'volunteer works for NGO', 'contact_type_left': 'c', 'contact_type_right': 'p', 'partner_category_left': self.category_01_ngo.id, 'partner_category_right': self.category_02_volunteer.id, }) ) def _create_relation_type_selection(self, vals): """Create relation type and return this with selection types.""" assert 'name' in vals, ( "Name missing in vals to create relation type. Vals: %s." % vals ) assert 'name' in vals, ( "Name_inverse missing in vals to create relation type. Vals: %s." % vals ) new_type = self.type_model.create(vals) self.assertTrue( new_type, msg="No relation type created with vals %s." % vals ) selection_types = self.selection_model.search([ ('type_id', '=', new_type.id), ]) for st in selection_types: if st.is_inverse: inverse_type_selection = st else: type_selection = st self.assertTrue( inverse_type_selection, msg="Failed to find inverse type selection based on" " relation type created with vals %s." % vals ) self.assertTrue( type_selection, msg="Failed to find type selection based on" " relation type created with vals %s." % vals ) return (new_type, type_selection, inverse_type_selection) def _create_company2person_relation(self): """Utility function to get a relation from company 2 partner.""" return self.relation_all_model.create({ 'type_selection_id': self.selection_company2person.id, 'this_partner_id': self.partner_02_company.id, 'other_partner_id': self.partner_01_person.id, })
agpl-3.0
-3,033,887,098,215,274,000
37.761062
78
0.550685
false
gencer/sentry
tests/sentry/api/endpoints/test_group_tags.py
1
1657
from __future__ import absolute_import from sentry import tagstore from sentry.testutils import APITestCase class GroupTagsTest(APITestCase): def test_simple(self): this_group = self.create_group() this_group.data['tags'] = (['foo', 'bar'], ['biz', 'baz']) this_group.save() other_group = self.create_group() other_group.data['tags'] = (['abc', 'xyz'], ) other_group.save() for group in (this_group, other_group): for key, value in group.data['tags']: tagstore.create_tag_key( project_id=group.project_id, environment_id=None, key=key, ) tagstore.create_tag_value( project_id=group.project_id, environment_id=None, key=key, value=value, ) tagstore.create_group_tag_key( project_id=group.project_id, group_id=group.id, environment_id=None, key=key, ) tagstore.create_group_tag_value( project_id=group.project_id, group_id=group.id, environment_id=None, key=key, value=value, ) self.login_as(user=self.user) url = '/api/0/issues/{}/tags/'.format(this_group.id) response = self.client.get(url, format='json') assert response.status_code == 200, response.content assert len(response.data) == 2
bsd-3-clause
-457,494,111,673,794,560
32.816327
66
0.483404
false
mitocw/edx-platform
common/djangoapps/util/models.py
3
2042
"""Models for the util app. """ import gzip import logging from io import BytesIO import six from config_models.models import ConfigurationModel from django.db import models from django.utils.text import compress_string from opaque_keys.edx.django.models import CreatorMixin logger = logging.getLogger(__name__) # pylint: disable=invalid-name class RateLimitConfiguration(ConfigurationModel): """ Configuration flag to enable/disable rate limiting. Applies to Django Rest Framework views. This is useful for disabling rate limiting for performance tests. When enabled, it will disable rate limiting on any view decorated with the `can_disable_rate_limit` class decorator. .. no_pii: """ class Meta(ConfigurationModel.Meta): app_label = "util" def decompress_string(value): """ Helper function to reverse CompressedTextField.get_prep_value. """ try: val = value.encode('utf').decode('base64') zbuf = BytesIO(val) zfile = gzip.GzipFile(fileobj=zbuf) ret = zfile.read() zfile.close() except Exception as e: logger.error('String decompression failed. There may be corrupted data in the database: %s', e) ret = value return ret class CompressedTextField(CreatorMixin, models.TextField): """ TextField that transparently compresses data when saving to the database, and decompresses the data when retrieving it from the database. """ def get_prep_value(self, value): """ Compress the text data. """ if value is not None: if isinstance(value, six.text_type): value = value.encode('utf8') value = compress_string(value) value = value.encode('base64').decode('utf8') return value def to_python(self, value): """ Decompresses the value from the database. """ if isinstance(value, six.text_type): value = decompress_string(value) return value
agpl-3.0
2,082,657,584,972,630,500
26.594595
103
0.65573
false
msimacek/samba
third_party/waf/wafadmin/Tools/cs.py
32
1802
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2006 (ita) "C# support" import TaskGen, Utils, Task, Options from Logs import error from TaskGen import before, after, taskgen, feature flag_vars= ['FLAGS', 'ASSEMBLIES'] @feature('cs') def init_cs(self): Utils.def_attrs(self, flags = '', assemblies = '', resources = '', uselib = '') @feature('cs') @after('init_cs') def apply_uselib_cs(self): if not self.uselib: return global flag_vars for var in self.to_list(self.uselib): for v in self.flag_vars: val = self.env[v+'_'+var] if val: self.env.append_value(v, val) @feature('cs') @after('apply_uselib_cs') @before('apply_core') def apply_cs(self): try: self.meths.remove('apply_core') except ValueError: pass # process the flags for the assemblies for i in self.to_list(self.assemblies) + self.env['ASSEMBLIES']: self.env.append_unique('_ASSEMBLIES', '/r:'+i) # process the flags for the resources for i in self.to_list(self.resources): self.env.append_unique('_RESOURCES', '/resource:'+i) # what kind of assembly are we generating? self.env['_TYPE'] = getattr(self, 'type', 'exe') # additional flags self.env.append_unique('_FLAGS', self.to_list(self.flags)) self.env.append_unique('_FLAGS', self.env.FLAGS) # process the sources nodes = [self.path.find_resource(i) for i in self.to_list(self.source)] self.create_task('mcs', nodes, self.path.find_or_declare(self.target)) Task.simple_task_type('mcs', '${MCS} ${SRC} /target:${_TYPE} /out:${TGT} ${_FLAGS} ${_ASSEMBLIES} ${_RESOURCES}', color='YELLOW') def detect(conf): csc = getattr(Options.options, 'cscbinary', None) if csc: conf.env.MCS = csc conf.find_program(['gmcs', 'mcs'], var='MCS') def set_options(opt): opt.add_option('--with-csc-binary', type='string', dest='cscbinary')
gpl-3.0
182,834,629,318,395,940
25.895522
129
0.677026
false
ssmruthi/mycroft-core
mycroft/skills/main.py
1
2371
# Copyright 2016 Mycroft AI, Inc. # # This file is part of Mycroft Core. # # Mycroft Core 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. # # Mycroft Core 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 Mycroft Core. If not, see <http://www.gnu.org/licenses/>. import json import sys from os.path import expanduser, exists from mycroft.configuration import ConfigurationManager from mycroft.messagebus.client.ws import WebsocketClient from mycroft.skills.core import load_skills, THIRD_PARTY_SKILLS_DIR from mycroft.util.log import getLogger logger = getLogger("Skills") __author__ = 'seanfitz' ws = None skills = [] def load_skills_callback(): global ws global skills skills += load_skills(ws) config = ConfigurationManager.get().get("skills") try: ini_third_party_skills_dir = expanduser(config.get("directory")) except AttributeError as e: logger.warning(e.message) for loc in THIRD_PARTY_SKILLS_DIR: if exists(loc): skills += load_skills(ws, loc) if ini_third_party_skills_dir and exists(ini_third_party_skills_dir): skills += load_skills(ws, ini_third_party_skills_dir) def connect(): global ws ws.run_forever() def main(): global ws ws = WebsocketClient() ConfigurationManager.init(ws) def echo(message): try: _message = json.loads(message) if _message.get("type") == "registration": # do not log tokens from registration messages _message["data"]["token"] = None message = json.dumps(_message) except: pass logger.debug(message) ws.on('message', echo) ws.once('open', load_skills_callback) ws.run_forever() if __name__ == "__main__": try: main() except KeyboardInterrupt: for skill in skills: skill.shutdown() finally: sys.exit()
gpl-3.0
7,545,943,746,307,939,000
25.054945
73
0.664698
false
christophmeissner/volunteer_planner
organizations/migrations/0008_add_slug_field.py
5
1608
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys from django.db import models, migrations from django.utils.text import slugify from common.migrations import skip def add_slugs(apps, schema_editor): organization_model = apps.get_model('organizations', 'Organization') facility_model = apps.get_model('organizations', 'Facility') for model in (organization_model, facility_model): for instance in model.objects.all(): instance.slug = slugify(instance.name)[:80] or slugify('{}'.format(instance.id)) instance.save() sys.stdout.write(u'{} -> {}\n'.format(instance, instance.slug)) class Migration(migrations.Migration): dependencies = [ ('organizations', '0007_auto_20151023_2129'), ] operations = [ migrations.AddField( model_name='facility', name='slug', field=models.SlugField(max_length=80, null=True, verbose_name='slug', blank=True), ), migrations.AddField( model_name='organization', name='slug', field=models.SlugField(max_length=80, null=True, verbose_name='slug', blank=True), ), migrations.RunPython(add_slugs, skip), migrations.AlterField( model_name='facility', name='slug', field=models.SlugField(max_length=80, verbose_name='slug'), ), migrations.AlterField( model_name='organization', name='slug', field=models.SlugField(max_length=80, verbose_name='slug'), ), ]
agpl-3.0
8,913,463,082,941,898,000
30.529412
94
0.605721
false
nzavagli/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Cython-0.22.1/Cython/Compiler/UtilityCode.py
4
8067
from __future__ import absolute_import from .TreeFragment import parse_from_strings, StringParseContext from . import Symtab from . import Naming from . import Code class NonManglingModuleScope(Symtab.ModuleScope): cpp = False def __init__(self, prefix, *args, **kw): self.prefix = prefix self.cython_scope = None Symtab.ModuleScope.__init__(self, *args, **kw) def add_imported_entry(self, name, entry, pos): entry.used = True return super(NonManglingModuleScope, self).add_imported_entry( name, entry, pos) def mangle(self, prefix, name=None): if name: if prefix in (Naming.typeobj_prefix, Naming.func_prefix, Naming.var_prefix, Naming.pyfunc_prefix): # Functions, classes etc. gets a manually defined prefix easily # manually callable instead (the one passed to CythonUtilityCode) prefix = self.prefix return "%s%s" % (prefix, name) else: return Symtab.ModuleScope.mangle(self, prefix) class CythonUtilityCodeContext(StringParseContext): scope = None def find_module(self, module_name, relative_to=None, pos=None, need_pxd=True): if module_name != self.module_name: if module_name not in self.modules: raise AssertionError("Only the cython cimport is supported.") else: return self.modules[module_name] if self.scope is None: self.scope = NonManglingModuleScope( self.prefix, module_name, parent_module=None, context=self) return self.scope class CythonUtilityCode(Code.UtilityCodeBase): """ Utility code written in the Cython language itself. The @cname decorator can set the cname for a function, method of cdef class. Functions decorated with @cname('c_func_name') get the given cname. For cdef classes the rules are as follows: obj struct -> <cname>_obj obj type ptr -> <cname>_type methods -> <class_cname>_<method_cname> For methods the cname decorator is optional, but without the decorator the methods will not be prototyped. See Cython.Compiler.CythonScope and tests/run/cythonscope.pyx for examples. """ is_cython_utility = True def __init__(self, impl, name="__pyxutil", prefix="", requires=None, file=None, from_scope=None, context=None, compiler_directives=None, outer_module_scope=None): # 1) We need to delay the parsing/processing, so that all modules can be # imported without import loops # 2) The same utility code object can be used for multiple source files; # while the generated node trees can be altered in the compilation of a # single file. # Hence, delay any processing until later. if context is not None: impl = Code.sub_tempita(impl, context, file, name) self.impl = impl self.name = name self.file = file self.prefix = prefix self.requires = requires or [] self.from_scope = from_scope self.outer_module_scope = outer_module_scope self.compiler_directives = compiler_directives def __eq__(self, other): if isinstance(other, CythonUtilityCode): return self._equality_params() == other._equality_params() else: return False def _equality_params(self): outer_scope = self.outer_module_scope while isinstance(outer_scope, NonManglingModuleScope): outer_scope = outer_scope.outer_scope return self.impl, outer_scope, self.compiler_directives def __hash__(self): return hash(self.impl) def get_tree(self, entries_only=False, cython_scope=None): from .AnalysedTreeTransforms import AutoTestDictTransform # The AutoTestDictTransform creates the statement "__test__ = {}", # which when copied into the main ModuleNode overwrites # any __test__ in user code; not desired excludes = [AutoTestDictTransform] from . import Pipeline, ParseTreeTransforms context = CythonUtilityCodeContext( self.name, compiler_directives=self.compiler_directives) context.prefix = self.prefix context.cython_scope = cython_scope #context = StringParseContext(self.name) tree = parse_from_strings( self.name, self.impl, context=context, allow_struct_enum_decorator=True) pipeline = Pipeline.create_pipeline(context, 'pyx', exclude_classes=excludes) if entries_only: p = [] for t in pipeline: p.append(t) if isinstance(p, ParseTreeTransforms.AnalyseDeclarationsTransform): break pipeline = p transform = ParseTreeTransforms.CnameDirectivesTransform(context) # InterpretCompilerDirectives already does a cdef declarator check #before = ParseTreeTransforms.DecoratorTransform before = ParseTreeTransforms.InterpretCompilerDirectives pipeline = Pipeline.insert_into_pipeline(pipeline, transform, before=before) if self.from_scope: def scope_transform(module_node): module_node.scope.merge_in(self.from_scope) return module_node transform = ParseTreeTransforms.AnalyseDeclarationsTransform pipeline = Pipeline.insert_into_pipeline(pipeline, scope_transform, before=transform) if self.outer_module_scope: # inject outer module between utility code module and builtin module def scope_transform(module_node): module_node.scope.outer_scope = self.outer_module_scope return module_node transform = ParseTreeTransforms.AnalyseDeclarationsTransform pipeline = Pipeline.insert_into_pipeline(pipeline, scope_transform, before=transform) (err, tree) = Pipeline.run_pipeline(pipeline, tree, printtree=False) assert not err, err return tree def put_code(self, output): pass @classmethod def load_as_string(cls, util_code_name, from_file=None, **kwargs): """ Load a utility code as a string. Returns (proto, implementation) """ util = cls.load(util_code_name, from_file, **kwargs) return util.proto, util.impl # keep line numbers => no lstrip() def declare_in_scope(self, dest_scope, used=False, cython_scope=None, whitelist=None): """ Declare all entries from the utility code in dest_scope. Code will only be included for used entries. If module_name is given, declare the type entries with that name. """ tree = self.get_tree(entries_only=True, cython_scope=cython_scope) entries = tree.scope.entries entries.pop('__name__') entries.pop('__file__') entries.pop('__builtins__') entries.pop('__doc__') for name, entry in entries.iteritems(): entry.utility_code_definition = self entry.used = used original_scope = tree.scope dest_scope.merge_in(original_scope, merge_unused=True, whitelist=whitelist) tree.scope = dest_scope for dep in self.requires: if dep.is_cython_utility: dep.declare_in_scope(dest_scope) return original_scope def declare_declarations_in_scope(declaration_string, env, private_type=True, *args, **kwargs): """ Declare some declarations given as Cython code in declaration_string in scope env. """ CythonUtilityCode(declaration_string, *args, **kwargs).declare_in_scope(env)
mit
458,207,164,308,549,000
37.783654
110
0.61671
false
kohoumas/ns-3-click-mac-dev
src/wimax/bindings/modulegen__gcc_LP64.py
1
732891
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.wimax', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## ul-job.h (module 'wimax'): ns3::ReqType [enumeration] module.add_enum('ReqType', ['DATA', 'UNICAST_POLLING']) ## log.h (module 'core'): ns3::LogLevel [enumeration] module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_INFO', 'LOG_FUNCTION', 'LOG_LEVEL_FUNCTION', 'LOG_LOGIC', 'LOG_LEVEL_LOGIC', 'LOG_ALL', 'LOG_LEVEL_ALL', 'LOG_PREFIX_FUNC', 'LOG_PREFIX_TIME', 'LOG_PREFIX_NODE'], import_from_module='ns.core') ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class] module.add_class('AsciiTraceHelper', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class] module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True, import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## cid.h (module 'wimax'): ns3::Cid [class] module.add_class('Cid') ## cid.h (module 'wimax'): ns3::Cid::Type [enumeration] module.add_enum('Type', ['BROADCAST', 'INITIAL_RANGING', 'BASIC', 'PRIMARY', 'TRANSPORT', 'MULTICAST', 'PADDING'], outer_class=root_module['ns3::Cid']) ## cid-factory.h (module 'wimax'): ns3::CidFactory [class] module.add_class('CidFactory') ## cs-parameters.h (module 'wimax'): ns3::CsParameters [class] module.add_class('CsParameters') ## cs-parameters.h (module 'wimax'): ns3::CsParameters::Action [enumeration] module.add_enum('Action', ['ADD', 'REPLACE', 'DELETE'], outer_class=root_module['ns3::CsParameters']) ## dl-mac-messages.h (module 'wimax'): ns3::DcdChannelEncodings [class] module.add_class('DcdChannelEncodings', allow_subclassing=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): ns3::DlFramePrefixIe [class] module.add_class('DlFramePrefixIe') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord [class] module.add_class('IpcsClassifierRecord') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## log.h (module 'core'): ns3::LogComponent [class] module.add_class('LogComponent', import_from_module='ns.core') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDcdChannelEncodings [class] module.add_class('OfdmDcdChannelEncodings', parent=root_module['ns3::DcdChannelEncodings']) ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDlBurstProfile [class] module.add_class('OfdmDlBurstProfile') ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDlBurstProfile::Diuc [enumeration] module.add_enum('Diuc', ['DIUC_STC_ZONE', 'DIUC_BURST_PROFILE_1', 'DIUC_BURST_PROFILE_2', 'DIUC_BURST_PROFILE_3', 'DIUC_BURST_PROFILE_4', 'DIUC_BURST_PROFILE_5', 'DIUC_BURST_PROFILE_6', 'DIUC_BURST_PROFILE_7', 'DIUC_BURST_PROFILE_8', 'DIUC_BURST_PROFILE_9', 'DIUC_BURST_PROFILE_10', 'DIUC_BURST_PROFILE_11', 'DIUC_GAP', 'DIUC_END_OF_MAP'], outer_class=root_module['ns3::OfdmDlBurstProfile']) ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDlMapIe [class] module.add_class('OfdmDlMapIe') ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUlBurstProfile [class] module.add_class('OfdmUlBurstProfile') ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUlBurstProfile::Uiuc [enumeration] module.add_enum('Uiuc', ['UIUC_INITIAL_RANGING', 'UIUC_REQ_REGION_FULL', 'UIUC_REQ_REGION_FOCUSED', 'UIUC_FOCUSED_CONTENTION_IE', 'UIUC_BURST_PROFILE_5', 'UIUC_BURST_PROFILE_6', 'UIUC_BURST_PROFILE_7', 'UIUC_BURST_PROFILE_8', 'UIUC_BURST_PROFILE_9', 'UIUC_BURST_PROFILE_10', 'UIUC_BURST_PROFILE_11', 'UIUC_BURST_PROFILE_12', 'UIUC_SUBCH_NETWORK_ENTRY', 'UIUC_END_OF_MAP'], outer_class=root_module['ns3::OfdmUlBurstProfile']) ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUlMapIe [class] module.add_class('OfdmUlMapIe') ## 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']) ## pcap-file.h (module 'network'): ns3::PcapFile [class] module.add_class('PcapFile', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelper [class] module.add_class('PcapHelper', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelper [enumeration] module.add_enum('', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO'], outer_class=root_module['ns3::PcapHelper'], import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class] module.add_class('PcapHelperForDevice', allow_subclassing=True, import_from_module='ns.network') ## random-variable.h (module 'core'): ns3::RandomVariable [class] module.add_class('RandomVariable', import_from_module='ns.core') ## snr-to-block-error-rate-manager.h (module 'wimax'): ns3::SNRToBlockErrorRateManager [class] module.add_class('SNRToBlockErrorRateManager') ## snr-to-block-error-rate-record.h (module 'wimax'): ns3::SNRToBlockErrorRateRecord [class] module.add_class('SNRToBlockErrorRateRecord') ## ss-record.h (module 'wimax'): ns3::SSRecord [class] module.add_class('SSRecord') ## random-variable.h (module 'core'): ns3::SeedManager [class] module.add_class('SeedManager', import_from_module='ns.core') ## send-params.h (module 'wimax'): ns3::SendParams [class] module.add_class('SendParams') ## random-variable.h (module 'core'): ns3::SequentialVariable [class] module.add_class('SequentialVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## service-flow.h (module 'wimax'): ns3::ServiceFlow [class] module.add_class('ServiceFlow') ## service-flow.h (module 'wimax'): ns3::ServiceFlow::Direction [enumeration] module.add_enum('Direction', ['SF_DIRECTION_DOWN', 'SF_DIRECTION_UP'], outer_class=root_module['ns3::ServiceFlow']) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::Type [enumeration] module.add_enum('Type', ['SF_TYPE_PROVISIONED', 'SF_TYPE_ADMITTED', 'SF_TYPE_ACTIVE'], outer_class=root_module['ns3::ServiceFlow']) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::SchedulingType [enumeration] module.add_enum('SchedulingType', ['SF_TYPE_NONE', 'SF_TYPE_UNDEF', 'SF_TYPE_BE', 'SF_TYPE_NRTPS', 'SF_TYPE_RTPS', 'SF_TYPE_UGS', 'SF_TYPE_ALL'], outer_class=root_module['ns3::ServiceFlow']) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::CsSpecification [enumeration] module.add_enum('CsSpecification', ['ATM', 'IPV4', 'IPV6', 'ETHERNET', 'VLAN', 'IPV4_OVER_ETHERNET', 'IPV6_OVER_ETHERNET', 'IPV4_OVER_VLAN', 'IPV6_OVER_VLAN'], outer_class=root_module['ns3::ServiceFlow']) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::ModulationType [enumeration] module.add_enum('ModulationType', ['MODULATION_TYPE_BPSK_12', 'MODULATION_TYPE_QPSK_12', 'MODULATION_TYPE_QPSK_34', 'MODULATION_TYPE_QAM16_12', 'MODULATION_TYPE_QAM16_34', 'MODULATION_TYPE_QAM64_23', 'MODULATION_TYPE_QAM64_34'], outer_class=root_module['ns3::ServiceFlow']) ## service-flow-record.h (module 'wimax'): ns3::ServiceFlowRecord [class] module.add_class('ServiceFlowRecord') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', is_singleton=True, 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') ## wimax-tlv.h (module 'wimax'): ns3::TlvValue [class] module.add_class('TlvValue', allow_subclassing=True) ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue [class] module.add_class('TosTlvValue', parent=root_module['ns3::TlvValue']) ## random-variable.h (module 'core'): ns3::TriangularVariable [class] module.add_class('TriangularVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## 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']) ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue [class] module.add_class('U16TlvValue', parent=root_module['ns3::TlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue [class] module.add_class('U32TlvValue', parent=root_module['ns3::TlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue [class] module.add_class('U8TlvValue', parent=root_module['ns3::TlvValue']) ## ul-mac-messages.h (module 'wimax'): ns3::UcdChannelEncodings [class] module.add_class('UcdChannelEncodings', allow_subclassing=True) ## random-variable.h (module 'core'): ns3::UniformVariable [class] module.add_class('UniformVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## wimax-tlv.h (module 'wimax'): ns3::VectorTlvValue [class] module.add_class('VectorTlvValue', parent=root_module['ns3::TlvValue']) ## random-variable.h (module 'core'): ns3::WeibullVariable [class] module.add_class('WeibullVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## wimax-helper.h (module 'wimax'): ns3::WimaxHelper [class] module.add_class('WimaxHelper', parent=[root_module['ns3::PcapHelperForDevice'], root_module['ns3::AsciiTraceHelperForDevice']]) ## wimax-helper.h (module 'wimax'): ns3::WimaxHelper::NetDeviceType [enumeration] module.add_enum('NetDeviceType', ['DEVICE_TYPE_SUBSCRIBER_STATION', 'DEVICE_TYPE_BASE_STATION'], outer_class=root_module['ns3::WimaxHelper']) ## wimax-helper.h (module 'wimax'): ns3::WimaxHelper::PhyType [enumeration] module.add_enum('PhyType', ['SIMPLE_PHY_TYPE_OFDM'], outer_class=root_module['ns3::WimaxHelper']) ## wimax-helper.h (module 'wimax'): ns3::WimaxHelper::SchedulerType [enumeration] module.add_enum('SchedulerType', ['SCHED_TYPE_SIMPLE', 'SCHED_TYPE_RTPS', 'SCHED_TYPE_MBQOS'], outer_class=root_module['ns3::WimaxHelper']) ## random-variable.h (module 'core'): ns3::ZetaVariable [class] module.add_class('ZetaVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## random-variable.h (module 'core'): ns3::ZipfVariable [class] module.add_class('ZipfVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## 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') ## simple-ofdm-send-param.h (module 'wimax'): ns3::simpleOfdmSendParam [class] module.add_class('simpleOfdmSendParam') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue [class] module.add_class('ClassificationRuleVectorTlvValue', parent=root_module['ns3::VectorTlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue::ClassificationRuleTlvType [enumeration] module.add_enum('ClassificationRuleTlvType', ['Priority', 'ToS', 'Protocol', 'IP_src', 'IP_dst', 'Port_src', 'Port_dst', 'Index'], outer_class=root_module['ns3::ClassificationRuleVectorTlvValue']) ## random-variable.h (module 'core'): ns3::ConstantVariable [class] module.add_class('ConstantVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue [class] module.add_class('CsParamVectorTlvValue', parent=root_module['ns3::VectorTlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue::Type [enumeration] module.add_enum('Type', ['Classifier_DSC_Action', 'Packet_Classification_Rule'], outer_class=root_module['ns3::CsParamVectorTlvValue']) ## random-variable.h (module 'core'): ns3::DeterministicVariable [class] module.add_class('DeterministicVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## random-variable.h (module 'core'): ns3::EmpiricalVariable [class] module.add_class('EmpiricalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## random-variable.h (module 'core'): ns3::ErlangVariable [class] module.add_class('ErlangVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## random-variable.h (module 'core'): ns3::ExponentialVariable [class] module.add_class('ExponentialVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## random-variable.h (module 'core'): ns3::GammaVariable [class] module.add_class('GammaVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## random-variable.h (module 'core'): ns3::IntEmpiricalVariable [class] module.add_class('IntEmpiricalVariable', import_from_module='ns.core', parent=root_module['ns3::EmpiricalVariable']) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue [class] module.add_class('Ipv4AddressTlvValue', parent=root_module['ns3::TlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr [struct] module.add_class('ipv4Addr', outer_class=root_module['ns3::Ipv4AddressTlvValue']) ## random-variable.h (module 'core'): ns3::LogNormalVariable [class] module.add_class('LogNormalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## wimax-mac-header.h (module 'wimax'): ns3::MacHeaderType [class] module.add_class('MacHeaderType', parent=root_module['ns3::Header']) ## wimax-mac-header.h (module 'wimax'): ns3::MacHeaderType::HeaderType [enumeration] module.add_enum('HeaderType', ['HEADER_TYPE_GENERIC', 'HEADER_TYPE_BANDWIDTH'], outer_class=root_module['ns3::MacHeaderType']) ## mac-messages.h (module 'wimax'): ns3::ManagementMessageType [class] module.add_class('ManagementMessageType', parent=root_module['ns3::Header']) ## mac-messages.h (module 'wimax'): ns3::ManagementMessageType::MessageType [enumeration] module.add_enum('MessageType', ['MESSAGE_TYPE_UCD', 'MESSAGE_TYPE_DCD', 'MESSAGE_TYPE_DL_MAP', 'MESSAGE_TYPE_UL_MAP', 'MESSAGE_TYPE_RNG_REQ', 'MESSAGE_TYPE_RNG_RSP', 'MESSAGE_TYPE_REG_REQ', 'MESSAGE_TYPE_REG_RSP', 'MESSAGE_TYPE_DSA_REQ', 'MESSAGE_TYPE_DSA_RSP', 'MESSAGE_TYPE_DSA_ACK'], outer_class=root_module['ns3::ManagementMessageType']) ## random-variable.h (module 'core'): ns3::NormalVariable [class] module.add_class('NormalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## 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']) ## ofdm-downlink-frame-prefix.h (module 'wimax'): ns3::OfdmDownlinkFramePrefix [class] module.add_class('OfdmDownlinkFramePrefix', parent=root_module['ns3::Header']) ## send-params.h (module 'wimax'): ns3::OfdmSendParams [class] module.add_class('OfdmSendParams', parent=root_module['ns3::SendParams']) ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUcdChannelEncodings [class] module.add_class('OfdmUcdChannelEncodings', parent=root_module['ns3::UcdChannelEncodings']) ## packet-burst.h (module 'network'): ns3::PacketBurst [class] module.add_class('PacketBurst', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable.h (module 'core'): ns3::ParetoVariable [class] module.add_class('ParetoVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class] module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=root_module['ns3::Object']) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue [class] module.add_class('PortRangeTlvValue', parent=root_module['ns3::TlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange [struct] module.add_class('PortRange', outer_class=root_module['ns3::PortRangeTlvValue']) ## ul-job.h (module 'wimax'): ns3::PriorityUlJob [class] module.add_class('PriorityUlJob', parent=root_module['ns3::Object']) ## propagation-loss-model.h (module 'propagation'): ns3::PropagationLossModel [class] module.add_class('PropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::Object']) ## wimax-tlv.h (module 'wimax'): ns3::ProtocolTlvValue [class] module.add_class('ProtocolTlvValue', parent=root_module['ns3::TlvValue']) ## propagation-loss-model.h (module 'propagation'): ns3::RandomPropagationLossModel [class] module.add_class('RandomPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## propagation-loss-model.h (module 'propagation'): ns3::RangePropagationLossModel [class] module.add_class('RangePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## mac-messages.h (module 'wimax'): ns3::RngReq [class] module.add_class('RngReq', parent=root_module['ns3::Header']) ## mac-messages.h (module 'wimax'): ns3::RngRsp [class] module.add_class('RngRsp', parent=root_module['ns3::Header']) ## ss-manager.h (module 'wimax'): ns3::SSManager [class] module.add_class('SSManager', parent=root_module['ns3::Object']) ## service-flow-manager.h (module 'wimax'): ns3::ServiceFlowManager [class] module.add_class('ServiceFlowManager', parent=root_module['ns3::Object']) ## service-flow-manager.h (module 'wimax'): ns3::ServiceFlowManager::ConfirmationCode [enumeration] module.add_enum('ConfirmationCode', ['CONFIRMATION_CODE_SUCCESS', 'CONFIRMATION_CODE_REJECT'], outer_class=root_module['ns3::ServiceFlowManager']) ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue [class] module.add_class('SfVectorTlvValue', parent=root_module['ns3::VectorTlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue::Type [enumeration] module.add_enum('Type', ['SFID', 'CID', 'Service_Class_Name', 'reserved1', 'QoS_Parameter_Set_Type', 'Traffic_Priority', 'Maximum_Sustained_Traffic_Rate', 'Maximum_Traffic_Burst', 'Minimum_Reserved_Traffic_Rate', 'Minimum_Tolerable_Traffic_Rate', 'Service_Flow_Scheduling_Type', 'Request_Transmission_Policy', 'Tolerated_Jitter', 'Maximum_Latency', 'Fixed_length_versus_Variable_length_SDU_Indicator', 'SDU_Size', 'Target_SAID', 'ARQ_Enable', 'ARQ_WINDOW_SIZE', 'ARQ_RETRY_TIMEOUT_Transmitter_Delay', 'ARQ_RETRY_TIMEOUT_Receiver_Delay', 'ARQ_BLOCK_LIFETIME', 'ARQ_SYNC_LOSS', 'ARQ_DELIVER_IN_ORDER', 'ARQ_PURGE_TIMEOUT', 'ARQ_BLOCK_SIZE', 'reserved2', 'CS_Specification', 'IPV4_CS_Parameters'], outer_class=root_module['ns3::SfVectorTlvValue']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## ss-service-flow-manager.h (module 'wimax'): ns3::SsServiceFlowManager [class] module.add_class('SsServiceFlowManager', parent=root_module['ns3::ServiceFlowManager']) ## ss-service-flow-manager.h (module 'wimax'): ns3::SsServiceFlowManager::ConfirmationCode [enumeration] module.add_enum('ConfirmationCode', ['CONFIRMATION_CODE_SUCCESS', 'CONFIRMATION_CODE_REJECT'], outer_class=root_module['ns3::SsServiceFlowManager']) ## propagation-loss-model.h (module 'propagation'): ns3::ThreeLogDistancePropagationLossModel [class] module.add_class('ThreeLogDistancePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## 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']) ## wimax-tlv.h (module 'wimax'): ns3::Tlv [class] module.add_class('Tlv', parent=root_module['ns3::Header']) ## wimax-tlv.h (module 'wimax'): ns3::Tlv::CommonTypes [enumeration] module.add_enum('CommonTypes', ['HMAC_TUPLE', 'MAC_VERSION_ENCODING', 'CURRENT_TRANSMIT_POWER', 'DOWNLINK_SERVICE_FLOW', 'UPLINK_SERVICE_FLOW', 'VENDOR_ID_EMCODING', 'VENDOR_SPECIFIC_INFORMATION'], outer_class=root_module['ns3::Tlv']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## propagation-loss-model.h (module 'propagation'): ns3::TwoRayGroundPropagationLossModel [class] module.add_class('TwoRayGroundPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## ul-mac-messages.h (module 'wimax'): ns3::Ucd [class] module.add_class('Ucd', parent=root_module['ns3::Header']) ## ul-job.h (module 'wimax'): ns3::UlJob [class] module.add_class('UlJob', parent=root_module['ns3::Object']) ## ul-job.h (module 'wimax'): ns3::UlJob::JobPriority [enumeration] module.add_enum('JobPriority', ['LOW', 'INTERMEDIATE', 'HIGH'], outer_class=root_module['ns3::UlJob']) ## ul-mac-messages.h (module 'wimax'): ns3::UlMap [class] module.add_class('UlMap', parent=root_module['ns3::Header']) ## bs-uplink-scheduler.h (module 'wimax'): ns3::UplinkScheduler [class] module.add_class('UplinkScheduler', parent=root_module['ns3::Object']) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): ns3::UplinkSchedulerMBQoS [class] module.add_class('UplinkSchedulerMBQoS', parent=root_module['ns3::UplinkScheduler']) ## bs-uplink-scheduler-rtps.h (module 'wimax'): ns3::UplinkSchedulerRtps [class] module.add_class('UplinkSchedulerRtps', parent=root_module['ns3::UplinkScheduler']) ## bs-uplink-scheduler-simple.h (module 'wimax'): ns3::UplinkSchedulerSimple [class] module.add_class('UplinkSchedulerSimple', parent=root_module['ns3::UplinkScheduler']) ## wimax-connection.h (module 'wimax'): ns3::WimaxConnection [class] module.add_class('WimaxConnection', parent=root_module['ns3::Object']) ## wimax-mac-queue.h (module 'wimax'): ns3::WimaxMacQueue [class] module.add_class('WimaxMacQueue', parent=root_module['ns3::Object']) ## wimax-mac-to-mac-header.h (module 'wimax'): ns3::WimaxMacToMacHeader [class] module.add_class('WimaxMacToMacHeader', parent=root_module['ns3::Header']) ## wimax-phy.h (module 'wimax'): ns3::WimaxPhy [class] module.add_class('WimaxPhy', parent=root_module['ns3::Object']) ## wimax-phy.h (module 'wimax'): ns3::WimaxPhy::ModulationType [enumeration] module.add_enum('ModulationType', ['MODULATION_TYPE_BPSK_12', 'MODULATION_TYPE_QPSK_12', 'MODULATION_TYPE_QPSK_34', 'MODULATION_TYPE_QAM16_12', 'MODULATION_TYPE_QAM16_34', 'MODULATION_TYPE_QAM64_23', 'MODULATION_TYPE_QAM64_34'], outer_class=root_module['ns3::WimaxPhy']) ## wimax-phy.h (module 'wimax'): ns3::WimaxPhy::PhyState [enumeration] module.add_enum('PhyState', ['PHY_STATE_IDLE', 'PHY_STATE_SCANNING', 'PHY_STATE_TX', 'PHY_STATE_RX'], outer_class=root_module['ns3::WimaxPhy']) ## wimax-phy.h (module 'wimax'): ns3::WimaxPhy::PhyType [enumeration] module.add_enum('PhyType', ['SimpleWimaxPhy', 'simpleOfdmWimaxPhy'], outer_class=root_module['ns3::WimaxPhy']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## bs-scheduler.h (module 'wimax'): ns3::BSScheduler [class] module.add_class('BSScheduler', parent=root_module['ns3::Object']) ## bs-scheduler-rtps.h (module 'wimax'): ns3::BSSchedulerRtps [class] module.add_class('BSSchedulerRtps', parent=root_module['ns3::BSScheduler']) ## bs-scheduler-simple.h (module 'wimax'): ns3::BSSchedulerSimple [class] module.add_class('BSSchedulerSimple', parent=root_module['ns3::BSScheduler']) ## wimax-mac-header.h (module 'wimax'): ns3::BandwidthRequestHeader [class] module.add_class('BandwidthRequestHeader', parent=root_module['ns3::Header']) ## wimax-mac-header.h (module 'wimax'): ns3::BandwidthRequestHeader::HeaderType [enumeration] module.add_enum('HeaderType', ['HEADER_TYPE_INCREMENTAL', 'HEADER_TYPE_AGGREGATE'], outer_class=root_module['ns3::BandwidthRequestHeader']) ## bs-service-flow-manager.h (module 'wimax'): ns3::BsServiceFlowManager [class] module.add_class('BsServiceFlowManager', parent=root_module['ns3::ServiceFlowManager']) ## bs-service-flow-manager.h (module 'wimax'): ns3::BsServiceFlowManager::ConfirmationCode [enumeration] module.add_enum('ConfirmationCode', ['CONFIRMATION_CODE_SUCCESS', 'CONFIRMATION_CODE_REJECT'], outer_class=root_module['ns3::BsServiceFlowManager']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## connection-manager.h (module 'wimax'): ns3::ConnectionManager [class] module.add_class('ConnectionManager', parent=root_module['ns3::Object']) ## dl-mac-messages.h (module 'wimax'): ns3::Dcd [class] module.add_class('Dcd', parent=root_module['ns3::Header']) ## dl-mac-messages.h (module 'wimax'): ns3::DlMap [class] module.add_class('DlMap', parent=root_module['ns3::Header']) ## mac-messages.h (module 'wimax'): ns3::DsaAck [class] module.add_class('DsaAck', parent=root_module['ns3::Header']) ## mac-messages.h (module 'wimax'): ns3::DsaReq [class] module.add_class('DsaReq', parent=root_module['ns3::Header']) ## mac-messages.h (module 'wimax'): ns3::DsaRsp [class] module.add_class('DsaRsp', parent=root_module['ns3::Header']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## propagation-loss-model.h (module 'propagation'): ns3::FixedRssLossModel [class] module.add_class('FixedRssLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## wimax-mac-header.h (module 'wimax'): ns3::FragmentationSubheader [class] module.add_class('FragmentationSubheader', parent=root_module['ns3::Header']) ## propagation-loss-model.h (module 'propagation'): ns3::FriisPropagationLossModel [class] module.add_class('FriisPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## wimax-mac-header.h (module 'wimax'): ns3::GenericMacHeader [class] module.add_class('GenericMacHeader', parent=root_module['ns3::Header']) ## wimax-mac-header.h (module 'wimax'): ns3::GrantManagementSubheader [class] module.add_class('GrantManagementSubheader', parent=root_module['ns3::Header']) ## ipcs-classifier.h (module 'wimax'): ns3::IpcsClassifier [class] module.add_class('IpcsClassifier', 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-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## propagation-loss-model.h (module 'propagation'): ns3::LogDistancePropagationLossModel [class] module.add_class('LogDistancePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## 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']) ## propagation-loss-model.h (module 'propagation'): ns3::MatrixPropagationLossModel [class] module.add_class('MatrixPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## propagation-loss-model.h (module 'propagation'): ns3::NakagamiPropagationLossModel [class] module.add_class('NakagamiPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## random-variable.h (module 'core'): ns3::RandomVariableChecker [class] module.add_class('RandomVariableChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## random-variable.h (module 'core'): ns3::RandomVariableValue [class] module.add_class('RandomVariableValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## simple-ofdm-wimax-phy.h (module 'wimax'): ns3::SimpleOfdmWimaxPhy [class] module.add_class('SimpleOfdmWimaxPhy', parent=root_module['ns3::WimaxPhy']) ## simple-ofdm-wimax-phy.h (module 'wimax'): ns3::SimpleOfdmWimaxPhy::FrameDurationCode [enumeration] module.add_enum('FrameDurationCode', ['FRAME_DURATION_2_POINT_5_MS', 'FRAME_DURATION_4_MS', 'FRAME_DURATION_5_MS', 'FRAME_DURATION_8_MS', 'FRAME_DURATION_10_MS', 'FRAME_DURATION_12_POINT_5_MS', 'FRAME_DURATION_20_MS'], outer_class=root_module['ns3::SimpleOfdmWimaxPhy']) ## 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']) ## uinteger.h (module 'core'): ns3::UintegerValue [class] module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## wimax-channel.h (module 'wimax'): ns3::WimaxChannel [class] module.add_class('WimaxChannel', parent=root_module['ns3::Channel']) ## wimax-net-device.h (module 'wimax'): ns3::WimaxNetDevice [class] module.add_class('WimaxNetDevice', parent=root_module['ns3::NetDevice']) ## wimax-net-device.h (module 'wimax'): ns3::WimaxNetDevice::Direction [enumeration] module.add_enum('Direction', ['DIRECTION_DOWNLINK', 'DIRECTION_UPLINK'], outer_class=root_module['ns3::WimaxNetDevice']) ## wimax-net-device.h (module 'wimax'): ns3::WimaxNetDevice::RangingStatus [enumeration] module.add_enum('RangingStatus', ['RANGING_STATUS_EXPIRED', 'RANGING_STATUS_CONTINUE', 'RANGING_STATUS_ABORT', 'RANGING_STATUS_SUCCESS'], outer_class=root_module['ns3::WimaxNetDevice']) ## 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']) ## bs-net-device.h (module 'wimax'): ns3::BaseStationNetDevice [class] module.add_class('BaseStationNetDevice', parent=root_module['ns3::WimaxNetDevice']) ## bs-net-device.h (module 'wimax'): ns3::BaseStationNetDevice::State [enumeration] module.add_enum('State', ['BS_STATE_DL_SUB_FRAME', 'BS_STATE_UL_SUB_FRAME', 'BS_STATE_TTG', 'BS_STATE_RTG'], outer_class=root_module['ns3::BaseStationNetDevice']) ## bs-net-device.h (module 'wimax'): ns3::BaseStationNetDevice::MacPreamble [enumeration] module.add_enum('MacPreamble', ['SHORT_PREAMBLE', 'LONG_PREAMBLE'], outer_class=root_module['ns3::BaseStationNetDevice']) ## simple-ofdm-wimax-channel.h (module 'wimax'): ns3::SimpleOfdmWimaxChannel [class] module.add_class('SimpleOfdmWimaxChannel', parent=root_module['ns3::WimaxChannel']) ## simple-ofdm-wimax-channel.h (module 'wimax'): ns3::SimpleOfdmWimaxChannel::PropModel [enumeration] module.add_enum('PropModel', ['RANDOM_PROPAGATION', 'FRIIS_PROPAGATION', 'LOG_DISTANCE_PROPAGATION', 'COST231_PROPAGATION'], outer_class=root_module['ns3::SimpleOfdmWimaxChannel']) ## ss-net-device.h (module 'wimax'): ns3::SubscriberStationNetDevice [class] module.add_class('SubscriberStationNetDevice', parent=root_module['ns3::WimaxNetDevice']) ## ss-net-device.h (module 'wimax'): ns3::SubscriberStationNetDevice::State [enumeration] module.add_enum('State', ['SS_STATE_IDLE', 'SS_STATE_SCANNING', 'SS_STATE_SYNCHRONIZING', 'SS_STATE_ACQUIRING_PARAMETERS', 'SS_STATE_WAITING_REG_RANG_INTRVL', 'SS_STATE_WAITING_INV_RANG_INTRVL', 'SS_STATE_WAITING_RNG_RSP', 'SS_STATE_ADJUSTING_PARAMETERS', 'SS_STATE_REGISTERED', 'SS_STATE_TRANSMITTING', 'SS_STATE_STOPPED'], outer_class=root_module['ns3::SubscriberStationNetDevice']) ## ss-net-device.h (module 'wimax'): ns3::SubscriberStationNetDevice::EventType [enumeration] module.add_enum('EventType', ['EVENT_NONE', 'EVENT_WAIT_FOR_RNG_RSP', 'EVENT_DL_MAP_SYNC_TIMEOUT', 'EVENT_LOST_DL_MAP', 'EVENT_LOST_UL_MAP', 'EVENT_DCD_WAIT_TIMEOUT', 'EVENT_UCD_WAIT_TIMEOUT', 'EVENT_RANG_OPP_WAIT_TIMEOUT'], outer_class=root_module['ns3::SubscriberStationNetDevice']) module.add_container('std::vector< ns3::ServiceFlow * >', 'ns3::ServiceFlow *', container_type='vector') module.add_container('std::vector< bool >', 'bool', container_type='vector') module.add_container('ns3::bvec', 'bool', container_type='vector') module.add_container('std::vector< ns3::DlFramePrefixIe >', 'ns3::DlFramePrefixIe', container_type='vector') module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type='list') module.add_container('std::vector< ns3::SSRecord * >', 'ns3::SSRecord *', container_type='vector') module.add_container('std::vector< ns3::OfdmUlBurstProfile >', 'ns3::OfdmUlBurstProfile', container_type='vector') module.add_container('std::list< ns3::OfdmUlMapIe >', 'ns3::OfdmUlMapIe', container_type='list') module.add_container('std::list< ns3::Ptr< ns3::UlJob > >', 'ns3::Ptr< ns3::UlJob >', container_type='list') module.add_container('std::list< ns3::Ptr< ns3::Packet const > >', 'ns3::Ptr< ns3::Packet const >', container_type='list') module.add_container('std::deque< ns3::WimaxMacQueue::QueueElement >', 'ns3::WimaxMacQueue::QueueElement', container_type='dequeue') module.add_container('std::list< std::pair< ns3::OfdmDlMapIe *, ns3::Ptr< ns3::PacketBurst > > >', 'std::pair< ns3::OfdmDlMapIe *, ns3::Ptr< ns3::PacketBurst > >', container_type='list') module.add_container('std::vector< ns3::Ptr< ns3::WimaxConnection > >', 'ns3::Ptr< ns3::WimaxConnection >', container_type='vector') module.add_container('std::vector< ns3::OfdmDlBurstProfile >', 'ns3::OfdmDlBurstProfile', container_type='vector') module.add_container('std::list< ns3::OfdmDlMapIe >', 'ns3::OfdmDlMapIe', container_type='list') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *', 'ns3::LogNodePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) **', 'ns3::LogNodePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *&', 'ns3::LogNodePrinter&') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *', 'ns3::LogTimePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) **', 'ns3::LogTimePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *&', 'ns3::LogTimePrinter&') typehandlers.add_type_alias('std::vector< bool, std::allocator< bool > >', 'ns3::bvec') typehandlers.add_type_alias('std::vector< bool, std::allocator< bool > >*', 'ns3::bvec*') typehandlers.add_type_alias('std::vector< bool, std::allocator< bool > >&', 'ns3::bvec&') ## 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 internal nested_module = module.add_cpp_namespace('internal') register_types_ns3_internal(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_internal(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper']) register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3Cid_methods(root_module, root_module['ns3::Cid']) register_Ns3CidFactory_methods(root_module, root_module['ns3::CidFactory']) register_Ns3CsParameters_methods(root_module, root_module['ns3::CsParameters']) register_Ns3DcdChannelEncodings_methods(root_module, root_module['ns3::DcdChannelEncodings']) register_Ns3DlFramePrefixIe_methods(root_module, root_module['ns3::DlFramePrefixIe']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3IpcsClassifierRecord_methods(root_module, root_module['ns3::IpcsClassifierRecord']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3OfdmDcdChannelEncodings_methods(root_module, root_module['ns3::OfdmDcdChannelEncodings']) register_Ns3OfdmDlBurstProfile_methods(root_module, root_module['ns3::OfdmDlBurstProfile']) register_Ns3OfdmDlMapIe_methods(root_module, root_module['ns3::OfdmDlMapIe']) register_Ns3OfdmUlBurstProfile_methods(root_module, root_module['ns3::OfdmUlBurstProfile']) register_Ns3OfdmUlMapIe_methods(root_module, root_module['ns3::OfdmUlMapIe']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile']) register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper']) register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice']) register_Ns3RandomVariable_methods(root_module, root_module['ns3::RandomVariable']) register_Ns3SNRToBlockErrorRateManager_methods(root_module, root_module['ns3::SNRToBlockErrorRateManager']) register_Ns3SNRToBlockErrorRateRecord_methods(root_module, root_module['ns3::SNRToBlockErrorRateRecord']) register_Ns3SSRecord_methods(root_module, root_module['ns3::SSRecord']) register_Ns3SeedManager_methods(root_module, root_module['ns3::SeedManager']) register_Ns3SendParams_methods(root_module, root_module['ns3::SendParams']) register_Ns3SequentialVariable_methods(root_module, root_module['ns3::SequentialVariable']) register_Ns3ServiceFlow_methods(root_module, root_module['ns3::ServiceFlow']) register_Ns3ServiceFlowRecord_methods(root_module, root_module['ns3::ServiceFlowRecord']) 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_Ns3TlvValue_methods(root_module, root_module['ns3::TlvValue']) register_Ns3TosTlvValue_methods(root_module, root_module['ns3::TosTlvValue']) register_Ns3TriangularVariable_methods(root_module, root_module['ns3::TriangularVariable']) 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_Ns3U16TlvValue_methods(root_module, root_module['ns3::U16TlvValue']) register_Ns3U32TlvValue_methods(root_module, root_module['ns3::U32TlvValue']) register_Ns3U8TlvValue_methods(root_module, root_module['ns3::U8TlvValue']) register_Ns3UcdChannelEncodings_methods(root_module, root_module['ns3::UcdChannelEncodings']) register_Ns3UniformVariable_methods(root_module, root_module['ns3::UniformVariable']) register_Ns3VectorTlvValue_methods(root_module, root_module['ns3::VectorTlvValue']) register_Ns3WeibullVariable_methods(root_module, root_module['ns3::WeibullVariable']) register_Ns3WimaxHelper_methods(root_module, root_module['ns3::WimaxHelper']) register_Ns3ZetaVariable_methods(root_module, root_module['ns3::ZetaVariable']) register_Ns3ZipfVariable_methods(root_module, root_module['ns3::ZipfVariable']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3SimpleOfdmSendParam_methods(root_module, root_module['ns3::simpleOfdmSendParam']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3ClassificationRuleVectorTlvValue_methods(root_module, root_module['ns3::ClassificationRuleVectorTlvValue']) register_Ns3ConstantVariable_methods(root_module, root_module['ns3::ConstantVariable']) register_Ns3CsParamVectorTlvValue_methods(root_module, root_module['ns3::CsParamVectorTlvValue']) register_Ns3DeterministicVariable_methods(root_module, root_module['ns3::DeterministicVariable']) register_Ns3EmpiricalVariable_methods(root_module, root_module['ns3::EmpiricalVariable']) register_Ns3ErlangVariable_methods(root_module, root_module['ns3::ErlangVariable']) register_Ns3ExponentialVariable_methods(root_module, root_module['ns3::ExponentialVariable']) register_Ns3GammaVariable_methods(root_module, root_module['ns3::GammaVariable']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3IntEmpiricalVariable_methods(root_module, root_module['ns3::IntEmpiricalVariable']) register_Ns3Ipv4AddressTlvValue_methods(root_module, root_module['ns3::Ipv4AddressTlvValue']) register_Ns3Ipv4AddressTlvValueIpv4Addr_methods(root_module, root_module['ns3::Ipv4AddressTlvValue::ipv4Addr']) register_Ns3LogNormalVariable_methods(root_module, root_module['ns3::LogNormalVariable']) register_Ns3MacHeaderType_methods(root_module, root_module['ns3::MacHeaderType']) register_Ns3ManagementMessageType_methods(root_module, root_module['ns3::ManagementMessageType']) register_Ns3NormalVariable_methods(root_module, root_module['ns3::NormalVariable']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3OfdmDownlinkFramePrefix_methods(root_module, root_module['ns3::OfdmDownlinkFramePrefix']) register_Ns3OfdmSendParams_methods(root_module, root_module['ns3::OfdmSendParams']) register_Ns3OfdmUcdChannelEncodings_methods(root_module, root_module['ns3::OfdmUcdChannelEncodings']) register_Ns3PacketBurst_methods(root_module, root_module['ns3::PacketBurst']) register_Ns3ParetoVariable_methods(root_module, root_module['ns3::ParetoVariable']) register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper']) register_Ns3PortRangeTlvValue_methods(root_module, root_module['ns3::PortRangeTlvValue']) register_Ns3PortRangeTlvValuePortRange_methods(root_module, root_module['ns3::PortRangeTlvValue::PortRange']) register_Ns3PriorityUlJob_methods(root_module, root_module['ns3::PriorityUlJob']) register_Ns3PropagationLossModel_methods(root_module, root_module['ns3::PropagationLossModel']) register_Ns3ProtocolTlvValue_methods(root_module, root_module['ns3::ProtocolTlvValue']) register_Ns3RandomPropagationLossModel_methods(root_module, root_module['ns3::RandomPropagationLossModel']) register_Ns3RangePropagationLossModel_methods(root_module, root_module['ns3::RangePropagationLossModel']) register_Ns3RngReq_methods(root_module, root_module['ns3::RngReq']) register_Ns3RngRsp_methods(root_module, root_module['ns3::RngRsp']) register_Ns3SSManager_methods(root_module, root_module['ns3::SSManager']) register_Ns3ServiceFlowManager_methods(root_module, root_module['ns3::ServiceFlowManager']) register_Ns3SfVectorTlvValue_methods(root_module, root_module['ns3::SfVectorTlvValue']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3SsServiceFlowManager_methods(root_module, root_module['ns3::SsServiceFlowManager']) register_Ns3ThreeLogDistancePropagationLossModel_methods(root_module, root_module['ns3::ThreeLogDistancePropagationLossModel']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3Tlv_methods(root_module, root_module['ns3::Tlv']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3TwoRayGroundPropagationLossModel_methods(root_module, root_module['ns3::TwoRayGroundPropagationLossModel']) register_Ns3Ucd_methods(root_module, root_module['ns3::Ucd']) register_Ns3UlJob_methods(root_module, root_module['ns3::UlJob']) register_Ns3UlMap_methods(root_module, root_module['ns3::UlMap']) register_Ns3UplinkScheduler_methods(root_module, root_module['ns3::UplinkScheduler']) register_Ns3UplinkSchedulerMBQoS_methods(root_module, root_module['ns3::UplinkSchedulerMBQoS']) register_Ns3UplinkSchedulerRtps_methods(root_module, root_module['ns3::UplinkSchedulerRtps']) register_Ns3UplinkSchedulerSimple_methods(root_module, root_module['ns3::UplinkSchedulerSimple']) register_Ns3WimaxConnection_methods(root_module, root_module['ns3::WimaxConnection']) register_Ns3WimaxMacQueue_methods(root_module, root_module['ns3::WimaxMacQueue']) register_Ns3WimaxMacToMacHeader_methods(root_module, root_module['ns3::WimaxMacToMacHeader']) register_Ns3WimaxPhy_methods(root_module, root_module['ns3::WimaxPhy']) 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_Ns3BSScheduler_methods(root_module, root_module['ns3::BSScheduler']) register_Ns3BSSchedulerRtps_methods(root_module, root_module['ns3::BSSchedulerRtps']) register_Ns3BSSchedulerSimple_methods(root_module, root_module['ns3::BSSchedulerSimple']) register_Ns3BandwidthRequestHeader_methods(root_module, root_module['ns3::BandwidthRequestHeader']) register_Ns3BsServiceFlowManager_methods(root_module, root_module['ns3::BsServiceFlowManager']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3ConnectionManager_methods(root_module, root_module['ns3::ConnectionManager']) register_Ns3Dcd_methods(root_module, root_module['ns3::Dcd']) register_Ns3DlMap_methods(root_module, root_module['ns3::DlMap']) register_Ns3DsaAck_methods(root_module, root_module['ns3::DsaAck']) register_Ns3DsaReq_methods(root_module, root_module['ns3::DsaReq']) register_Ns3DsaRsp_methods(root_module, root_module['ns3::DsaRsp']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3FixedRssLossModel_methods(root_module, root_module['ns3::FixedRssLossModel']) register_Ns3FragmentationSubheader_methods(root_module, root_module['ns3::FragmentationSubheader']) register_Ns3FriisPropagationLossModel_methods(root_module, root_module['ns3::FriisPropagationLossModel']) register_Ns3GenericMacHeader_methods(root_module, root_module['ns3::GenericMacHeader']) register_Ns3GrantManagementSubheader_methods(root_module, root_module['ns3::GrantManagementSubheader']) register_Ns3IpcsClassifier_methods(root_module, root_module['ns3::IpcsClassifier']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3LogDistancePropagationLossModel_methods(root_module, root_module['ns3::LogDistancePropagationLossModel']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3MatrixPropagationLossModel_methods(root_module, root_module['ns3::MatrixPropagationLossModel']) register_Ns3NakagamiPropagationLossModel_methods(root_module, root_module['ns3::NakagamiPropagationLossModel']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3RandomVariableChecker_methods(root_module, root_module['ns3::RandomVariableChecker']) register_Ns3RandomVariableValue_methods(root_module, root_module['ns3::RandomVariableValue']) register_Ns3SimpleOfdmWimaxPhy_methods(root_module, root_module['ns3::SimpleOfdmWimaxPhy']) 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_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue']) register_Ns3WimaxChannel_methods(root_module, root_module['ns3::WimaxChannel']) register_Ns3WimaxNetDevice_methods(root_module, root_module['ns3::WimaxNetDevice']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3BaseStationNetDevice_methods(root_module, root_module['ns3::BaseStationNetDevice']) register_Ns3SimpleOfdmWimaxChannel_methods(root_module, root_module['ns3::SimpleOfdmWimaxChannel']) register_Ns3SubscriberStationNetDevice_methods(root_module, root_module['ns3::SubscriberStationNetDevice']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AsciiTraceHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::_Ios_Openmode filemode=std::ios_base::out) [member function] cls.add_method('CreateFileStream', 'ns3::Ptr< ns3::OutputStreamWrapper >', [param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode', default_value='std::ios_base::out')]) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3AsciiTraceHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice(ns3::AsciiTraceHelperForDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::NetDevice> nd) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::NetDevice >', 'nd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, std::string ndName, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ndName) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ndName')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t deviceid) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(std::string prefix) [member function] cls.add_method('EnableAsciiAll', 'void', [param('std::string', 'prefix')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiAll', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function] cls.add_method('EnableAsciiInternal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3Cid_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## cid.h (module 'wimax'): ns3::Cid::Cid(ns3::Cid const & arg0) [copy constructor] cls.add_constructor([param('ns3::Cid const &', 'arg0')]) ## cid.h (module 'wimax'): ns3::Cid::Cid() [constructor] cls.add_constructor([]) ## cid.h (module 'wimax'): ns3::Cid::Cid(uint16_t cid) [constructor] cls.add_constructor([param('uint16_t', 'cid')]) ## cid.h (module 'wimax'): static ns3::Cid ns3::Cid::Broadcast() [member function] cls.add_method('Broadcast', 'ns3::Cid', [], is_static=True) ## cid.h (module 'wimax'): uint16_t ns3::Cid::GetIdentifier() const [member function] cls.add_method('GetIdentifier', 'uint16_t', [], is_const=True) ## cid.h (module 'wimax'): static ns3::Cid ns3::Cid::InitialRanging() [member function] cls.add_method('InitialRanging', 'ns3::Cid', [], is_static=True) ## cid.h (module 'wimax'): bool ns3::Cid::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## cid.h (module 'wimax'): bool ns3::Cid::IsInitialRanging() const [member function] cls.add_method('IsInitialRanging', 'bool', [], is_const=True) ## cid.h (module 'wimax'): bool ns3::Cid::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## cid.h (module 'wimax'): bool ns3::Cid::IsPadding() const [member function] cls.add_method('IsPadding', 'bool', [], is_const=True) ## cid.h (module 'wimax'): static ns3::Cid ns3::Cid::Padding() [member function] cls.add_method('Padding', 'ns3::Cid', [], is_static=True) return def register_Ns3CidFactory_methods(root_module, cls): ## cid-factory.h (module 'wimax'): ns3::CidFactory::CidFactory(ns3::CidFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::CidFactory const &', 'arg0')]) ## cid-factory.h (module 'wimax'): ns3::CidFactory::CidFactory() [constructor] cls.add_constructor([]) ## cid-factory.h (module 'wimax'): ns3::Cid ns3::CidFactory::Allocate(ns3::Cid::Type type) [member function] cls.add_method('Allocate', 'ns3::Cid', [param('ns3::Cid::Type', 'type')]) ## cid-factory.h (module 'wimax'): ns3::Cid ns3::CidFactory::AllocateBasic() [member function] cls.add_method('AllocateBasic', 'ns3::Cid', []) ## cid-factory.h (module 'wimax'): ns3::Cid ns3::CidFactory::AllocateMulticast() [member function] cls.add_method('AllocateMulticast', 'ns3::Cid', []) ## cid-factory.h (module 'wimax'): ns3::Cid ns3::CidFactory::AllocatePrimary() [member function] cls.add_method('AllocatePrimary', 'ns3::Cid', []) ## cid-factory.h (module 'wimax'): ns3::Cid ns3::CidFactory::AllocateTransportOrSecondary() [member function] cls.add_method('AllocateTransportOrSecondary', 'ns3::Cid', []) ## cid-factory.h (module 'wimax'): void ns3::CidFactory::FreeCid(ns3::Cid cid) [member function] cls.add_method('FreeCid', 'void', [param('ns3::Cid', 'cid')]) ## cid-factory.h (module 'wimax'): bool ns3::CidFactory::IsBasic(ns3::Cid cid) const [member function] cls.add_method('IsBasic', 'bool', [param('ns3::Cid', 'cid')], is_const=True) ## cid-factory.h (module 'wimax'): bool ns3::CidFactory::IsPrimary(ns3::Cid cid) const [member function] cls.add_method('IsPrimary', 'bool', [param('ns3::Cid', 'cid')], is_const=True) ## cid-factory.h (module 'wimax'): bool ns3::CidFactory::IsTransport(ns3::Cid cid) const [member function] cls.add_method('IsTransport', 'bool', [param('ns3::Cid', 'cid')], is_const=True) return def register_Ns3CsParameters_methods(root_module, cls): ## cs-parameters.h (module 'wimax'): ns3::CsParameters::CsParameters(ns3::CsParameters const & arg0) [copy constructor] cls.add_constructor([param('ns3::CsParameters const &', 'arg0')]) ## cs-parameters.h (module 'wimax'): ns3::CsParameters::CsParameters() [constructor] cls.add_constructor([]) ## cs-parameters.h (module 'wimax'): ns3::CsParameters::CsParameters(ns3::Tlv tlv) [constructor] cls.add_constructor([param('ns3::Tlv', 'tlv')]) ## cs-parameters.h (module 'wimax'): ns3::CsParameters::CsParameters(ns3::CsParameters::Action classifierDscAction, ns3::IpcsClassifierRecord classifier) [constructor] cls.add_constructor([param('ns3::CsParameters::Action', 'classifierDscAction'), param('ns3::IpcsClassifierRecord', 'classifier')]) ## cs-parameters.h (module 'wimax'): ns3::CsParameters::Action ns3::CsParameters::GetClassifierDscAction() const [member function] cls.add_method('GetClassifierDscAction', 'ns3::CsParameters::Action', [], is_const=True) ## cs-parameters.h (module 'wimax'): ns3::IpcsClassifierRecord ns3::CsParameters::GetPacketClassifierRule() const [member function] cls.add_method('GetPacketClassifierRule', 'ns3::IpcsClassifierRecord', [], is_const=True) ## cs-parameters.h (module 'wimax'): void ns3::CsParameters::SetClassifierDscAction(ns3::CsParameters::Action action) [member function] cls.add_method('SetClassifierDscAction', 'void', [param('ns3::CsParameters::Action', 'action')]) ## cs-parameters.h (module 'wimax'): void ns3::CsParameters::SetPacketClassifierRule(ns3::IpcsClassifierRecord packetClassifierRule) [member function] cls.add_method('SetPacketClassifierRule', 'void', [param('ns3::IpcsClassifierRecord', 'packetClassifierRule')]) ## cs-parameters.h (module 'wimax'): ns3::Tlv ns3::CsParameters::ToTlv() const [member function] cls.add_method('ToTlv', 'ns3::Tlv', [], is_const=True) return def register_Ns3DcdChannelEncodings_methods(root_module, cls): ## dl-mac-messages.h (module 'wimax'): ns3::DcdChannelEncodings::DcdChannelEncodings(ns3::DcdChannelEncodings const & arg0) [copy constructor] cls.add_constructor([param('ns3::DcdChannelEncodings const &', 'arg0')]) ## dl-mac-messages.h (module 'wimax'): ns3::DcdChannelEncodings::DcdChannelEncodings() [constructor] cls.add_constructor([]) ## dl-mac-messages.h (module 'wimax'): uint16_t ns3::DcdChannelEncodings::GetBsEirp() const [member function] cls.add_method('GetBsEirp', 'uint16_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint16_t ns3::DcdChannelEncodings::GetEirxPIrMax() const [member function] cls.add_method('GetEirxPIrMax', 'uint16_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint32_t ns3::DcdChannelEncodings::GetFrequency() const [member function] cls.add_method('GetFrequency', 'uint32_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint16_t ns3::DcdChannelEncodings::GetSize() const [member function] cls.add_method('GetSize', 'uint16_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::DcdChannelEncodings::Read(ns3::Buffer::Iterator start) [member function] cls.add_method('Read', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')]) ## dl-mac-messages.h (module 'wimax'): void ns3::DcdChannelEncodings::SetBsEirp(uint16_t bs_eirp) [member function] cls.add_method('SetBsEirp', 'void', [param('uint16_t', 'bs_eirp')]) ## dl-mac-messages.h (module 'wimax'): void ns3::DcdChannelEncodings::SetEirxPIrMax(uint16_t rss_ir_max) [member function] cls.add_method('SetEirxPIrMax', 'void', [param('uint16_t', 'rss_ir_max')]) ## dl-mac-messages.h (module 'wimax'): void ns3::DcdChannelEncodings::SetFrequency(uint32_t frequency) [member function] cls.add_method('SetFrequency', 'void', [param('uint32_t', 'frequency')]) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::DcdChannelEncodings::Write(ns3::Buffer::Iterator start) const [member function] cls.add_method('Write', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::DcdChannelEncodings::DoRead(ns3::Buffer::Iterator start) [member function] cls.add_method('DoRead', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, visibility='private', is_virtual=True) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::DcdChannelEncodings::DoWrite(ns3::Buffer::Iterator start) const [member function] cls.add_method('DoWrite', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3DlFramePrefixIe_methods(root_module, cls): ## ofdm-downlink-frame-prefix.h (module 'wimax'): ns3::DlFramePrefixIe::DlFramePrefixIe(ns3::DlFramePrefixIe const & arg0) [copy constructor] cls.add_constructor([param('ns3::DlFramePrefixIe const &', 'arg0')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): ns3::DlFramePrefixIe::DlFramePrefixIe() [constructor] cls.add_constructor([]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint8_t ns3::DlFramePrefixIe::GetDiuc() const [member function] cls.add_method('GetDiuc', 'uint8_t', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint16_t ns3::DlFramePrefixIe::GetLength() const [member function] cls.add_method('GetLength', 'uint16_t', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint8_t ns3::DlFramePrefixIe::GetPreamblePresent() const [member function] cls.add_method('GetPreamblePresent', 'uint8_t', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint8_t ns3::DlFramePrefixIe::GetRateId() const [member function] cls.add_method('GetRateId', 'uint8_t', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint16_t ns3::DlFramePrefixIe::GetSize() const [member function] cls.add_method('GetSize', 'uint16_t', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint16_t ns3::DlFramePrefixIe::GetStartTime() const [member function] cls.add_method('GetStartTime', 'uint16_t', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): ns3::Buffer::Iterator ns3::DlFramePrefixIe::Read(ns3::Buffer::Iterator start) [member function] cls.add_method('Read', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::DlFramePrefixIe::SetDiuc(uint8_t diuc) [member function] cls.add_method('SetDiuc', 'void', [param('uint8_t', 'diuc')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::DlFramePrefixIe::SetLength(uint16_t length) [member function] cls.add_method('SetLength', 'void', [param('uint16_t', 'length')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::DlFramePrefixIe::SetPreamblePresent(uint8_t preamblePresent) [member function] cls.add_method('SetPreamblePresent', 'void', [param('uint8_t', 'preamblePresent')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::DlFramePrefixIe::SetRateId(uint8_t rateId) [member function] cls.add_method('SetRateId', 'void', [param('uint8_t', 'rateId')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::DlFramePrefixIe::SetStartTime(uint16_t startTime) [member function] cls.add_method('SetStartTime', 'void', [param('uint16_t', 'startTime')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): ns3::Buffer::Iterator ns3::DlFramePrefixIe::Write(ns3::Buffer::Iterator start) const [member function] cls.add_method('Write', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3IpcsClassifierRecord_methods(root_module, cls): ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord::IpcsClassifierRecord(ns3::IpcsClassifierRecord const & arg0) [copy constructor] cls.add_constructor([param('ns3::IpcsClassifierRecord const &', 'arg0')]) ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord::IpcsClassifierRecord() [constructor] cls.add_constructor([]) ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord::IpcsClassifierRecord(ns3::Ipv4Address srcAddress, ns3::Ipv4Mask srcMask, ns3::Ipv4Address dstAddress, ns3::Ipv4Mask dstMask, uint16_t srcPortLow, uint16_t srcPortHigh, uint16_t dstPortLow, uint16_t dstPortHigh, uint8_t protocol, uint8_t priority) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'srcAddress'), param('ns3::Ipv4Mask', 'srcMask'), param('ns3::Ipv4Address', 'dstAddress'), param('ns3::Ipv4Mask', 'dstMask'), param('uint16_t', 'srcPortLow'), param('uint16_t', 'srcPortHigh'), param('uint16_t', 'dstPortLow'), param('uint16_t', 'dstPortHigh'), param('uint8_t', 'protocol'), param('uint8_t', 'priority')]) ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord::IpcsClassifierRecord(ns3::Tlv tlv) [constructor] cls.add_constructor([param('ns3::Tlv', 'tlv')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddDstAddr(ns3::Ipv4Address dstAddress, ns3::Ipv4Mask dstMask) [member function] cls.add_method('AddDstAddr', 'void', [param('ns3::Ipv4Address', 'dstAddress'), param('ns3::Ipv4Mask', 'dstMask')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddDstPortRange(uint16_t dstPortLow, uint16_t dstPortHigh) [member function] cls.add_method('AddDstPortRange', 'void', [param('uint16_t', 'dstPortLow'), param('uint16_t', 'dstPortHigh')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddProtocol(uint8_t proto) [member function] cls.add_method('AddProtocol', 'void', [param('uint8_t', 'proto')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddSrcAddr(ns3::Ipv4Address srcAddress, ns3::Ipv4Mask srcMask) [member function] cls.add_method('AddSrcAddr', 'void', [param('ns3::Ipv4Address', 'srcAddress'), param('ns3::Ipv4Mask', 'srcMask')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddSrcPortRange(uint16_t srcPortLow, uint16_t srcPortHigh) [member function] cls.add_method('AddSrcPortRange', 'void', [param('uint16_t', 'srcPortLow'), param('uint16_t', 'srcPortHigh')]) ## ipcs-classifier-record.h (module 'wimax'): bool ns3::IpcsClassifierRecord::CheckMatch(ns3::Ipv4Address srcAddress, ns3::Ipv4Address dstAddress, uint16_t srcPort, uint16_t dstPort, uint8_t proto) const [member function] cls.add_method('CheckMatch', 'bool', [param('ns3::Ipv4Address', 'srcAddress'), param('ns3::Ipv4Address', 'dstAddress'), param('uint16_t', 'srcPort'), param('uint16_t', 'dstPort'), param('uint8_t', 'proto')], is_const=True) ## ipcs-classifier-record.h (module 'wimax'): uint16_t ns3::IpcsClassifierRecord::GetCid() const [member function] cls.add_method('GetCid', 'uint16_t', [], is_const=True) ## ipcs-classifier-record.h (module 'wimax'): uint16_t ns3::IpcsClassifierRecord::GetIndex() const [member function] cls.add_method('GetIndex', 'uint16_t', [], is_const=True) ## ipcs-classifier-record.h (module 'wimax'): uint8_t ns3::IpcsClassifierRecord::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::SetCid(uint16_t cid) [member function] cls.add_method('SetCid', 'void', [param('uint16_t', 'cid')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::SetIndex(uint16_t index) [member function] cls.add_method('SetIndex', 'void', [param('uint16_t', 'index')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::SetPriority(uint8_t prio) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'prio')]) ## ipcs-classifier-record.h (module 'wimax'): ns3::Tlv ns3::IpcsClassifierRecord::ToTlv() const [member function] cls.add_method('ToTlv', 'ns3::Tlv', [], is_const=True) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): 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::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', '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::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3LogComponent_methods(root_module, cls): ## log.h (module 'core'): ns3::LogComponent::LogComponent(ns3::LogComponent const & arg0) [copy constructor] cls.add_constructor([param('ns3::LogComponent const &', 'arg0')]) ## log.h (module 'core'): ns3::LogComponent::LogComponent(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## log.h (module 'core'): void ns3::LogComponent::Disable(ns3::LogLevel level) [member function] cls.add_method('Disable', 'void', [param('ns3::LogLevel', 'level')]) ## log.h (module 'core'): void ns3::LogComponent::Enable(ns3::LogLevel level) [member function] cls.add_method('Enable', 'void', [param('ns3::LogLevel', 'level')]) ## log.h (module 'core'): void ns3::LogComponent::EnvVarCheck(char const * name) [member function] cls.add_method('EnvVarCheck', 'void', [param('char const *', 'name')]) ## log.h (module 'core'): bool ns3::LogComponent::IsEnabled(ns3::LogLevel level) const [member function] cls.add_method('IsEnabled', 'bool', [param('ns3::LogLevel', 'level')], is_const=True) ## log.h (module 'core'): bool ns3::LogComponent::IsNoneEnabled() const [member function] cls.add_method('IsNoneEnabled', 'bool', [], is_const=True) ## log.h (module 'core'): char const * ns3::LogComponent::Name() const [member function] cls.add_method('Name', 'char const *', [], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3OfdmDcdChannelEncodings_methods(root_module, cls): ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDcdChannelEncodings::OfdmDcdChannelEncodings(ns3::OfdmDcdChannelEncodings const & arg0) [copy constructor] cls.add_constructor([param('ns3::OfdmDcdChannelEncodings const &', 'arg0')]) ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDcdChannelEncodings::OfdmDcdChannelEncodings() [constructor] cls.add_constructor([]) ## dl-mac-messages.h (module 'wimax'): ns3::Mac48Address ns3::OfdmDcdChannelEncodings::GetBaseStationId() const [member function] cls.add_method('GetBaseStationId', 'ns3::Mac48Address', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDcdChannelEncodings::GetChannelNr() const [member function] cls.add_method('GetChannelNr', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDcdChannelEncodings::GetFrameDurationCode() const [member function] cls.add_method('GetFrameDurationCode', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint32_t ns3::OfdmDcdChannelEncodings::GetFrameNumber() const [member function] cls.add_method('GetFrameNumber', 'uint32_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDcdChannelEncodings::GetRtg() const [member function] cls.add_method('GetRtg', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint16_t ns3::OfdmDcdChannelEncodings::GetSize() const [member function] cls.add_method('GetSize', 'uint16_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDcdChannelEncodings::GetTtg() const [member function] cls.add_method('GetTtg', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDcdChannelEncodings::SetBaseStationId(ns3::Mac48Address baseStationId) [member function] cls.add_method('SetBaseStationId', 'void', [param('ns3::Mac48Address', 'baseStationId')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDcdChannelEncodings::SetChannelNr(uint8_t channelNr) [member function] cls.add_method('SetChannelNr', 'void', [param('uint8_t', 'channelNr')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDcdChannelEncodings::SetFrameDurationCode(uint8_t frameDurationCode) [member function] cls.add_method('SetFrameDurationCode', 'void', [param('uint8_t', 'frameDurationCode')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDcdChannelEncodings::SetFrameNumber(uint32_t frameNumber) [member function] cls.add_method('SetFrameNumber', 'void', [param('uint32_t', 'frameNumber')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDcdChannelEncodings::SetRtg(uint8_t rtg) [member function] cls.add_method('SetRtg', 'void', [param('uint8_t', 'rtg')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDcdChannelEncodings::SetTtg(uint8_t ttg) [member function] cls.add_method('SetTtg', 'void', [param('uint8_t', 'ttg')]) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmDcdChannelEncodings::DoRead(ns3::Buffer::Iterator start) [member function] cls.add_method('DoRead', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], visibility='private', is_virtual=True) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmDcdChannelEncodings::DoWrite(ns3::Buffer::Iterator start) const [member function] cls.add_method('DoWrite', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3OfdmDlBurstProfile_methods(root_module, cls): ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDlBurstProfile::OfdmDlBurstProfile(ns3::OfdmDlBurstProfile const & arg0) [copy constructor] cls.add_constructor([param('ns3::OfdmDlBurstProfile const &', 'arg0')]) ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDlBurstProfile::OfdmDlBurstProfile() [constructor] cls.add_constructor([]) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDlBurstProfile::GetDiuc() const [member function] cls.add_method('GetDiuc', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDlBurstProfile::GetFecCodeType() const [member function] cls.add_method('GetFecCodeType', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDlBurstProfile::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint16_t ns3::OfdmDlBurstProfile::GetSize() const [member function] cls.add_method('GetSize', 'uint16_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDlBurstProfile::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmDlBurstProfile::Read(ns3::Buffer::Iterator start) [member function] cls.add_method('Read', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDlBurstProfile::SetDiuc(uint8_t diuc) [member function] cls.add_method('SetDiuc', 'void', [param('uint8_t', 'diuc')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDlBurstProfile::SetFecCodeType(uint8_t fecCodeType) [member function] cls.add_method('SetFecCodeType', 'void', [param('uint8_t', 'fecCodeType')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDlBurstProfile::SetLength(uint8_t length) [member function] cls.add_method('SetLength', 'void', [param('uint8_t', 'length')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDlBurstProfile::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmDlBurstProfile::Write(ns3::Buffer::Iterator start) const [member function] cls.add_method('Write', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True) return def register_Ns3OfdmDlMapIe_methods(root_module, cls): ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDlMapIe::OfdmDlMapIe(ns3::OfdmDlMapIe const & arg0) [copy constructor] cls.add_constructor([param('ns3::OfdmDlMapIe const &', 'arg0')]) ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDlMapIe::OfdmDlMapIe() [constructor] cls.add_constructor([]) ## dl-mac-messages.h (module 'wimax'): ns3::Cid ns3::OfdmDlMapIe::GetCid() const [member function] cls.add_method('GetCid', 'ns3::Cid', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDlMapIe::GetDiuc() const [member function] cls.add_method('GetDiuc', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmDlMapIe::GetPreamblePresent() const [member function] cls.add_method('GetPreamblePresent', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint16_t ns3::OfdmDlMapIe::GetSize() const [member function] cls.add_method('GetSize', 'uint16_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint16_t ns3::OfdmDlMapIe::GetStartTime() const [member function] cls.add_method('GetStartTime', 'uint16_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmDlMapIe::Read(ns3::Buffer::Iterator start) [member function] cls.add_method('Read', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDlMapIe::SetCid(ns3::Cid cid) [member function] cls.add_method('SetCid', 'void', [param('ns3::Cid', 'cid')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDlMapIe::SetDiuc(uint8_t diuc) [member function] cls.add_method('SetDiuc', 'void', [param('uint8_t', 'diuc')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDlMapIe::SetPreamblePresent(uint8_t preamblePresent) [member function] cls.add_method('SetPreamblePresent', 'void', [param('uint8_t', 'preamblePresent')]) ## dl-mac-messages.h (module 'wimax'): void ns3::OfdmDlMapIe::SetStartTime(uint16_t startTime) [member function] cls.add_method('SetStartTime', 'void', [param('uint16_t', 'startTime')]) ## dl-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmDlMapIe::Write(ns3::Buffer::Iterator start) const [member function] cls.add_method('Write', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True) return def register_Ns3OfdmUlBurstProfile_methods(root_module, cls): ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUlBurstProfile::OfdmUlBurstProfile(ns3::OfdmUlBurstProfile const & arg0) [copy constructor] cls.add_constructor([param('ns3::OfdmUlBurstProfile const &', 'arg0')]) ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUlBurstProfile::OfdmUlBurstProfile() [constructor] cls.add_constructor([]) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmUlBurstProfile::GetFecCodeType() const [member function] cls.add_method('GetFecCodeType', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmUlBurstProfile::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint16_t ns3::OfdmUlBurstProfile::GetSize() const [member function] cls.add_method('GetSize', 'uint16_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmUlBurstProfile::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmUlBurstProfile::GetUiuc() const [member function] cls.add_method('GetUiuc', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmUlBurstProfile::Read(ns3::Buffer::Iterator start) [member function] cls.add_method('Read', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlBurstProfile::SetFecCodeType(uint8_t fecCodeType) [member function] cls.add_method('SetFecCodeType', 'void', [param('uint8_t', 'fecCodeType')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlBurstProfile::SetLength(uint8_t length) [member function] cls.add_method('SetLength', 'void', [param('uint8_t', 'length')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlBurstProfile::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlBurstProfile::SetUiuc(uint8_t uiuc) [member function] cls.add_method('SetUiuc', 'void', [param('uint8_t', 'uiuc')]) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmUlBurstProfile::Write(ns3::Buffer::Iterator start) const [member function] cls.add_method('Write', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True) return def register_Ns3OfdmUlMapIe_methods(root_module, cls): ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUlMapIe::OfdmUlMapIe(ns3::OfdmUlMapIe const & arg0) [copy constructor] cls.add_constructor([param('ns3::OfdmUlMapIe const &', 'arg0')]) ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUlMapIe::OfdmUlMapIe() [constructor] cls.add_constructor([]) ## ul-mac-messages.h (module 'wimax'): ns3::Cid ns3::OfdmUlMapIe::GetCid() const [member function] cls.add_method('GetCid', 'ns3::Cid', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint16_t ns3::OfdmUlMapIe::GetDuration() const [member function] cls.add_method('GetDuration', 'uint16_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmUlMapIe::GetMidambleRepetitionInterval() const [member function] cls.add_method('GetMidambleRepetitionInterval', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint16_t ns3::OfdmUlMapIe::GetSize() const [member function] cls.add_method('GetSize', 'uint16_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint16_t ns3::OfdmUlMapIe::GetStartTime() const [member function] cls.add_method('GetStartTime', 'uint16_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmUlMapIe::GetSubchannelIndex() const [member function] cls.add_method('GetSubchannelIndex', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmUlMapIe::GetUiuc() const [member function] cls.add_method('GetUiuc', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmUlMapIe::Read(ns3::Buffer::Iterator start) [member function] cls.add_method('Read', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlMapIe::SetCid(ns3::Cid cid) [member function] cls.add_method('SetCid', 'void', [param('ns3::Cid', 'cid')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlMapIe::SetDuration(uint16_t duration) [member function] cls.add_method('SetDuration', 'void', [param('uint16_t', 'duration')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlMapIe::SetMidambleRepetitionInterval(uint8_t midambleRepetitionInterval) [member function] cls.add_method('SetMidambleRepetitionInterval', 'void', [param('uint8_t', 'midambleRepetitionInterval')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlMapIe::SetStartTime(uint16_t startTime) [member function] cls.add_method('SetStartTime', 'void', [param('uint16_t', 'startTime')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlMapIe::SetSubchannelIndex(uint8_t subchannelIndex) [member function] cls.add_method('SetSubchannelIndex', 'void', [param('uint8_t', 'subchannelIndex')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUlMapIe::SetUiuc(uint8_t uiuc) [member function] cls.add_method('SetUiuc', 'void', [param('uint8_t', 'uiuc')]) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmUlMapIe::Write(ns3::Buffer::Iterator start) const [member function] cls.add_method('Write', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True) 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_Ns3PcapFile_methods(root_module, cls): ## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor] cls.add_constructor([]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT) [member function] cls.add_method('Diff', 'bool', [param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint32_t &', 'sec'), param('uint32_t &', 'usec'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT')], is_static=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file.h (module 'network'): bool ns3::PcapFile::GetSwapMode() [member function] cls.add_method('GetSwapMode', 'bool', []) ## pcap-file.h (module 'network'): int32_t ns3::PcapFile::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Init(uint32_t dataLinkType, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT, int32_t timeZoneCorrection=ns3::PcapFile::ZONE_DEFAULT, bool swapMode=false) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT'), param('int32_t', 'timeZoneCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT'), param('bool', 'swapMode', default_value='false')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Read(uint8_t * const data, uint32_t maxBytes, uint32_t & tsSec, uint32_t & tsUsec, uint32_t & inclLen, uint32_t & origLen, uint32_t & readLen) [member function] cls.add_method('Read', 'void', [param('uint8_t * const', 'data'), param('uint32_t', 'maxBytes'), param('uint32_t &', 'tsSec'), param('uint32_t &', 'tsUsec'), param('uint32_t &', 'inclLen'), param('uint32_t &', 'origLen'), param('uint32_t &', 'readLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, uint8_t const * const data, uint32_t totalLen) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('uint8_t const * const', 'data'), param('uint32_t', 'totalLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Header & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): ns3::PcapFile::SNAPLEN_DEFAULT [variable] cls.add_static_attribute('SNAPLEN_DEFAULT', 'uint32_t const', is_const=True) ## pcap-file.h (module 'network'): ns3::PcapFile::ZONE_DEFAULT [variable] cls.add_static_attribute('ZONE_DEFAULT', 'int32_t const', is_const=True) return def register_Ns3PcapHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper(ns3::PcapHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::PcapFileWrapper> ns3::PcapHelper::CreateFile(std::string filename, std::_Ios_Openmode filemode, uint32_t dataLinkType, uint32_t snapLen=65535, int32_t tzCorrection=0) [member function] cls.add_method('CreateFile', 'ns3::Ptr< ns3::PcapFileWrapper >', [param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode'), param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='65535'), param('int32_t', 'tzCorrection', default_value='0')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3PcapHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function] cls.add_method('EnablePcapAll', 'void', [param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3RandomVariable_methods(root_module, cls): cls.add_output_stream_operator() ## random-variable.h (module 'core'): ns3::RandomVariable::RandomVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::RandomVariable::RandomVariable(ns3::RandomVariable const & o) [copy constructor] cls.add_constructor([param('ns3::RandomVariable const &', 'o')]) ## random-variable.h (module 'core'): uint32_t ns3::RandomVariable::GetInteger() const [member function] cls.add_method('GetInteger', 'uint32_t', [], is_const=True) ## random-variable.h (module 'core'): double ns3::RandomVariable::GetValue() const [member function] cls.add_method('GetValue', 'double', [], is_const=True) return def register_Ns3SNRToBlockErrorRateManager_methods(root_module, cls): ## snr-to-block-error-rate-manager.h (module 'wimax'): ns3::SNRToBlockErrorRateManager::SNRToBlockErrorRateManager(ns3::SNRToBlockErrorRateManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::SNRToBlockErrorRateManager const &', 'arg0')]) ## snr-to-block-error-rate-manager.h (module 'wimax'): ns3::SNRToBlockErrorRateManager::SNRToBlockErrorRateManager() [constructor] cls.add_constructor([]) ## snr-to-block-error-rate-manager.h (module 'wimax'): void ns3::SNRToBlockErrorRateManager::ActivateLoss(bool loss) [member function] cls.add_method('ActivateLoss', 'void', [param('bool', 'loss')]) ## snr-to-block-error-rate-manager.h (module 'wimax'): double ns3::SNRToBlockErrorRateManager::GetBlockErrorRate(double SNR, uint8_t modulation) [member function] cls.add_method('GetBlockErrorRate', 'double', [param('double', 'SNR'), param('uint8_t', 'modulation')]) ## snr-to-block-error-rate-manager.h (module 'wimax'): ns3::SNRToBlockErrorRateRecord * ns3::SNRToBlockErrorRateManager::GetSNRToBlockErrorRateRecord(double SNR, uint8_t modulation) [member function] cls.add_method('GetSNRToBlockErrorRateRecord', 'ns3::SNRToBlockErrorRateRecord *', [param('double', 'SNR'), param('uint8_t', 'modulation')]) ## snr-to-block-error-rate-manager.h (module 'wimax'): std::string ns3::SNRToBlockErrorRateManager::GetTraceFilePath() [member function] cls.add_method('GetTraceFilePath', 'std::string', []) ## snr-to-block-error-rate-manager.h (module 'wimax'): void ns3::SNRToBlockErrorRateManager::LoadDefaultTraces() [member function] cls.add_method('LoadDefaultTraces', 'void', []) ## snr-to-block-error-rate-manager.h (module 'wimax'): void ns3::SNRToBlockErrorRateManager::LoadTraces() [member function] cls.add_method('LoadTraces', 'void', []) ## snr-to-block-error-rate-manager.h (module 'wimax'): void ns3::SNRToBlockErrorRateManager::ReLoadTraces() [member function] cls.add_method('ReLoadTraces', 'void', []) ## snr-to-block-error-rate-manager.h (module 'wimax'): void ns3::SNRToBlockErrorRateManager::SetTraceFilePath(char * traceFilePath) [member function] cls.add_method('SetTraceFilePath', 'void', [param('char *', 'traceFilePath')]) return def register_Ns3SNRToBlockErrorRateRecord_methods(root_module, cls): ## snr-to-block-error-rate-record.h (module 'wimax'): ns3::SNRToBlockErrorRateRecord::SNRToBlockErrorRateRecord(ns3::SNRToBlockErrorRateRecord const & arg0) [copy constructor] cls.add_constructor([param('ns3::SNRToBlockErrorRateRecord const &', 'arg0')]) ## snr-to-block-error-rate-record.h (module 'wimax'): ns3::SNRToBlockErrorRateRecord::SNRToBlockErrorRateRecord(double snrValue, double bitErrorRate, double BlockErrorRate, double sigma2, double I1, double I2) [constructor] cls.add_constructor([param('double', 'snrValue'), param('double', 'bitErrorRate'), param('double', 'BlockErrorRate'), param('double', 'sigma2'), param('double', 'I1'), param('double', 'I2')]) ## snr-to-block-error-rate-record.h (module 'wimax'): ns3::SNRToBlockErrorRateRecord * ns3::SNRToBlockErrorRateRecord::Copy() [member function] cls.add_method('Copy', 'ns3::SNRToBlockErrorRateRecord *', []) ## snr-to-block-error-rate-record.h (module 'wimax'): double ns3::SNRToBlockErrorRateRecord::GetBitErrorRate() [member function] cls.add_method('GetBitErrorRate', 'double', []) ## snr-to-block-error-rate-record.h (module 'wimax'): double ns3::SNRToBlockErrorRateRecord::GetBlockErrorRate() [member function] cls.add_method('GetBlockErrorRate', 'double', []) ## snr-to-block-error-rate-record.h (module 'wimax'): double ns3::SNRToBlockErrorRateRecord::GetI1() [member function] cls.add_method('GetI1', 'double', []) ## snr-to-block-error-rate-record.h (module 'wimax'): double ns3::SNRToBlockErrorRateRecord::GetI2() [member function] cls.add_method('GetI2', 'double', []) ## snr-to-block-error-rate-record.h (module 'wimax'): double ns3::SNRToBlockErrorRateRecord::GetSNRValue() [member function] cls.add_method('GetSNRValue', 'double', []) ## snr-to-block-error-rate-record.h (module 'wimax'): double ns3::SNRToBlockErrorRateRecord::GetSigma2() [member function] cls.add_method('GetSigma2', 'double', []) ## snr-to-block-error-rate-record.h (module 'wimax'): void ns3::SNRToBlockErrorRateRecord::SetBitErrorRate(double arg0) [member function] cls.add_method('SetBitErrorRate', 'void', [param('double', 'arg0')]) ## snr-to-block-error-rate-record.h (module 'wimax'): void ns3::SNRToBlockErrorRateRecord::SetBlockErrorRate(double arg0) [member function] cls.add_method('SetBlockErrorRate', 'void', [param('double', 'arg0')]) ## snr-to-block-error-rate-record.h (module 'wimax'): void ns3::SNRToBlockErrorRateRecord::SetI1(double arg0) [member function] cls.add_method('SetI1', 'void', [param('double', 'arg0')]) ## snr-to-block-error-rate-record.h (module 'wimax'): void ns3::SNRToBlockErrorRateRecord::SetI2(double arg0) [member function] cls.add_method('SetI2', 'void', [param('double', 'arg0')]) ## snr-to-block-error-rate-record.h (module 'wimax'): void ns3::SNRToBlockErrorRateRecord::SetSNRValue(double arg0) [member function] cls.add_method('SetSNRValue', 'void', [param('double', 'arg0')]) return def register_Ns3SSRecord_methods(root_module, cls): ## ss-record.h (module 'wimax'): ns3::SSRecord::SSRecord(ns3::SSRecord const & arg0) [copy constructor] cls.add_constructor([param('ns3::SSRecord const &', 'arg0')]) ## ss-record.h (module 'wimax'): ns3::SSRecord::SSRecord() [constructor] cls.add_constructor([]) ## ss-record.h (module 'wimax'): ns3::SSRecord::SSRecord(ns3::Mac48Address macAddress) [constructor] cls.add_constructor([param('ns3::Mac48Address', 'macAddress')]) ## ss-record.h (module 'wimax'): ns3::SSRecord::SSRecord(ns3::Mac48Address macAddress, ns3::Ipv4Address IPaddress) [constructor] cls.add_constructor([param('ns3::Mac48Address', 'macAddress'), param('ns3::Ipv4Address', 'IPaddress')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::AddServiceFlow(ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('AddServiceFlow', 'void', [param('ns3::ServiceFlow *', 'serviceFlow')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::DisablePollForRanging() [member function] cls.add_method('DisablePollForRanging', 'void', []) ## ss-record.h (module 'wimax'): void ns3::SSRecord::EnablePollForRanging() [member function] cls.add_method('EnablePollForRanging', 'void', []) ## ss-record.h (module 'wimax'): bool ns3::SSRecord::GetAreServiceFlowsAllocated() const [member function] cls.add_method('GetAreServiceFlowsAllocated', 'bool', [], is_const=True) ## ss-record.h (module 'wimax'): ns3::Cid ns3::SSRecord::GetBasicCid() const [member function] cls.add_method('GetBasicCid', 'ns3::Cid', [], is_const=True) ## ss-record.h (module 'wimax'): ns3::DsaRsp ns3::SSRecord::GetDsaRsp() const [member function] cls.add_method('GetDsaRsp', 'ns3::DsaRsp', [], is_const=True) ## ss-record.h (module 'wimax'): uint8_t ns3::SSRecord::GetDsaRspRetries() const [member function] cls.add_method('GetDsaRspRetries', 'uint8_t', [], is_const=True) ## ss-record.h (module 'wimax'): bool ns3::SSRecord::GetHasServiceFlowBe() const [member function] cls.add_method('GetHasServiceFlowBe', 'bool', [], is_const=True) ## ss-record.h (module 'wimax'): bool ns3::SSRecord::GetHasServiceFlowNrtps() const [member function] cls.add_method('GetHasServiceFlowNrtps', 'bool', [], is_const=True) ## ss-record.h (module 'wimax'): bool ns3::SSRecord::GetHasServiceFlowRtps() const [member function] cls.add_method('GetHasServiceFlowRtps', 'bool', [], is_const=True) ## ss-record.h (module 'wimax'): bool ns3::SSRecord::GetHasServiceFlowUgs() const [member function] cls.add_method('GetHasServiceFlowUgs', 'bool', [], is_const=True) ## ss-record.h (module 'wimax'): ns3::Ipv4Address ns3::SSRecord::GetIPAddress() [member function] cls.add_method('GetIPAddress', 'ns3::Ipv4Address', []) ## ss-record.h (module 'wimax'): uint8_t ns3::SSRecord::GetInvitedRangRetries() const [member function] cls.add_method('GetInvitedRangRetries', 'uint8_t', [], is_const=True) ## ss-record.h (module 'wimax'): bool ns3::SSRecord::GetIsBroadcastSS() [member function] cls.add_method('GetIsBroadcastSS', 'bool', []) ## ss-record.h (module 'wimax'): ns3::Mac48Address ns3::SSRecord::GetMacAddress() const [member function] cls.add_method('GetMacAddress', 'ns3::Mac48Address', [], is_const=True) ## ss-record.h (module 'wimax'): ns3::WimaxPhy::ModulationType ns3::SSRecord::GetModulationType() const [member function] cls.add_method('GetModulationType', 'ns3::WimaxPhy::ModulationType', [], is_const=True) ## ss-record.h (module 'wimax'): bool ns3::SSRecord::GetPollForRanging() const [member function] cls.add_method('GetPollForRanging', 'bool', [], is_const=True) ## ss-record.h (module 'wimax'): bool ns3::SSRecord::GetPollMeBit() const [member function] cls.add_method('GetPollMeBit', 'bool', [], is_const=True) ## ss-record.h (module 'wimax'): ns3::Cid ns3::SSRecord::GetPrimaryCid() const [member function] cls.add_method('GetPrimaryCid', 'ns3::Cid', [], is_const=True) ## ss-record.h (module 'wimax'): uint8_t ns3::SSRecord::GetRangingCorrectionRetries() const [member function] cls.add_method('GetRangingCorrectionRetries', 'uint8_t', [], is_const=True) ## ss-record.h (module 'wimax'): ns3::WimaxNetDevice::RangingStatus ns3::SSRecord::GetRangingStatus() const [member function] cls.add_method('GetRangingStatus', 'ns3::WimaxNetDevice::RangingStatus', [], is_const=True) ## ss-record.h (module 'wimax'): std::vector<ns3::ServiceFlow*,std::allocator<ns3::ServiceFlow*> > ns3::SSRecord::GetServiceFlows(ns3::ServiceFlow::SchedulingType schedulingType) const [member function] cls.add_method('GetServiceFlows', 'std::vector< ns3::ServiceFlow * >', [param('ns3::ServiceFlow::SchedulingType', 'schedulingType')], is_const=True) ## ss-record.h (module 'wimax'): uint16_t ns3::SSRecord::GetSfTransactionId() const [member function] cls.add_method('GetSfTransactionId', 'uint16_t', [], is_const=True) ## ss-record.h (module 'wimax'): void ns3::SSRecord::IncrementDsaRspRetries() [member function] cls.add_method('IncrementDsaRspRetries', 'void', []) ## ss-record.h (module 'wimax'): void ns3::SSRecord::IncrementInvitedRangingRetries() [member function] cls.add_method('IncrementInvitedRangingRetries', 'void', []) ## ss-record.h (module 'wimax'): void ns3::SSRecord::IncrementRangingCorrectionRetries() [member function] cls.add_method('IncrementRangingCorrectionRetries', 'void', []) ## ss-record.h (module 'wimax'): void ns3::SSRecord::ResetInvitedRangingRetries() [member function] cls.add_method('ResetInvitedRangingRetries', 'void', []) ## ss-record.h (module 'wimax'): void ns3::SSRecord::ResetRangingCorrectionRetries() [member function] cls.add_method('ResetRangingCorrectionRetries', 'void', []) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetAreServiceFlowsAllocated(bool val) [member function] cls.add_method('SetAreServiceFlowsAllocated', 'void', [param('bool', 'val')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetBasicCid(ns3::Cid basicCid) [member function] cls.add_method('SetBasicCid', 'void', [param('ns3::Cid', 'basicCid')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetDsaRsp(ns3::DsaRsp dsaRsp) [member function] cls.add_method('SetDsaRsp', 'void', [param('ns3::DsaRsp', 'dsaRsp')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetDsaRspRetries(uint8_t dsaRspRetries) [member function] cls.add_method('SetDsaRspRetries', 'void', [param('uint8_t', 'dsaRspRetries')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetIPAddress(ns3::Ipv4Address IPaddress) [member function] cls.add_method('SetIPAddress', 'void', [param('ns3::Ipv4Address', 'IPaddress')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetIsBroadcastSS(bool arg0) [member function] cls.add_method('SetIsBroadcastSS', 'void', [param('bool', 'arg0')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetMacAddress(ns3::Mac48Address macAddress) [member function] cls.add_method('SetMacAddress', 'void', [param('ns3::Mac48Address', 'macAddress')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetModulationType(ns3::WimaxPhy::ModulationType modulationType) [member function] cls.add_method('SetModulationType', 'void', [param('ns3::WimaxPhy::ModulationType', 'modulationType')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetPollMeBit(bool pollMeBit) [member function] cls.add_method('SetPollMeBit', 'void', [param('bool', 'pollMeBit')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetPrimaryCid(ns3::Cid primaryCid) [member function] cls.add_method('SetPrimaryCid', 'void', [param('ns3::Cid', 'primaryCid')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetRangingStatus(ns3::WimaxNetDevice::RangingStatus rangingStatus) [member function] cls.add_method('SetRangingStatus', 'void', [param('ns3::WimaxNetDevice::RangingStatus', 'rangingStatus')]) ## ss-record.h (module 'wimax'): void ns3::SSRecord::SetSfTransactionId(uint16_t sfTransactionId) [member function] cls.add_method('SetSfTransactionId', 'void', [param('uint16_t', 'sfTransactionId')]) return def register_Ns3SeedManager_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::SeedManager::SeedManager() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::SeedManager::SeedManager(ns3::SeedManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::SeedManager const &', 'arg0')]) ## random-variable.h (module 'core'): static bool ns3::SeedManager::CheckSeed(uint32_t seed) [member function] cls.add_method('CheckSeed', 'bool', [param('uint32_t', 'seed')], is_static=True) ## random-variable.h (module 'core'): static uint32_t ns3::SeedManager::GetRun() [member function] cls.add_method('GetRun', 'uint32_t', [], is_static=True) ## random-variable.h (module 'core'): static uint32_t ns3::SeedManager::GetSeed() [member function] cls.add_method('GetSeed', 'uint32_t', [], is_static=True) ## random-variable.h (module 'core'): static void ns3::SeedManager::SetRun(uint32_t run) [member function] cls.add_method('SetRun', 'void', [param('uint32_t', 'run')], is_static=True) ## random-variable.h (module 'core'): static void ns3::SeedManager::SetSeed(uint32_t seed) [member function] cls.add_method('SetSeed', 'void', [param('uint32_t', 'seed')], is_static=True) return def register_Ns3SendParams_methods(root_module, cls): ## send-params.h (module 'wimax'): ns3::SendParams::SendParams(ns3::SendParams const & arg0) [copy constructor] cls.add_constructor([param('ns3::SendParams const &', 'arg0')]) ## send-params.h (module 'wimax'): ns3::SendParams::SendParams() [constructor] cls.add_constructor([]) return def register_Ns3SequentialVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::SequentialVariable::SequentialVariable(ns3::SequentialVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::SequentialVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::SequentialVariable::SequentialVariable(double f, double l, double i=1, uint32_t c=1) [constructor] cls.add_constructor([param('double', 'f'), param('double', 'l'), param('double', 'i', default_value='1'), param('uint32_t', 'c', default_value='1')]) ## random-variable.h (module 'core'): ns3::SequentialVariable::SequentialVariable(double f, double l, ns3::RandomVariable const & i, uint32_t c=1) [constructor] cls.add_constructor([param('double', 'f'), param('double', 'l'), param('ns3::RandomVariable const &', 'i'), param('uint32_t', 'c', default_value='1')]) return def register_Ns3ServiceFlow_methods(root_module, cls): ## service-flow.h (module 'wimax'): ns3::ServiceFlow::ServiceFlow(ns3::Tlv tlv) [constructor] cls.add_constructor([param('ns3::Tlv', 'tlv')]) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::ServiceFlow(ns3::ServiceFlow::Direction direction) [constructor] cls.add_constructor([param('ns3::ServiceFlow::Direction', 'direction')]) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::ServiceFlow() [constructor] cls.add_constructor([]) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::ServiceFlow(ns3::ServiceFlow const & sf) [copy constructor] cls.add_constructor([param('ns3::ServiceFlow const &', 'sf')]) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::ServiceFlow(uint32_t sfid, ns3::ServiceFlow::Direction direction, ns3::Ptr<ns3::WimaxConnection> connection) [constructor] cls.add_constructor([param('uint32_t', 'sfid'), param('ns3::ServiceFlow::Direction', 'direction'), param('ns3::Ptr< ns3::WimaxConnection >', 'connection')]) ## service-flow.h (module 'wimax'): bool ns3::ServiceFlow::CheckClassifierMatch(ns3::Ipv4Address srcAddress, ns3::Ipv4Address dstAddress, uint16_t srcPort, uint16_t dstPort, uint8_t proto) const [member function] cls.add_method('CheckClassifierMatch', 'bool', [param('ns3::Ipv4Address', 'srcAddress'), param('ns3::Ipv4Address', 'dstAddress'), param('uint16_t', 'srcPort'), param('uint16_t', 'dstPort'), param('uint8_t', 'proto')], is_const=True) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::CleanUpQueue() [member function] cls.add_method('CleanUpQueue', 'void', []) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::CopyParametersFrom(ns3::ServiceFlow sf) [member function] cls.add_method('CopyParametersFrom', 'void', [param('ns3::ServiceFlow', 'sf')]) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetArqBlockLifeTime() const [member function] cls.add_method('GetArqBlockLifeTime', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetArqBlockSize() const [member function] cls.add_method('GetArqBlockSize', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint8_t ns3::ServiceFlow::GetArqDeliverInOrder() const [member function] cls.add_method('GetArqDeliverInOrder', 'uint8_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint8_t ns3::ServiceFlow::GetArqEnable() const [member function] cls.add_method('GetArqEnable', 'uint8_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetArqPurgeTimeout() const [member function] cls.add_method('GetArqPurgeTimeout', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetArqRetryTimeoutRx() const [member function] cls.add_method('GetArqRetryTimeoutRx', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetArqRetryTimeoutTx() const [member function] cls.add_method('GetArqRetryTimeoutTx', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetArqSyncLoss() const [member function] cls.add_method('GetArqSyncLoss', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetArqWindowSize() const [member function] cls.add_method('GetArqWindowSize', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetCid() const [member function] cls.add_method('GetCid', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::Ptr<ns3::WimaxConnection> ns3::ServiceFlow::GetConnection() const [member function] cls.add_method('GetConnection', 'ns3::Ptr< ns3::WimaxConnection >', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::CsParameters ns3::ServiceFlow::GetConvergenceSublayerParam() const [member function] cls.add_method('GetConvergenceSublayerParam', 'ns3::CsParameters', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::CsSpecification ns3::ServiceFlow::GetCsSpecification() const [member function] cls.add_method('GetCsSpecification', 'ns3::ServiceFlow::CsSpecification', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::Direction ns3::ServiceFlow::GetDirection() const [member function] cls.add_method('GetDirection', 'ns3::ServiceFlow::Direction', [], is_const=True) ## service-flow.h (module 'wimax'): uint8_t ns3::ServiceFlow::GetFixedversusVariableSduIndicator() const [member function] cls.add_method('GetFixedversusVariableSduIndicator', 'uint8_t', [], is_const=True) ## service-flow.h (module 'wimax'): bool ns3::ServiceFlow::GetIsEnabled() const [member function] cls.add_method('GetIsEnabled', 'bool', [], is_const=True) ## service-flow.h (module 'wimax'): bool ns3::ServiceFlow::GetIsMulticast() const [member function] cls.add_method('GetIsMulticast', 'bool', [], is_const=True) ## service-flow.h (module 'wimax'): uint32_t ns3::ServiceFlow::GetMaxSustainedTrafficRate() const [member function] cls.add_method('GetMaxSustainedTrafficRate', 'uint32_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint32_t ns3::ServiceFlow::GetMaxTrafficBurst() const [member function] cls.add_method('GetMaxTrafficBurst', 'uint32_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint32_t ns3::ServiceFlow::GetMaximumLatency() const [member function] cls.add_method('GetMaximumLatency', 'uint32_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint32_t ns3::ServiceFlow::GetMinReservedTrafficRate() const [member function] cls.add_method('GetMinReservedTrafficRate', 'uint32_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint32_t ns3::ServiceFlow::GetMinTolerableTrafficRate() const [member function] cls.add_method('GetMinTolerableTrafficRate', 'uint32_t', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::WimaxPhy::ModulationType ns3::ServiceFlow::GetModulation() const [member function] cls.add_method('GetModulation', 'ns3::WimaxPhy::ModulationType', [], is_const=True) ## service-flow.h (module 'wimax'): uint8_t ns3::ServiceFlow::GetQosParamSetType() const [member function] cls.add_method('GetQosParamSetType', 'uint8_t', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::Ptr<ns3::WimaxMacQueue> ns3::ServiceFlow::GetQueue() const [member function] cls.add_method('GetQueue', 'ns3::Ptr< ns3::WimaxMacQueue >', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::ServiceFlowRecord * ns3::ServiceFlow::GetRecord() const [member function] cls.add_method('GetRecord', 'ns3::ServiceFlowRecord *', [], is_const=True) ## service-flow.h (module 'wimax'): uint32_t ns3::ServiceFlow::GetRequestTransmissionPolicy() const [member function] cls.add_method('GetRequestTransmissionPolicy', 'uint32_t', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::SchedulingType ns3::ServiceFlow::GetSchedulingType() const [member function] cls.add_method('GetSchedulingType', 'ns3::ServiceFlow::SchedulingType', [], is_const=True) ## service-flow.h (module 'wimax'): char * ns3::ServiceFlow::GetSchedulingTypeStr() const [member function] cls.add_method('GetSchedulingTypeStr', 'char *', [], is_const=True) ## service-flow.h (module 'wimax'): uint8_t ns3::ServiceFlow::GetSduSize() const [member function] cls.add_method('GetSduSize', 'uint8_t', [], is_const=True) ## service-flow.h (module 'wimax'): std::string ns3::ServiceFlow::GetServiceClassName() const [member function] cls.add_method('GetServiceClassName', 'std::string', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::SchedulingType ns3::ServiceFlow::GetServiceSchedulingType() const [member function] cls.add_method('GetServiceSchedulingType', 'ns3::ServiceFlow::SchedulingType', [], is_const=True) ## service-flow.h (module 'wimax'): uint32_t ns3::ServiceFlow::GetSfid() const [member function] cls.add_method('GetSfid', 'uint32_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetTargetSAID() const [member function] cls.add_method('GetTargetSAID', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint32_t ns3::ServiceFlow::GetToleratedJitter() const [member function] cls.add_method('GetToleratedJitter', 'uint32_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint8_t ns3::ServiceFlow::GetTrafficPriority() const [member function] cls.add_method('GetTrafficPriority', 'uint8_t', [], is_const=True) ## service-flow.h (module 'wimax'): ns3::ServiceFlow::Type ns3::ServiceFlow::GetType() const [member function] cls.add_method('GetType', 'ns3::ServiceFlow::Type', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetUnsolicitedGrantInterval() const [member function] cls.add_method('GetUnsolicitedGrantInterval', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): uint16_t ns3::ServiceFlow::GetUnsolicitedPollingInterval() const [member function] cls.add_method('GetUnsolicitedPollingInterval', 'uint16_t', [], is_const=True) ## service-flow.h (module 'wimax'): bool ns3::ServiceFlow::HasPackets() const [member function] cls.add_method('HasPackets', 'bool', [], is_const=True) ## service-flow.h (module 'wimax'): bool ns3::ServiceFlow::HasPackets(ns3::MacHeaderType::HeaderType packetType) const [member function] cls.add_method('HasPackets', 'bool', [param('ns3::MacHeaderType::HeaderType', 'packetType')], is_const=True) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::InitValues() [member function] cls.add_method('InitValues', 'void', []) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::PrintQoSParameters() const [member function] cls.add_method('PrintQoSParameters', 'void', [], is_const=True) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetArqBlockLifeTime(uint16_t arg0) [member function] cls.add_method('SetArqBlockLifeTime', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetArqBlockSize(uint16_t arg0) [member function] cls.add_method('SetArqBlockSize', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetArqDeliverInOrder(uint8_t arg0) [member function] cls.add_method('SetArqDeliverInOrder', 'void', [param('uint8_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetArqEnable(uint8_t arg0) [member function] cls.add_method('SetArqEnable', 'void', [param('uint8_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetArqPurgeTimeout(uint16_t arg0) [member function] cls.add_method('SetArqPurgeTimeout', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetArqRetryTimeoutRx(uint16_t arg0) [member function] cls.add_method('SetArqRetryTimeoutRx', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetArqRetryTimeoutTx(uint16_t arg0) [member function] cls.add_method('SetArqRetryTimeoutTx', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetArqSyncLoss(uint16_t arg0) [member function] cls.add_method('SetArqSyncLoss', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetArqWindowSize(uint16_t arg0) [member function] cls.add_method('SetArqWindowSize', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetConnection(ns3::Ptr<ns3::WimaxConnection> connection) [member function] cls.add_method('SetConnection', 'void', [param('ns3::Ptr< ns3::WimaxConnection >', 'connection')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetConvergenceSublayerParam(ns3::CsParameters arg0) [member function] cls.add_method('SetConvergenceSublayerParam', 'void', [param('ns3::CsParameters', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetCsSpecification(ns3::ServiceFlow::CsSpecification arg0) [member function] cls.add_method('SetCsSpecification', 'void', [param('ns3::ServiceFlow::CsSpecification', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetDirection(ns3::ServiceFlow::Direction direction) [member function] cls.add_method('SetDirection', 'void', [param('ns3::ServiceFlow::Direction', 'direction')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetFixedversusVariableSduIndicator(uint8_t arg0) [member function] cls.add_method('SetFixedversusVariableSduIndicator', 'void', [param('uint8_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetIsEnabled(bool isEnabled) [member function] cls.add_method('SetIsEnabled', 'void', [param('bool', 'isEnabled')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetIsMulticast(bool isMulticast) [member function] cls.add_method('SetIsMulticast', 'void', [param('bool', 'isMulticast')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetMaxSustainedTrafficRate(uint32_t arg0) [member function] cls.add_method('SetMaxSustainedTrafficRate', 'void', [param('uint32_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetMaxTrafficBurst(uint32_t arg0) [member function] cls.add_method('SetMaxTrafficBurst', 'void', [param('uint32_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetMaximumLatency(uint32_t arg0) [member function] cls.add_method('SetMaximumLatency', 'void', [param('uint32_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetMinReservedTrafficRate(uint32_t arg0) [member function] cls.add_method('SetMinReservedTrafficRate', 'void', [param('uint32_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetMinTolerableTrafficRate(uint32_t arg0) [member function] cls.add_method('SetMinTolerableTrafficRate', 'void', [param('uint32_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetModulation(ns3::WimaxPhy::ModulationType modulationType) [member function] cls.add_method('SetModulation', 'void', [param('ns3::WimaxPhy::ModulationType', 'modulationType')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetQosParamSetType(uint8_t arg0) [member function] cls.add_method('SetQosParamSetType', 'void', [param('uint8_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetRecord(ns3::ServiceFlowRecord * record) [member function] cls.add_method('SetRecord', 'void', [param('ns3::ServiceFlowRecord *', 'record')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetRequestTransmissionPolicy(uint32_t arg0) [member function] cls.add_method('SetRequestTransmissionPolicy', 'void', [param('uint32_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetSduSize(uint8_t arg0) [member function] cls.add_method('SetSduSize', 'void', [param('uint8_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetServiceClassName(std::string arg0) [member function] cls.add_method('SetServiceClassName', 'void', [param('std::string', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetServiceSchedulingType(ns3::ServiceFlow::SchedulingType arg0) [member function] cls.add_method('SetServiceSchedulingType', 'void', [param('ns3::ServiceFlow::SchedulingType', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetSfid(uint32_t arg0) [member function] cls.add_method('SetSfid', 'void', [param('uint32_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetTargetSAID(uint16_t arg0) [member function] cls.add_method('SetTargetSAID', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetToleratedJitter(uint32_t arg0) [member function] cls.add_method('SetToleratedJitter', 'void', [param('uint32_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetTrafficPriority(uint8_t arg0) [member function] cls.add_method('SetTrafficPriority', 'void', [param('uint8_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetType(ns3::ServiceFlow::Type type) [member function] cls.add_method('SetType', 'void', [param('ns3::ServiceFlow::Type', 'type')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetUnsolicitedGrantInterval(uint16_t arg0) [member function] cls.add_method('SetUnsolicitedGrantInterval', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): void ns3::ServiceFlow::SetUnsolicitedPollingInterval(uint16_t arg0) [member function] cls.add_method('SetUnsolicitedPollingInterval', 'void', [param('uint16_t', 'arg0')]) ## service-flow.h (module 'wimax'): ns3::Tlv ns3::ServiceFlow::ToTlv() const [member function] cls.add_method('ToTlv', 'ns3::Tlv', [], is_const=True) return def register_Ns3ServiceFlowRecord_methods(root_module, cls): ## service-flow-record.h (module 'wimax'): ns3::ServiceFlowRecord::ServiceFlowRecord(ns3::ServiceFlowRecord const & arg0) [copy constructor] cls.add_constructor([param('ns3::ServiceFlowRecord const &', 'arg0')]) ## service-flow-record.h (module 'wimax'): ns3::ServiceFlowRecord::ServiceFlowRecord() [constructor] cls.add_constructor([]) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetBacklogged() const [member function] cls.add_method('GetBacklogged', 'uint32_t', [], is_const=True) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetBackloggedTemp() const [member function] cls.add_method('GetBackloggedTemp', 'uint32_t', [], is_const=True) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetBwSinceLastExpiry() [member function] cls.add_method('GetBwSinceLastExpiry', 'uint32_t', []) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetBytesRcvd() const [member function] cls.add_method('GetBytesRcvd', 'uint32_t', [], is_const=True) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetBytesSent() const [member function] cls.add_method('GetBytesSent', 'uint32_t', [], is_const=True) ## service-flow-record.h (module 'wimax'): ns3::Time ns3::ServiceFlowRecord::GetDlTimeStamp() const [member function] cls.add_method('GetDlTimeStamp', 'ns3::Time', [], is_const=True) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetGrantSize() const [member function] cls.add_method('GetGrantSize', 'uint32_t', [], is_const=True) ## service-flow-record.h (module 'wimax'): ns3::Time ns3::ServiceFlowRecord::GetGrantTimeStamp() const [member function] cls.add_method('GetGrantTimeStamp', 'ns3::Time', [], is_const=True) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetGrantedBandwidth() [member function] cls.add_method('GetGrantedBandwidth', 'uint32_t', []) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetGrantedBandwidthTemp() [member function] cls.add_method('GetGrantedBandwidthTemp', 'uint32_t', []) ## service-flow-record.h (module 'wimax'): ns3::Time ns3::ServiceFlowRecord::GetLastGrantTime() const [member function] cls.add_method('GetLastGrantTime', 'ns3::Time', [], is_const=True) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetPktsRcvd() const [member function] cls.add_method('GetPktsRcvd', 'uint32_t', [], is_const=True) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetPktsSent() const [member function] cls.add_method('GetPktsSent', 'uint32_t', [], is_const=True) ## service-flow-record.h (module 'wimax'): uint32_t ns3::ServiceFlowRecord::GetRequestedBandwidth() [member function] cls.add_method('GetRequestedBandwidth', 'uint32_t', []) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::IncreaseBacklogged(uint32_t backlogged) [member function] cls.add_method('IncreaseBacklogged', 'void', [param('uint32_t', 'backlogged')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::IncreaseBackloggedTemp(uint32_t backloggedTemp) [member function] cls.add_method('IncreaseBackloggedTemp', 'void', [param('uint32_t', 'backloggedTemp')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetBacklogged(uint32_t backlogged) [member function] cls.add_method('SetBacklogged', 'void', [param('uint32_t', 'backlogged')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetBackloggedTemp(uint32_t backloggedTemp) [member function] cls.add_method('SetBackloggedTemp', 'void', [param('uint32_t', 'backloggedTemp')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetBwSinceLastExpiry(uint32_t bwSinceLastExpiry) [member function] cls.add_method('SetBwSinceLastExpiry', 'void', [param('uint32_t', 'bwSinceLastExpiry')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetBytesRcvd(uint32_t bytesRcvd) [member function] cls.add_method('SetBytesRcvd', 'void', [param('uint32_t', 'bytesRcvd')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetBytesSent(uint32_t bytesSent) [member function] cls.add_method('SetBytesSent', 'void', [param('uint32_t', 'bytesSent')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetDlTimeStamp(ns3::Time dlTimeStamp) [member function] cls.add_method('SetDlTimeStamp', 'void', [param('ns3::Time', 'dlTimeStamp')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetGrantSize(uint32_t grantSize) [member function] cls.add_method('SetGrantSize', 'void', [param('uint32_t', 'grantSize')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetGrantTimeStamp(ns3::Time grantTimeStamp) [member function] cls.add_method('SetGrantTimeStamp', 'void', [param('ns3::Time', 'grantTimeStamp')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetGrantedBandwidth(uint32_t grantedBandwidth) [member function] cls.add_method('SetGrantedBandwidth', 'void', [param('uint32_t', 'grantedBandwidth')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetGrantedBandwidthTemp(uint32_t grantedBandwidthTemp) [member function] cls.add_method('SetGrantedBandwidthTemp', 'void', [param('uint32_t', 'grantedBandwidthTemp')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetLastGrantTime(ns3::Time grantTime) [member function] cls.add_method('SetLastGrantTime', 'void', [param('ns3::Time', 'grantTime')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetPktsRcvd(uint32_t pktsRcvd) [member function] cls.add_method('SetPktsRcvd', 'void', [param('uint32_t', 'pktsRcvd')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetPktsSent(uint32_t pktsSent) [member function] cls.add_method('SetPktsSent', 'void', [param('uint32_t', 'pktsSent')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::SetRequestedBandwidth(uint32_t requestedBandwidth) [member function] cls.add_method('SetRequestedBandwidth', 'void', [param('uint32_t', 'requestedBandwidth')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::UpdateBwSinceLastExpiry(uint32_t bwSinceLastExpiry) [member function] cls.add_method('UpdateBwSinceLastExpiry', 'void', [param('uint32_t', 'bwSinceLastExpiry')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::UpdateBytesRcvd(uint32_t bytesRcvd) [member function] cls.add_method('UpdateBytesRcvd', 'void', [param('uint32_t', 'bytesRcvd')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::UpdateBytesSent(uint32_t bytesSent) [member function] cls.add_method('UpdateBytesSent', 'void', [param('uint32_t', 'bytesSent')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::UpdateGrantedBandwidth(uint32_t grantedBandwidth) [member function] cls.add_method('UpdateGrantedBandwidth', 'void', [param('uint32_t', 'grantedBandwidth')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::UpdateGrantedBandwidthTemp(uint32_t grantedBandwidthTemp) [member function] cls.add_method('UpdateGrantedBandwidthTemp', 'void', [param('uint32_t', 'grantedBandwidthTemp')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::UpdatePktsRcvd(uint32_t pktsRcvd) [member function] cls.add_method('UpdatePktsRcvd', 'void', [param('uint32_t', 'pktsRcvd')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::UpdatePktsSent(uint32_t pktsSent) [member function] cls.add_method('UpdatePktsSent', 'void', [param('uint32_t', 'pktsSent')]) ## service-flow-record.h (module 'wimax'): void ns3::ServiceFlowRecord::UpdateRequestedBandwidth(uint32_t requestedBandwidth) [member function] cls.add_method('UpdateRequestedBandwidth', 'void', [param('uint32_t', 'requestedBandwidth')]) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Next() [member function] cls.add_method('Next', 'ns3::Time', [], is_static=True, deprecated=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::RunOneEvent() [member function] cls.add_method('RunOneEvent', 'void', [], is_static=True, deprecated=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::TlvValue::TlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::TlvValue::TlvValue(ns3::TlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::TlvValue * ns3::TlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::TlvValue *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::TlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLen) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLen')], is_pure_virtual=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::TlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::TlvValue::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_Ns3TosTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue::TosTlvValue(ns3::TosTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TosTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue::TosTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue::TosTlvValue(uint8_t arg0, uint8_t arg1, uint8_t arg2) [constructor] cls.add_constructor([param('uint8_t', 'arg0'), param('uint8_t', 'arg1'), param('uint8_t', 'arg2')]) ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue * ns3::TosTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::TosTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::TosTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::TosTlvValue::GetHigh() const [member function] cls.add_method('GetHigh', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::TosTlvValue::GetLow() const [member function] cls.add_method('GetLow', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::TosTlvValue::GetMask() const [member function] cls.add_method('GetMask', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::TosTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::TosTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3TriangularVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::TriangularVariable::TriangularVariable(ns3::TriangularVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::TriangularVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::TriangularVariable::TriangularVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::TriangularVariable::TriangularVariable(double s, double l, double mean) [constructor] cls.add_constructor([param('double', 's'), param('double', 'l'), param('double', 'mean')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info')], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): static void ns3::TypeId::ResetInitialValues() [member function] cls.add_method('ResetInitialValues', 'void', [], is_static=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3U16TlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue::U16TlvValue(ns3::U16TlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::U16TlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue::U16TlvValue(uint16_t value) [constructor] cls.add_constructor([param('uint16_t', 'value')]) ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue::U16TlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue * ns3::U16TlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::U16TlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U16TlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLen) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLen')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U16TlvValue::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')]) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U16TlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint16_t ns3::U16TlvValue::GetValue() const [member function] cls.add_method('GetValue', 'uint16_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): void ns3::U16TlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3U32TlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue::U32TlvValue(ns3::U32TlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::U32TlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue::U32TlvValue(uint32_t value) [constructor] cls.add_constructor([param('uint32_t', 'value')]) ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue::U32TlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue * ns3::U32TlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::U32TlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U32TlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLen) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLen')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U32TlvValue::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')]) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U32TlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U32TlvValue::GetValue() const [member function] cls.add_method('GetValue', 'uint32_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): void ns3::U32TlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3U8TlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue::U8TlvValue(ns3::U8TlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::U8TlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue::U8TlvValue(uint8_t value) [constructor] cls.add_constructor([param('uint8_t', 'value')]) ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue::U8TlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue * ns3::U8TlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::U8TlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U8TlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLen) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLen')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U8TlvValue::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')]) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U8TlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::U8TlvValue::GetValue() const [member function] cls.add_method('GetValue', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): void ns3::U8TlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3UcdChannelEncodings_methods(root_module, cls): ## ul-mac-messages.h (module 'wimax'): ns3::UcdChannelEncodings::UcdChannelEncodings(ns3::UcdChannelEncodings const & arg0) [copy constructor] cls.add_constructor([param('ns3::UcdChannelEncodings const &', 'arg0')]) ## ul-mac-messages.h (module 'wimax'): ns3::UcdChannelEncodings::UcdChannelEncodings() [constructor] cls.add_constructor([]) ## ul-mac-messages.h (module 'wimax'): uint16_t ns3::UcdChannelEncodings::GetBwReqOppSize() const [member function] cls.add_method('GetBwReqOppSize', 'uint16_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint32_t ns3::UcdChannelEncodings::GetFrequency() const [member function] cls.add_method('GetFrequency', 'uint32_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint16_t ns3::UcdChannelEncodings::GetRangReqOppSize() const [member function] cls.add_method('GetRangReqOppSize', 'uint16_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint16_t ns3::UcdChannelEncodings::GetSize() const [member function] cls.add_method('GetSize', 'uint16_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::UcdChannelEncodings::Read(ns3::Buffer::Iterator start) [member function] cls.add_method('Read', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')]) ## ul-mac-messages.h (module 'wimax'): void ns3::UcdChannelEncodings::SetBwReqOppSize(uint16_t bwReqOppSize) [member function] cls.add_method('SetBwReqOppSize', 'void', [param('uint16_t', 'bwReqOppSize')]) ## ul-mac-messages.h (module 'wimax'): void ns3::UcdChannelEncodings::SetFrequency(uint32_t frequency) [member function] cls.add_method('SetFrequency', 'void', [param('uint32_t', 'frequency')]) ## ul-mac-messages.h (module 'wimax'): void ns3::UcdChannelEncodings::SetRangReqOppSize(uint16_t rangReqOppSize) [member function] cls.add_method('SetRangReqOppSize', 'void', [param('uint16_t', 'rangReqOppSize')]) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::UcdChannelEncodings::Write(ns3::Buffer::Iterator start) const [member function] cls.add_method('Write', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::UcdChannelEncodings::DoRead(ns3::Buffer::Iterator start) [member function] cls.add_method('DoRead', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::UcdChannelEncodings::DoWrite(ns3::Buffer::Iterator start) const [member function] cls.add_method('DoWrite', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3UniformVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::UniformVariable::UniformVariable(ns3::UniformVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::UniformVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::UniformVariable::UniformVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::UniformVariable::UniformVariable(double s, double l) [constructor] cls.add_constructor([param('double', 's'), param('double', 'l')]) ## random-variable.h (module 'core'): uint32_t ns3::UniformVariable::GetInteger(uint32_t s, uint32_t l) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 's'), param('uint32_t', 'l')]) ## random-variable.h (module 'core'): double ns3::UniformVariable::GetValue() const [member function] cls.add_method('GetValue', 'double', [], is_const=True) ## random-variable.h (module 'core'): double ns3::UniformVariable::GetValue(double s, double l) [member function] cls.add_method('GetValue', 'double', [param('double', 's'), param('double', 'l')]) return def register_Ns3VectorTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::VectorTlvValue::VectorTlvValue(ns3::VectorTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::VectorTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::VectorTlvValue::VectorTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): void ns3::VectorTlvValue::Add(ns3::Tlv const & val) [member function] cls.add_method('Add', 'void', [param('ns3::Tlv const &', 'val')]) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<ns3::Tlv* const*,std::vector<ns3::Tlv*, std::allocator<ns3::Tlv*> > > ns3::VectorTlvValue::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Tlv * const *, std::vector< ns3::Tlv * > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::VectorTlvValue * ns3::VectorTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::VectorTlvValue *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::VectorTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_pure_virtual=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<ns3::Tlv* const*,std::vector<ns3::Tlv*, std::allocator<ns3::Tlv*> > > ns3::VectorTlvValue::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Tlv * const *, std::vector< ns3::Tlv * > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::VectorTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::VectorTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3WeibullVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable(ns3::WeibullVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::WeibullVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable(double m) [constructor] cls.add_constructor([param('double', 'm')]) ## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable(double m, double s) [constructor] cls.add_constructor([param('double', 'm'), param('double', 's')]) ## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable(double m, double s, double b) [constructor] cls.add_constructor([param('double', 'm'), param('double', 's'), param('double', 'b')]) return def register_Ns3WimaxHelper_methods(root_module, cls): ## wimax-helper.h (module 'wimax'): ns3::WimaxHelper::WimaxHelper(ns3::WimaxHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::WimaxHelper const &', 'arg0')]) ## wimax-helper.h (module 'wimax'): ns3::WimaxHelper::WimaxHelper() [constructor] cls.add_constructor([]) ## wimax-helper.h (module 'wimax'): ns3::Ptr<ns3::BSScheduler> ns3::WimaxHelper::CreateBSScheduler(ns3::WimaxHelper::SchedulerType schedulerType) [member function] cls.add_method('CreateBSScheduler', 'ns3::Ptr< ns3::BSScheduler >', [param('ns3::WimaxHelper::SchedulerType', 'schedulerType')]) ## wimax-helper.h (module 'wimax'): ns3::Ptr<ns3::WimaxPhy> ns3::WimaxHelper::CreatePhy(ns3::WimaxHelper::PhyType phyType) [member function] cls.add_method('CreatePhy', 'ns3::Ptr< ns3::WimaxPhy >', [param('ns3::WimaxHelper::PhyType', 'phyType')]) ## wimax-helper.h (module 'wimax'): ns3::Ptr<ns3::WimaxPhy> ns3::WimaxHelper::CreatePhy(ns3::WimaxHelper::PhyType phyType, char * SNRTraceFilePath, bool activateLoss) [member function] cls.add_method('CreatePhy', 'ns3::Ptr< ns3::WimaxPhy >', [param('ns3::WimaxHelper::PhyType', 'phyType'), param('char *', 'SNRTraceFilePath'), param('bool', 'activateLoss')]) ## wimax-helper.h (module 'wimax'): ns3::Ptr<ns3::WimaxPhy> ns3::WimaxHelper::CreatePhyWithoutChannel(ns3::WimaxHelper::PhyType phyType) [member function] cls.add_method('CreatePhyWithoutChannel', 'ns3::Ptr< ns3::WimaxPhy >', [param('ns3::WimaxHelper::PhyType', 'phyType')]) ## wimax-helper.h (module 'wimax'): ns3::Ptr<ns3::WimaxPhy> ns3::WimaxHelper::CreatePhyWithoutChannel(ns3::WimaxHelper::PhyType phyType, char * SNRTraceFilePath, bool activateLoss) [member function] cls.add_method('CreatePhyWithoutChannel', 'ns3::Ptr< ns3::WimaxPhy >', [param('ns3::WimaxHelper::PhyType', 'phyType'), param('char *', 'SNRTraceFilePath'), param('bool', 'activateLoss')]) ## wimax-helper.h (module 'wimax'): ns3::ServiceFlow ns3::WimaxHelper::CreateServiceFlow(ns3::ServiceFlow::Direction direction, ns3::ServiceFlow::SchedulingType schedulinType, ns3::IpcsClassifierRecord classifier) [member function] cls.add_method('CreateServiceFlow', 'ns3::ServiceFlow', [param('ns3::ServiceFlow::Direction', 'direction'), param('ns3::ServiceFlow::SchedulingType', 'schedulinType'), param('ns3::IpcsClassifierRecord', 'classifier')]) ## wimax-helper.h (module 'wimax'): ns3::Ptr<ns3::UplinkScheduler> ns3::WimaxHelper::CreateUplinkScheduler(ns3::WimaxHelper::SchedulerType schedulerType) [member function] cls.add_method('CreateUplinkScheduler', 'ns3::Ptr< ns3::UplinkScheduler >', [param('ns3::WimaxHelper::SchedulerType', 'schedulerType')]) ## wimax-helper.h (module 'wimax'): static void ns3::WimaxHelper::EnableAsciiForConnection(ns3::Ptr<ns3::OutputStreamWrapper> oss, uint32_t nodeid, uint32_t deviceid, char * netdevice, char * connection) [member function] cls.add_method('EnableAsciiForConnection', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'oss'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('char *', 'netdevice'), param('char *', 'connection')], is_static=True) ## wimax-helper.h (module 'wimax'): static void ns3::WimaxHelper::EnableLogComponents() [member function] cls.add_method('EnableLogComponents', 'void', [], is_static=True) ## wimax-helper.h (module 'wimax'): ns3::NetDeviceContainer ns3::WimaxHelper::Install(ns3::NodeContainer c, ns3::WimaxHelper::NetDeviceType type, ns3::WimaxHelper::PhyType phyType, ns3::WimaxHelper::SchedulerType schedulerType) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c'), param('ns3::WimaxHelper::NetDeviceType', 'type'), param('ns3::WimaxHelper::PhyType', 'phyType'), param('ns3::WimaxHelper::SchedulerType', 'schedulerType')]) ## wimax-helper.h (module 'wimax'): ns3::NetDeviceContainer ns3::WimaxHelper::Install(ns3::NodeContainer c, ns3::WimaxHelper::NetDeviceType deviceType, ns3::WimaxHelper::PhyType phyType, ns3::Ptr<ns3::WimaxChannel> channel, ns3::WimaxHelper::SchedulerType schedulerType) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c'), param('ns3::WimaxHelper::NetDeviceType', 'deviceType'), param('ns3::WimaxHelper::PhyType', 'phyType'), param('ns3::Ptr< ns3::WimaxChannel >', 'channel'), param('ns3::WimaxHelper::SchedulerType', 'schedulerType')]) ## wimax-helper.h (module 'wimax'): ns3::NetDeviceContainer ns3::WimaxHelper::Install(ns3::NodeContainer c, ns3::WimaxHelper::NetDeviceType deviceType, ns3::WimaxHelper::PhyType phyType, ns3::WimaxHelper::SchedulerType schedulerType, double frameDuration) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c'), param('ns3::WimaxHelper::NetDeviceType', 'deviceType'), param('ns3::WimaxHelper::PhyType', 'phyType'), param('ns3::WimaxHelper::SchedulerType', 'schedulerType'), param('double', 'frameDuration')]) ## wimax-helper.h (module 'wimax'): ns3::Ptr<ns3::WimaxNetDevice> ns3::WimaxHelper::Install(ns3::Ptr<ns3::Node> node, ns3::WimaxHelper::NetDeviceType deviceType, ns3::WimaxHelper::PhyType phyType, ns3::Ptr<ns3::WimaxChannel> channel, ns3::WimaxHelper::SchedulerType schedulerType) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::WimaxNetDevice >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::WimaxHelper::NetDeviceType', 'deviceType'), param('ns3::WimaxHelper::PhyType', 'phyType'), param('ns3::Ptr< ns3::WimaxChannel >', 'channel'), param('ns3::WimaxHelper::SchedulerType', 'schedulerType')]) ## wimax-helper.h (module 'wimax'): void ns3::WimaxHelper::SetPropagationLossModel(ns3::SimpleOfdmWimaxChannel::PropModel propagationModel) [member function] cls.add_method('SetPropagationLossModel', 'void', [param('ns3::SimpleOfdmWimaxChannel::PropModel', 'propagationModel')]) ## wimax-helper.h (module 'wimax'): void ns3::WimaxHelper::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function] cls.add_method('EnableAsciiInternal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## wimax-helper.h (module 'wimax'): void ns3::WimaxHelper::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename, bool promiscuous) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename'), param('bool', 'promiscuous')], visibility='private', is_virtual=True) return def register_Ns3ZetaVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::ZetaVariable::ZetaVariable(ns3::ZetaVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::ZetaVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::ZetaVariable::ZetaVariable(double alpha) [constructor] cls.add_constructor([param('double', 'alpha')]) ## random-variable.h (module 'core'): ns3::ZetaVariable::ZetaVariable() [constructor] cls.add_constructor([]) return def register_Ns3ZipfVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::ZipfVariable::ZipfVariable(ns3::ZipfVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::ZipfVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::ZipfVariable::ZipfVariable(long int N, double alpha) [constructor] cls.add_constructor([param('long int', 'N'), param('double', 'alpha')]) ## random-variable.h (module 'core'): ns3::ZipfVariable::ZipfVariable() [constructor] cls.add_constructor([]) 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_Ns3SimpleOfdmSendParam_methods(root_module, cls): ## simple-ofdm-send-param.h (module 'wimax'): ns3::simpleOfdmSendParam::simpleOfdmSendParam(ns3::simpleOfdmSendParam const & arg0) [copy constructor] cls.add_constructor([param('ns3::simpleOfdmSendParam const &', 'arg0')]) ## simple-ofdm-send-param.h (module 'wimax'): ns3::simpleOfdmSendParam::simpleOfdmSendParam() [constructor] cls.add_constructor([]) ## simple-ofdm-send-param.h (module 'wimax'): ns3::simpleOfdmSendParam::simpleOfdmSendParam(ns3::bvec const & fecBlock, uint32_t burstSize, bool isFirstBlock, uint64_t Frequency, ns3::WimaxPhy::ModulationType modulationType, uint8_t direction, double rxPowerDbm) [constructor] cls.add_constructor([param('ns3::bvec const &', 'fecBlock'), param('uint32_t', 'burstSize'), param('bool', 'isFirstBlock'), param('uint64_t', 'Frequency'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('uint8_t', 'direction'), param('double', 'rxPowerDbm')]) ## simple-ofdm-send-param.h (module 'wimax'): ns3::simpleOfdmSendParam::simpleOfdmSendParam(uint32_t burstSize, bool isFirstBlock, uint64_t Frequency, ns3::WimaxPhy::ModulationType modulationType, uint8_t direction, double rxPowerDbm, ns3::Ptr<ns3::PacketBurst> burst) [constructor] cls.add_constructor([param('uint32_t', 'burstSize'), param('bool', 'isFirstBlock'), param('uint64_t', 'Frequency'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('uint8_t', 'direction'), param('double', 'rxPowerDbm'), param('ns3::Ptr< ns3::PacketBurst >', 'burst')]) ## simple-ofdm-send-param.h (module 'wimax'): ns3::Ptr<ns3::PacketBurst> ns3::simpleOfdmSendParam::GetBurst() [member function] cls.add_method('GetBurst', 'ns3::Ptr< ns3::PacketBurst >', []) ## simple-ofdm-send-param.h (module 'wimax'): uint32_t ns3::simpleOfdmSendParam::GetBurstSize() [member function] cls.add_method('GetBurstSize', 'uint32_t', []) ## simple-ofdm-send-param.h (module 'wimax'): uint8_t ns3::simpleOfdmSendParam::GetDirection() [member function] cls.add_method('GetDirection', 'uint8_t', []) ## simple-ofdm-send-param.h (module 'wimax'): ns3::bvec ns3::simpleOfdmSendParam::GetFecBlock() [member function] cls.add_method('GetFecBlock', 'ns3::bvec', []) ## simple-ofdm-send-param.h (module 'wimax'): uint64_t ns3::simpleOfdmSendParam::GetFrequency() [member function] cls.add_method('GetFrequency', 'uint64_t', []) ## simple-ofdm-send-param.h (module 'wimax'): bool ns3::simpleOfdmSendParam::GetIsFirstBlock() [member function] cls.add_method('GetIsFirstBlock', 'bool', []) ## simple-ofdm-send-param.h (module 'wimax'): ns3::WimaxPhy::ModulationType ns3::simpleOfdmSendParam::GetModulationType() [member function] cls.add_method('GetModulationType', 'ns3::WimaxPhy::ModulationType', []) ## simple-ofdm-send-param.h (module 'wimax'): double ns3::simpleOfdmSendParam::GetRxPowerDbm() [member function] cls.add_method('GetRxPowerDbm', 'double', []) ## simple-ofdm-send-param.h (module 'wimax'): void ns3::simpleOfdmSendParam::SetBurstSize(uint32_t burstSize) [member function] cls.add_method('SetBurstSize', 'void', [param('uint32_t', 'burstSize')]) ## simple-ofdm-send-param.h (module 'wimax'): void ns3::simpleOfdmSendParam::SetDirection(uint8_t direction) [member function] cls.add_method('SetDirection', 'void', [param('uint8_t', 'direction')]) ## simple-ofdm-send-param.h (module 'wimax'): void ns3::simpleOfdmSendParam::SetFecBlock(ns3::bvec const & fecBlock) [member function] cls.add_method('SetFecBlock', 'void', [param('ns3::bvec const &', 'fecBlock')]) ## simple-ofdm-send-param.h (module 'wimax'): void ns3::simpleOfdmSendParam::SetFrequency(uint64_t Frequency) [member function] cls.add_method('SetFrequency', 'void', [param('uint64_t', 'Frequency')]) ## simple-ofdm-send-param.h (module 'wimax'): void ns3::simpleOfdmSendParam::SetIsFirstBlock(bool isFirstBlock) [member function] cls.add_method('SetIsFirstBlock', 'void', [param('bool', 'isFirstBlock')]) ## simple-ofdm-send-param.h (module 'wimax'): void ns3::simpleOfdmSendParam::SetModulationType(ns3::WimaxPhy::ModulationType modulationType) [member function] cls.add_method('SetModulationType', 'void', [param('ns3::WimaxPhy::ModulationType', 'modulationType')]) ## simple-ofdm-send-param.h (module 'wimax'): void ns3::simpleOfdmSendParam::SetRxPowerDbm(double rxPowerDbm) [member function] cls.add_method('SetRxPowerDbm', 'void', [param('double', 'rxPowerDbm')]) 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_Ns3ClassificationRuleVectorTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue::ClassificationRuleVectorTlvValue(ns3::ClassificationRuleVectorTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ClassificationRuleVectorTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue::ClassificationRuleVectorTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue * ns3::ClassificationRuleVectorTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::ClassificationRuleVectorTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::ClassificationRuleVectorTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) return def register_Ns3ConstantVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::ConstantVariable::ConstantVariable(ns3::ConstantVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::ConstantVariable::ConstantVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::ConstantVariable::ConstantVariable(double c) [constructor] cls.add_constructor([param('double', 'c')]) ## random-variable.h (module 'core'): void ns3::ConstantVariable::SetConstant(double c) [member function] cls.add_method('SetConstant', 'void', [param('double', 'c')]) return def register_Ns3CsParamVectorTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue::CsParamVectorTlvValue(ns3::CsParamVectorTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CsParamVectorTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue::CsParamVectorTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue * ns3::CsParamVectorTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::CsParamVectorTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::CsParamVectorTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) return def register_Ns3DeterministicVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::DeterministicVariable::DeterministicVariable(ns3::DeterministicVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeterministicVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::DeterministicVariable::DeterministicVariable(double * d, uint32_t c) [constructor] cls.add_constructor([param('double *', 'd'), param('uint32_t', 'c')]) return def register_Ns3EmpiricalVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::EmpiricalVariable::EmpiricalVariable(ns3::EmpiricalVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmpiricalVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::EmpiricalVariable::EmpiricalVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): void ns3::EmpiricalVariable::CDF(double v, double c) [member function] cls.add_method('CDF', 'void', [param('double', 'v'), param('double', 'c')]) return def register_Ns3ErlangVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::ErlangVariable::ErlangVariable(ns3::ErlangVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::ErlangVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::ErlangVariable::ErlangVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::ErlangVariable::ErlangVariable(unsigned int k, double lambda) [constructor] cls.add_constructor([param('unsigned int', 'k'), param('double', 'lambda')]) ## random-variable.h (module 'core'): double ns3::ErlangVariable::GetValue() const [member function] cls.add_method('GetValue', 'double', [], is_const=True) ## random-variable.h (module 'core'): double ns3::ErlangVariable::GetValue(unsigned int k, double lambda) const [member function] cls.add_method('GetValue', 'double', [param('unsigned int', 'k'), param('double', 'lambda')], is_const=True) return def register_Ns3ExponentialVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::ExponentialVariable::ExponentialVariable(ns3::ExponentialVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::ExponentialVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::ExponentialVariable::ExponentialVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::ExponentialVariable::ExponentialVariable(double m) [constructor] cls.add_constructor([param('double', 'm')]) ## random-variable.h (module 'core'): ns3::ExponentialVariable::ExponentialVariable(double m, double b) [constructor] cls.add_constructor([param('double', 'm'), param('double', 'b')]) return def register_Ns3GammaVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::GammaVariable::GammaVariable(ns3::GammaVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::GammaVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::GammaVariable::GammaVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::GammaVariable::GammaVariable(double alpha, double beta) [constructor] cls.add_constructor([param('double', 'alpha'), param('double', 'beta')]) ## random-variable.h (module 'core'): double ns3::GammaVariable::GetValue() const [member function] cls.add_method('GetValue', 'double', [], is_const=True) ## random-variable.h (module 'core'): double ns3::GammaVariable::GetValue(double alpha, double beta) const [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha'), param('double', 'beta')], is_const=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_Ns3IntEmpiricalVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::IntEmpiricalVariable::IntEmpiricalVariable(ns3::IntEmpiricalVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntEmpiricalVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::IntEmpiricalVariable::IntEmpiricalVariable() [constructor] cls.add_constructor([]) return def register_Ns3Ipv4AddressTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::Ipv4AddressTlvValue(ns3::Ipv4AddressTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::Ipv4AddressTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): void ns3::Ipv4AddressTlvValue::Add(ns3::Ipv4Address address, ns3::Ipv4Mask Mask) [member function] cls.add_method('Add', 'void', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'Mask')]) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const ns3::Ipv4AddressTlvValue::ipv4Addr*,std::vector<ns3::Ipv4AddressTlvValue::ipv4Addr, std::allocator<ns3::Ipv4AddressTlvValue::ipv4Addr> > > ns3::Ipv4AddressTlvValue::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ipv4AddressTlvValue::ipv4Addr const *, std::vector< ns3::Ipv4AddressTlvValue::ipv4Addr > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue * ns3::Ipv4AddressTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ipv4AddressTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::Ipv4AddressTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const ns3::Ipv4AddressTlvValue::ipv4Addr*,std::vector<ns3::Ipv4AddressTlvValue::ipv4Addr, std::allocator<ns3::Ipv4AddressTlvValue::ipv4Addr> > > ns3::Ipv4AddressTlvValue::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ipv4AddressTlvValue::ipv4Addr const *, std::vector< ns3::Ipv4AddressTlvValue::ipv4Addr > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::Ipv4AddressTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::Ipv4AddressTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3Ipv4AddressTlvValueIpv4Addr_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr::ipv4Addr() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr::ipv4Addr(ns3::Ipv4AddressTlvValue::ipv4Addr const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressTlvValue::ipv4Addr const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr::Address [variable] cls.add_instance_attribute('Address', 'ns3::Ipv4Address', is_const=False) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr::Mask [variable] cls.add_instance_attribute('Mask', 'ns3::Ipv4Mask', is_const=False) return def register_Ns3LogNormalVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::LogNormalVariable::LogNormalVariable(ns3::LogNormalVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::LogNormalVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::LogNormalVariable::LogNormalVariable(double mu, double sigma) [constructor] cls.add_constructor([param('double', 'mu'), param('double', 'sigma')]) return def register_Ns3MacHeaderType_methods(root_module, cls): ## wimax-mac-header.h (module 'wimax'): ns3::MacHeaderType::MacHeaderType(ns3::MacHeaderType const & arg0) [copy constructor] cls.add_constructor([param('ns3::MacHeaderType const &', 'arg0')]) ## wimax-mac-header.h (module 'wimax'): ns3::MacHeaderType::MacHeaderType() [constructor] cls.add_constructor([]) ## wimax-mac-header.h (module 'wimax'): ns3::MacHeaderType::MacHeaderType(uint8_t type) [constructor] cls.add_constructor([param('uint8_t', 'type')]) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::MacHeaderType::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wimax-mac-header.h (module 'wimax'): ns3::TypeId ns3::MacHeaderType::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): std::string ns3::MacHeaderType::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::MacHeaderType::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::MacHeaderType::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): static ns3::TypeId ns3::MacHeaderType::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-mac-header.h (module 'wimax'): void ns3::MacHeaderType::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::MacHeaderType::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::MacHeaderType::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) return def register_Ns3ManagementMessageType_methods(root_module, cls): ## mac-messages.h (module 'wimax'): ns3::ManagementMessageType::ManagementMessageType(ns3::ManagementMessageType const & arg0) [copy constructor] cls.add_constructor([param('ns3::ManagementMessageType const &', 'arg0')]) ## mac-messages.h (module 'wimax'): ns3::ManagementMessageType::ManagementMessageType() [constructor] cls.add_constructor([]) ## mac-messages.h (module 'wimax'): ns3::ManagementMessageType::ManagementMessageType(uint8_t type) [constructor] cls.add_constructor([param('uint8_t', 'type')]) ## mac-messages.h (module 'wimax'): uint32_t ns3::ManagementMessageType::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mac-messages.h (module 'wimax'): ns3::TypeId ns3::ManagementMessageType::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): std::string ns3::ManagementMessageType::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::ManagementMessageType::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): uint8_t ns3::ManagementMessageType::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## mac-messages.h (module 'wimax'): static ns3::TypeId ns3::ManagementMessageType::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mac-messages.h (module 'wimax'): void ns3::ManagementMessageType::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::ManagementMessageType::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::ManagementMessageType::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) return def register_Ns3NormalVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::NormalVariable::NormalVariable(ns3::NormalVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::NormalVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::NormalVariable::NormalVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::NormalVariable::NormalVariable(double m, double v) [constructor] cls.add_constructor([param('double', 'm'), param('double', 'v')]) ## random-variable.h (module 'core'): ns3::NormalVariable::NormalVariable(double m, double v, double b) [constructor] cls.add_constructor([param('double', 'm'), param('double', 'v'), param('double', 'b')]) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Start() [member function] cls.add_method('Start', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3OfdmDownlinkFramePrefix_methods(root_module, cls): ## ofdm-downlink-frame-prefix.h (module 'wimax'): ns3::OfdmDownlinkFramePrefix::OfdmDownlinkFramePrefix(ns3::OfdmDownlinkFramePrefix const & arg0) [copy constructor] cls.add_constructor([param('ns3::OfdmDownlinkFramePrefix const &', 'arg0')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): ns3::OfdmDownlinkFramePrefix::OfdmDownlinkFramePrefix() [constructor] cls.add_constructor([]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::OfdmDownlinkFramePrefix::AddDlFramePrefixElement(ns3::DlFramePrefixIe dlFramePrefixElement) [member function] cls.add_method('AddDlFramePrefixElement', 'void', [param('ns3::DlFramePrefixIe', 'dlFramePrefixElement')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint32_t ns3::OfdmDownlinkFramePrefix::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): ns3::Mac48Address ns3::OfdmDownlinkFramePrefix::GetBaseStationId() const [member function] cls.add_method('GetBaseStationId', 'ns3::Mac48Address', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint8_t ns3::OfdmDownlinkFramePrefix::GetConfigurationChangeCount() const [member function] cls.add_method('GetConfigurationChangeCount', 'uint8_t', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): std::vector<ns3::DlFramePrefixIe, std::allocator<ns3::DlFramePrefixIe> > ns3::OfdmDownlinkFramePrefix::GetDlFramePrefixElements() const [member function] cls.add_method('GetDlFramePrefixElements', 'std::vector< ns3::DlFramePrefixIe >', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint32_t ns3::OfdmDownlinkFramePrefix::GetFrameNumber() const [member function] cls.add_method('GetFrameNumber', 'uint32_t', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint8_t ns3::OfdmDownlinkFramePrefix::GetHcs() const [member function] cls.add_method('GetHcs', 'uint8_t', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): std::string ns3::OfdmDownlinkFramePrefix::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): uint32_t ns3::OfdmDownlinkFramePrefix::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::OfdmDownlinkFramePrefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::OfdmDownlinkFramePrefix::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::OfdmDownlinkFramePrefix::SetBaseStationId(ns3::Mac48Address baseStationId) [member function] cls.add_method('SetBaseStationId', 'void', [param('ns3::Mac48Address', 'baseStationId')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::OfdmDownlinkFramePrefix::SetConfigurationChangeCount(uint8_t configurationChangeCount) [member function] cls.add_method('SetConfigurationChangeCount', 'void', [param('uint8_t', 'configurationChangeCount')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::OfdmDownlinkFramePrefix::SetFrameNumber(uint32_t frameNumber) [member function] cls.add_method('SetFrameNumber', 'void', [param('uint32_t', 'frameNumber')]) ## ofdm-downlink-frame-prefix.h (module 'wimax'): void ns3::OfdmDownlinkFramePrefix::SetHcs(uint8_t hcs) [member function] cls.add_method('SetHcs', 'void', [param('uint8_t', 'hcs')]) return def register_Ns3OfdmSendParams_methods(root_module, cls): ## send-params.h (module 'wimax'): ns3::OfdmSendParams::OfdmSendParams(ns3::OfdmSendParams const & arg0) [copy constructor] cls.add_constructor([param('ns3::OfdmSendParams const &', 'arg0')]) ## send-params.h (module 'wimax'): ns3::OfdmSendParams::OfdmSendParams(ns3::Ptr<ns3::PacketBurst> burst, uint8_t modulationType, uint8_t direction) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::PacketBurst >', 'burst'), param('uint8_t', 'modulationType'), param('uint8_t', 'direction')]) ## send-params.h (module 'wimax'): ns3::Ptr<ns3::PacketBurst> ns3::OfdmSendParams::GetBurst() const [member function] cls.add_method('GetBurst', 'ns3::Ptr< ns3::PacketBurst >', [], is_const=True) ## send-params.h (module 'wimax'): uint8_t ns3::OfdmSendParams::GetDirection() const [member function] cls.add_method('GetDirection', 'uint8_t', [], is_const=True) ## send-params.h (module 'wimax'): uint8_t ns3::OfdmSendParams::GetModulationType() const [member function] cls.add_method('GetModulationType', 'uint8_t', [], is_const=True) return def register_Ns3OfdmUcdChannelEncodings_methods(root_module, cls): ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUcdChannelEncodings::OfdmUcdChannelEncodings(ns3::OfdmUcdChannelEncodings const & arg0) [copy constructor] cls.add_constructor([param('ns3::OfdmUcdChannelEncodings const &', 'arg0')]) ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUcdChannelEncodings::OfdmUcdChannelEncodings() [constructor] cls.add_constructor([]) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmUcdChannelEncodings::GetSbchnlFocContCodes() const [member function] cls.add_method('GetSbchnlFocContCodes', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::OfdmUcdChannelEncodings::GetSbchnlReqRegionFullParams() const [member function] cls.add_method('GetSbchnlReqRegionFullParams', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint16_t ns3::OfdmUcdChannelEncodings::GetSize() const [member function] cls.add_method('GetSize', 'uint16_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUcdChannelEncodings::SetSbchnlFocContCodes(uint8_t sbchnlFocContCodes) [member function] cls.add_method('SetSbchnlFocContCodes', 'void', [param('uint8_t', 'sbchnlFocContCodes')]) ## ul-mac-messages.h (module 'wimax'): void ns3::OfdmUcdChannelEncodings::SetSbchnlReqRegionFullParams(uint8_t sbchnlReqRegionFullParams) [member function] cls.add_method('SetSbchnlReqRegionFullParams', 'void', [param('uint8_t', 'sbchnlReqRegionFullParams')]) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmUcdChannelEncodings::DoRead(ns3::Buffer::Iterator start) [member function] cls.add_method('DoRead', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], visibility='private', is_virtual=True) ## ul-mac-messages.h (module 'wimax'): ns3::Buffer::Iterator ns3::OfdmUcdChannelEncodings::DoWrite(ns3::Buffer::Iterator start) const [member function] cls.add_method('DoWrite', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3PacketBurst_methods(root_module, cls): ## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst(ns3::PacketBurst const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketBurst const &', 'arg0')]) ## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst() [constructor] cls.add_constructor([]) ## packet-burst.h (module 'network'): void ns3::PacketBurst::AddPacket(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('AddPacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')]) ## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', [], is_const=True) ## packet-burst.h (module 'network'): ns3::Ptr<ns3::PacketBurst> ns3::PacketBurst::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::PacketBurst >', [], is_const=True) ## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', [], is_const=True) ## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## packet-burst.h (module 'network'): std::list<ns3::Ptr<ns3::Packet>, std::allocator<ns3::Ptr<ns3::Packet> > > ns3::PacketBurst::GetPackets() const [member function] cls.add_method('GetPackets', 'std::list< ns3::Ptr< ns3::Packet > >', [], is_const=True) ## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet-burst.h (module 'network'): static ns3::TypeId ns3::PacketBurst::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-burst.h (module 'network'): void ns3::PacketBurst::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3ParetoVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(ns3::ParetoVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::ParetoVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(double m) [constructor] cls.add_constructor([param('double', 'm')]) ## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(double m, double s) [constructor] cls.add_constructor([param('double', 'm'), param('double', 's')]) ## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(double m, double s, double b) [constructor] cls.add_constructor([param('double', 'm'), param('double', 's'), param('double', 'b')]) ## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(std::pair<double,double> params) [constructor] cls.add_constructor([param('std::pair< double, double >', 'params')]) ## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(std::pair<double,double> params, double b) [constructor] cls.add_constructor([param('std::pair< double, double >', 'params'), param('double', 'b')]) return def register_Ns3PcapFileWrapper_methods(root_module, cls): ## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor] cls.add_constructor([]) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::_Ios_Openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Header & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')]) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) return def register_Ns3PortRangeTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRangeTlvValue(ns3::PortRangeTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::PortRangeTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRangeTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): void ns3::PortRangeTlvValue::Add(uint16_t portLow, uint16_t portHigh) [member function] cls.add_method('Add', 'void', [param('uint16_t', 'portLow'), param('uint16_t', 'portHigh')]) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const ns3::PortRangeTlvValue::PortRange*,std::vector<ns3::PortRangeTlvValue::PortRange, std::allocator<ns3::PortRangeTlvValue::PortRange> > > ns3::PortRangeTlvValue::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::PortRangeTlvValue::PortRange const *, std::vector< ns3::PortRangeTlvValue::PortRange > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue * ns3::PortRangeTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::PortRangeTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::PortRangeTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const ns3::PortRangeTlvValue::PortRange*,std::vector<ns3::PortRangeTlvValue::PortRange, std::allocator<ns3::PortRangeTlvValue::PortRange> > > ns3::PortRangeTlvValue::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::PortRangeTlvValue::PortRange const *, std::vector< ns3::PortRangeTlvValue::PortRange > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::PortRangeTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::PortRangeTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3PortRangeTlvValuePortRange_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange::PortRange() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange::PortRange(ns3::PortRangeTlvValue::PortRange const & arg0) [copy constructor] cls.add_constructor([param('ns3::PortRangeTlvValue::PortRange const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange::PortHigh [variable] cls.add_instance_attribute('PortHigh', 'uint16_t', is_const=False) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange::PortLow [variable] cls.add_instance_attribute('PortLow', 'uint16_t', is_const=False) return def register_Ns3PriorityUlJob_methods(root_module, cls): ## ul-job.h (module 'wimax'): ns3::PriorityUlJob::PriorityUlJob(ns3::PriorityUlJob const & arg0) [copy constructor] cls.add_constructor([param('ns3::PriorityUlJob const &', 'arg0')]) ## ul-job.h (module 'wimax'): ns3::PriorityUlJob::PriorityUlJob() [constructor] cls.add_constructor([]) ## ul-job.h (module 'wimax'): int ns3::PriorityUlJob::GetPriority() [member function] cls.add_method('GetPriority', 'int', []) ## ul-job.h (module 'wimax'): ns3::Ptr<ns3::UlJob> ns3::PriorityUlJob::GetUlJob() [member function] cls.add_method('GetUlJob', 'ns3::Ptr< ns3::UlJob >', []) ## ul-job.h (module 'wimax'): void ns3::PriorityUlJob::SetPriority(int priority) [member function] cls.add_method('SetPriority', 'void', [param('int', 'priority')]) ## ul-job.h (module 'wimax'): void ns3::PriorityUlJob::SetUlJob(ns3::Ptr<ns3::UlJob> job) [member function] cls.add_method('SetUlJob', 'void', [param('ns3::Ptr< ns3::UlJob >', 'job')]) return def register_Ns3PropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::PropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::PropagationLossModel::PropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::PropagationLossModel::SetNext(ns3::Ptr<ns3::PropagationLossModel> next) [member function] cls.add_method('SetNext', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'next')]) ## propagation-loss-model.h (module 'propagation'): double ns3::PropagationLossModel::CalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('CalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::PropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3ProtocolTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::ProtocolTlvValue::ProtocolTlvValue(ns3::ProtocolTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ProtocolTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::ProtocolTlvValue::ProtocolTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): void ns3::ProtocolTlvValue::Add(uint8_t protiocol) [member function] cls.add_method('Add', 'void', [param('uint8_t', 'protiocol')]) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const unsigned char*,std::vector<unsigned char, std::allocator<unsigned char> > > ns3::ProtocolTlvValue::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::ProtocolTlvValue * ns3::ProtocolTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::ProtocolTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::ProtocolTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const unsigned char*,std::vector<unsigned char, std::allocator<unsigned char> > > ns3::ProtocolTlvValue::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::ProtocolTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::ProtocolTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3RandomPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::RandomPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::RandomPropagationLossModel::RandomPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): double ns3::RandomPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3RangePropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::RangePropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::RangePropagationLossModel::RangePropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): double ns3::RangePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3RngReq_methods(root_module, cls): ## mac-messages.h (module 'wimax'): ns3::RngReq::RngReq(ns3::RngReq const & arg0) [copy constructor] cls.add_constructor([param('ns3::RngReq const &', 'arg0')]) ## mac-messages.h (module 'wimax'): ns3::RngReq::RngReq() [constructor] cls.add_constructor([]) ## mac-messages.h (module 'wimax'): uint32_t ns3::RngReq::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mac-messages.h (module 'wimax'): ns3::TypeId ns3::RngReq::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): ns3::Mac48Address ns3::RngReq::GetMacAddress() const [member function] cls.add_method('GetMacAddress', 'ns3::Mac48Address', [], is_const=True) ## mac-messages.h (module 'wimax'): std::string ns3::RngReq::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## mac-messages.h (module 'wimax'): uint8_t ns3::RngReq::GetRangingAnomalies() const [member function] cls.add_method('GetRangingAnomalies', 'uint8_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint8_t ns3::RngReq::GetReqDlBurstProfile() const [member function] cls.add_method('GetReqDlBurstProfile', 'uint8_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::RngReq::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): static ns3::TypeId ns3::RngReq::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mac-messages.h (module 'wimax'): void ns3::RngReq::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::RngReq::PrintDebug() const [member function] cls.add_method('PrintDebug', 'void', [], is_const=True) ## mac-messages.h (module 'wimax'): void ns3::RngReq::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::RngReq::SetMacAddress(ns3::Mac48Address macAddress) [member function] cls.add_method('SetMacAddress', 'void', [param('ns3::Mac48Address', 'macAddress')]) ## mac-messages.h (module 'wimax'): void ns3::RngReq::SetRangingAnomalies(uint8_t rangingAnomalies) [member function] cls.add_method('SetRangingAnomalies', 'void', [param('uint8_t', 'rangingAnomalies')]) ## mac-messages.h (module 'wimax'): void ns3::RngReq::SetReqDlBurstProfile(uint8_t reqDlBurstProfile) [member function] cls.add_method('SetReqDlBurstProfile', 'void', [param('uint8_t', 'reqDlBurstProfile')]) return def register_Ns3RngRsp_methods(root_module, cls): ## mac-messages.h (module 'wimax'): ns3::RngRsp::RngRsp(ns3::RngRsp const & arg0) [copy constructor] cls.add_constructor([param('ns3::RngRsp const &', 'arg0')]) ## mac-messages.h (module 'wimax'): ns3::RngRsp::RngRsp() [constructor] cls.add_constructor([]) ## mac-messages.h (module 'wimax'): uint32_t ns3::RngRsp::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mac-messages.h (module 'wimax'): uint8_t ns3::RngRsp::GetAasBdcastPermission() const [member function] cls.add_method('GetAasBdcastPermission', 'uint8_t', [], is_const=True) ## mac-messages.h (module 'wimax'): ns3::Cid ns3::RngRsp::GetBasicCid() const [member function] cls.add_method('GetBasicCid', 'ns3::Cid', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::RngRsp::GetDlFreqOverride() const [member function] cls.add_method('GetDlFreqOverride', 'uint32_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint16_t ns3::RngRsp::GetDlOperBurstProfile() const [member function] cls.add_method('GetDlOperBurstProfile', 'uint16_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::RngRsp::GetFrameNumber() const [member function] cls.add_method('GetFrameNumber', 'uint32_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint8_t ns3::RngRsp::GetInitRangOppNumber() const [member function] cls.add_method('GetInitRangOppNumber', 'uint8_t', [], is_const=True) ## mac-messages.h (module 'wimax'): ns3::TypeId ns3::RngRsp::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): ns3::Mac48Address ns3::RngRsp::GetMacAddress() const [member function] cls.add_method('GetMacAddress', 'ns3::Mac48Address', [], is_const=True) ## mac-messages.h (module 'wimax'): std::string ns3::RngRsp::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::RngRsp::GetOffsetFreqAdjust() const [member function] cls.add_method('GetOffsetFreqAdjust', 'uint32_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint8_t ns3::RngRsp::GetPowerLevelAdjust() const [member function] cls.add_method('GetPowerLevelAdjust', 'uint8_t', [], is_const=True) ## mac-messages.h (module 'wimax'): ns3::Cid ns3::RngRsp::GetPrimaryCid() const [member function] cls.add_method('GetPrimaryCid', 'ns3::Cid', [], is_const=True) ## mac-messages.h (module 'wimax'): uint8_t ns3::RngRsp::GetRangStatus() const [member function] cls.add_method('GetRangStatus', 'uint8_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint8_t ns3::RngRsp::GetRangSubchnl() const [member function] cls.add_method('GetRangSubchnl', 'uint8_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::RngRsp::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::RngRsp::GetTimingAdjust() const [member function] cls.add_method('GetTimingAdjust', 'uint32_t', [], is_const=True) ## mac-messages.h (module 'wimax'): static ns3::TypeId ns3::RngRsp::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mac-messages.h (module 'wimax'): uint8_t ns3::RngRsp::GetUlChnlIdOverride() const [member function] cls.add_method('GetUlChnlIdOverride', 'uint8_t', [], is_const=True) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetAasBdcastPermission(uint8_t aasBdcastPermission) [member function] cls.add_method('SetAasBdcastPermission', 'void', [param('uint8_t', 'aasBdcastPermission')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetBasicCid(ns3::Cid basicCid) [member function] cls.add_method('SetBasicCid', 'void', [param('ns3::Cid', 'basicCid')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetDlFreqOverride(uint32_t dlFreqOverride) [member function] cls.add_method('SetDlFreqOverride', 'void', [param('uint32_t', 'dlFreqOverride')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetDlOperBurstProfile(uint16_t dlOperBurstProfile) [member function] cls.add_method('SetDlOperBurstProfile', 'void', [param('uint16_t', 'dlOperBurstProfile')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetFrameNumber(uint32_t frameNumber) [member function] cls.add_method('SetFrameNumber', 'void', [param('uint32_t', 'frameNumber')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetInitRangOppNumber(uint8_t initRangOppNumber) [member function] cls.add_method('SetInitRangOppNumber', 'void', [param('uint8_t', 'initRangOppNumber')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetMacAddress(ns3::Mac48Address macAddress) [member function] cls.add_method('SetMacAddress', 'void', [param('ns3::Mac48Address', 'macAddress')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetOffsetFreqAdjust(uint32_t offsetFreqAdjust) [member function] cls.add_method('SetOffsetFreqAdjust', 'void', [param('uint32_t', 'offsetFreqAdjust')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetPowerLevelAdjust(uint8_t powerLevelAdjust) [member function] cls.add_method('SetPowerLevelAdjust', 'void', [param('uint8_t', 'powerLevelAdjust')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetPrimaryCid(ns3::Cid primaryCid) [member function] cls.add_method('SetPrimaryCid', 'void', [param('ns3::Cid', 'primaryCid')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetRangStatus(uint8_t rangStatus) [member function] cls.add_method('SetRangStatus', 'void', [param('uint8_t', 'rangStatus')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetRangSubchnl(uint8_t rangSubchnl) [member function] cls.add_method('SetRangSubchnl', 'void', [param('uint8_t', 'rangSubchnl')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetTimingAdjust(uint32_t timingAdjust) [member function] cls.add_method('SetTimingAdjust', 'void', [param('uint32_t', 'timingAdjust')]) ## mac-messages.h (module 'wimax'): void ns3::RngRsp::SetUlChnlIdOverride(uint8_t ulChnlIdOverride) [member function] cls.add_method('SetUlChnlIdOverride', 'void', [param('uint8_t', 'ulChnlIdOverride')]) return def register_Ns3SSManager_methods(root_module, cls): ## ss-manager.h (module 'wimax'): ns3::SSManager::SSManager(ns3::SSManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::SSManager const &', 'arg0')]) ## ss-manager.h (module 'wimax'): ns3::SSManager::SSManager() [constructor] cls.add_constructor([]) ## ss-manager.h (module 'wimax'): ns3::SSRecord * ns3::SSManager::CreateSSRecord(ns3::Mac48Address const & macAddress) [member function] cls.add_method('CreateSSRecord', 'ns3::SSRecord *', [param('ns3::Mac48Address const &', 'macAddress')]) ## ss-manager.h (module 'wimax'): void ns3::SSManager::DeleteSSRecord(ns3::Cid cid) [member function] cls.add_method('DeleteSSRecord', 'void', [param('ns3::Cid', 'cid')]) ## ss-manager.h (module 'wimax'): ns3::Mac48Address ns3::SSManager::GetMacAddress(ns3::Cid cid) const [member function] cls.add_method('GetMacAddress', 'ns3::Mac48Address', [param('ns3::Cid', 'cid')], is_const=True) ## ss-manager.h (module 'wimax'): uint32_t ns3::SSManager::GetNRegisteredSSs() const [member function] cls.add_method('GetNRegisteredSSs', 'uint32_t', [], is_const=True) ## ss-manager.h (module 'wimax'): uint32_t ns3::SSManager::GetNSSs() const [member function] cls.add_method('GetNSSs', 'uint32_t', [], is_const=True) ## ss-manager.h (module 'wimax'): ns3::SSRecord * ns3::SSManager::GetSSRecord(ns3::Mac48Address const & macAddress) const [member function] cls.add_method('GetSSRecord', 'ns3::SSRecord *', [param('ns3::Mac48Address const &', 'macAddress')], is_const=True) ## ss-manager.h (module 'wimax'): ns3::SSRecord * ns3::SSManager::GetSSRecord(ns3::Cid cid) const [member function] cls.add_method('GetSSRecord', 'ns3::SSRecord *', [param('ns3::Cid', 'cid')], is_const=True) ## ss-manager.h (module 'wimax'): std::vector<ns3::SSRecord*,std::allocator<ns3::SSRecord*> > * ns3::SSManager::GetSSRecords() const [member function] cls.add_method('GetSSRecords', 'std::vector< ns3::SSRecord * > *', [], is_const=True) ## ss-manager.h (module 'wimax'): bool ns3::SSManager::IsInRecord(ns3::Mac48Address const & macAddress) const [member function] cls.add_method('IsInRecord', 'bool', [param('ns3::Mac48Address const &', 'macAddress')], is_const=True) ## ss-manager.h (module 'wimax'): bool ns3::SSManager::IsRegistered(ns3::Mac48Address const & macAddress) const [member function] cls.add_method('IsRegistered', 'bool', [param('ns3::Mac48Address const &', 'macAddress')], is_const=True) return def register_Ns3ServiceFlowManager_methods(root_module, cls): ## service-flow-manager.h (module 'wimax'): ns3::ServiceFlowManager::ServiceFlowManager(ns3::ServiceFlowManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::ServiceFlowManager const &', 'arg0')]) ## service-flow-manager.h (module 'wimax'): ns3::ServiceFlowManager::ServiceFlowManager() [constructor] cls.add_constructor([]) ## service-flow-manager.h (module 'wimax'): void ns3::ServiceFlowManager::AddServiceFlow(ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('AddServiceFlow', 'void', [param('ns3::ServiceFlow *', 'serviceFlow')]) ## service-flow-manager.h (module 'wimax'): bool ns3::ServiceFlowManager::AreServiceFlowsAllocated() [member function] cls.add_method('AreServiceFlowsAllocated', 'bool', []) ## service-flow-manager.h (module 'wimax'): bool ns3::ServiceFlowManager::AreServiceFlowsAllocated(std::vector<ns3::ServiceFlow*,std::allocator<ns3::ServiceFlow*> > * serviceFlows) [member function] cls.add_method('AreServiceFlowsAllocated', 'bool', [param('std::vector< ns3::ServiceFlow * > *', 'serviceFlows')]) ## service-flow-manager.h (module 'wimax'): bool ns3::ServiceFlowManager::AreServiceFlowsAllocated(std::vector<ns3::ServiceFlow*,std::allocator<ns3::ServiceFlow*> > serviceFlows) [member function] cls.add_method('AreServiceFlowsAllocated', 'bool', [param('std::vector< ns3::ServiceFlow * >', 'serviceFlows')]) ## service-flow-manager.h (module 'wimax'): ns3::ServiceFlow * ns3::ServiceFlowManager::DoClassify(ns3::Ipv4Address SrcAddress, ns3::Ipv4Address DstAddress, uint16_t SrcPort, uint16_t DstPort, uint8_t Proto, ns3::ServiceFlow::Direction dir) const [member function] cls.add_method('DoClassify', 'ns3::ServiceFlow *', [param('ns3::Ipv4Address', 'SrcAddress'), param('ns3::Ipv4Address', 'DstAddress'), param('uint16_t', 'SrcPort'), param('uint16_t', 'DstPort'), param('uint8_t', 'Proto'), param('ns3::ServiceFlow::Direction', 'dir')], is_const=True) ## service-flow-manager.h (module 'wimax'): void ns3::ServiceFlowManager::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## service-flow-manager.h (module 'wimax'): ns3::ServiceFlow * ns3::ServiceFlowManager::GetNextServiceFlowToAllocate() [member function] cls.add_method('GetNextServiceFlowToAllocate', 'ns3::ServiceFlow *', []) ## service-flow-manager.h (module 'wimax'): uint32_t ns3::ServiceFlowManager::GetNrServiceFlows() const [member function] cls.add_method('GetNrServiceFlows', 'uint32_t', [], is_const=True) ## service-flow-manager.h (module 'wimax'): ns3::ServiceFlow * ns3::ServiceFlowManager::GetServiceFlow(uint32_t sfid) const [member function] cls.add_method('GetServiceFlow', 'ns3::ServiceFlow *', [param('uint32_t', 'sfid')], is_const=True) ## service-flow-manager.h (module 'wimax'): ns3::ServiceFlow * ns3::ServiceFlowManager::GetServiceFlow(ns3::Cid cid) const [member function] cls.add_method('GetServiceFlow', 'ns3::ServiceFlow *', [param('ns3::Cid', 'cid')], is_const=True) ## service-flow-manager.h (module 'wimax'): std::vector<ns3::ServiceFlow*,std::allocator<ns3::ServiceFlow*> > ns3::ServiceFlowManager::GetServiceFlows(ns3::ServiceFlow::SchedulingType schedulingType) const [member function] cls.add_method('GetServiceFlows', 'std::vector< ns3::ServiceFlow * >', [param('ns3::ServiceFlow::SchedulingType', 'schedulingType')], is_const=True) return def register_Ns3SfVectorTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue::SfVectorTlvValue(ns3::SfVectorTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::SfVectorTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue::SfVectorTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue * ns3::SfVectorTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::SfVectorTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::SfVectorTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SsServiceFlowManager_methods(root_module, cls): ## ss-service-flow-manager.h (module 'wimax'): ns3::SsServiceFlowManager::SsServiceFlowManager(ns3::SsServiceFlowManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::SsServiceFlowManager const &', 'arg0')]) ## ss-service-flow-manager.h (module 'wimax'): ns3::SsServiceFlowManager::SsServiceFlowManager(ns3::Ptr<ns3::SubscriberStationNetDevice> device) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::SubscriberStationNetDevice >', 'device')]) ## ss-service-flow-manager.h (module 'wimax'): void ns3::SsServiceFlowManager::AddServiceFlow(ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('AddServiceFlow', 'void', [param('ns3::ServiceFlow *', 'serviceFlow')]) ## ss-service-flow-manager.h (module 'wimax'): void ns3::SsServiceFlowManager::AddServiceFlow(ns3::ServiceFlow serviceFlow) [member function] cls.add_method('AddServiceFlow', 'void', [param('ns3::ServiceFlow', 'serviceFlow')]) ## ss-service-flow-manager.h (module 'wimax'): ns3::Ptr<ns3::Packet> ns3::SsServiceFlowManager::CreateDsaAck() [member function] cls.add_method('CreateDsaAck', 'ns3::Ptr< ns3::Packet >', []) ## ss-service-flow-manager.h (module 'wimax'): ns3::DsaReq ns3::SsServiceFlowManager::CreateDsaReq(ns3::ServiceFlow const * serviceFlow) [member function] cls.add_method('CreateDsaReq', 'ns3::DsaReq', [param('ns3::ServiceFlow const *', 'serviceFlow')]) ## ss-service-flow-manager.h (module 'wimax'): void ns3::SsServiceFlowManager::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## ss-service-flow-manager.h (module 'wimax'): ns3::EventId ns3::SsServiceFlowManager::GetDsaAckTimeoutEvent() const [member function] cls.add_method('GetDsaAckTimeoutEvent', 'ns3::EventId', [], is_const=True) ## ss-service-flow-manager.h (module 'wimax'): ns3::EventId ns3::SsServiceFlowManager::GetDsaRspTimeoutEvent() const [member function] cls.add_method('GetDsaRspTimeoutEvent', 'ns3::EventId', [], is_const=True) ## ss-service-flow-manager.h (module 'wimax'): uint8_t ns3::SsServiceFlowManager::GetMaxDsaReqRetries() const [member function] cls.add_method('GetMaxDsaReqRetries', 'uint8_t', [], is_const=True) ## ss-service-flow-manager.h (module 'wimax'): void ns3::SsServiceFlowManager::InitiateServiceFlows() [member function] cls.add_method('InitiateServiceFlows', 'void', []) ## ss-service-flow-manager.h (module 'wimax'): void ns3::SsServiceFlowManager::ProcessDsaRsp(ns3::DsaRsp const & dsaRsp) [member function] cls.add_method('ProcessDsaRsp', 'void', [param('ns3::DsaRsp const &', 'dsaRsp')]) ## ss-service-flow-manager.h (module 'wimax'): void ns3::SsServiceFlowManager::ScheduleDsaReq(ns3::ServiceFlow const * serviceFlow) [member function] cls.add_method('ScheduleDsaReq', 'void', [param('ns3::ServiceFlow const *', 'serviceFlow')]) ## ss-service-flow-manager.h (module 'wimax'): void ns3::SsServiceFlowManager::SetMaxDsaReqRetries(uint8_t maxDsaReqRetries) [member function] cls.add_method('SetMaxDsaReqRetries', 'void', [param('uint8_t', 'maxDsaReqRetries')]) return def register_Ns3ThreeLogDistancePropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::ThreeLogDistancePropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::ThreeLogDistancePropagationLossModel::ThreeLogDistancePropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): double ns3::ThreeLogDistancePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3Tlv_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::Tlv::Tlv(uint8_t type, uint64_t length, ns3::TlvValue const & value) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint64_t', 'length'), param('ns3::TlvValue const &', 'value')]) ## wimax-tlv.h (module 'wimax'): ns3::Tlv::Tlv() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::Tlv::Tlv(ns3::Tlv const & tlv) [copy constructor] cls.add_constructor([param('ns3::Tlv const &', 'tlv')]) ## wimax-tlv.h (module 'wimax'): ns3::Tlv * ns3::Tlv::Copy() const [member function] cls.add_method('Copy', 'ns3::Tlv *', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::TlvValue * ns3::Tlv::CopyValue() const [member function] cls.add_method('CopyValue', 'ns3::TlvValue *', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::Tlv::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): ns3::TypeId ns3::Tlv::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint64_t ns3::Tlv::GetLength() const [member function] cls.add_method('GetLength', 'uint64_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::Tlv::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::Tlv::GetSizeOfLen() const [member function] cls.add_method('GetSizeOfLen', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::Tlv::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::TlvValue * ns3::Tlv::PeekValue() [member function] cls.add_method('PeekValue', 'ns3::TlvValue *', []) ## wimax-tlv.h (module 'wimax'): void ns3::Tlv::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::Tlv::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TwoRayGroundPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::TwoRayGroundPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::TwoRayGroundPropagationLossModel::TwoRayGroundPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetLambda(double frequency, double speed) [member function] cls.add_method('SetLambda', 'void', [param('double', 'frequency'), param('double', 'speed')]) ## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetLambda(double lambda) [member function] cls.add_method('SetLambda', 'void', [param('double', 'lambda')]) ## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetSystemLoss(double systemLoss) [member function] cls.add_method('SetSystemLoss', 'void', [param('double', 'systemLoss')]) ## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetMinDistance(double minDistance) [member function] cls.add_method('SetMinDistance', 'void', [param('double', 'minDistance')]) ## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetMinDistance() const [member function] cls.add_method('GetMinDistance', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetLambda() const [member function] cls.add_method('GetLambda', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetSystemLoss() const [member function] cls.add_method('GetSystemLoss', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetHeightAboveZ(double heightAboveZ) [member function] cls.add_method('SetHeightAboveZ', 'void', [param('double', 'heightAboveZ')]) ## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3Ucd_methods(root_module, cls): ## ul-mac-messages.h (module 'wimax'): ns3::Ucd::Ucd(ns3::Ucd const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ucd const &', 'arg0')]) ## ul-mac-messages.h (module 'wimax'): ns3::Ucd::Ucd() [constructor] cls.add_constructor([]) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::AddUlBurstProfile(ns3::OfdmUlBurstProfile ulBurstProfile) [member function] cls.add_method('AddUlBurstProfile', 'void', [param('ns3::OfdmUlBurstProfile', 'ulBurstProfile')]) ## ul-mac-messages.h (module 'wimax'): uint32_t ns3::Ucd::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ul-mac-messages.h (module 'wimax'): ns3::OfdmUcdChannelEncodings ns3::Ucd::GetChannelEncodings() const [member function] cls.add_method('GetChannelEncodings', 'ns3::OfdmUcdChannelEncodings', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::Ucd::GetConfigurationChangeCount() const [member function] cls.add_method('GetConfigurationChangeCount', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): ns3::TypeId ns3::Ucd::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ul-mac-messages.h (module 'wimax'): std::string ns3::Ucd::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::Ucd::GetNrUlBurstProfiles() const [member function] cls.add_method('GetNrUlBurstProfiles', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::Ucd::GetRangingBackoffEnd() const [member function] cls.add_method('GetRangingBackoffEnd', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::Ucd::GetRangingBackoffStart() const [member function] cls.add_method('GetRangingBackoffStart', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::Ucd::GetRequestBackoffEnd() const [member function] cls.add_method('GetRequestBackoffEnd', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::Ucd::GetRequestBackoffStart() const [member function] cls.add_method('GetRequestBackoffStart', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint32_t ns3::Ucd::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ul-mac-messages.h (module 'wimax'): static ns3::TypeId ns3::Ucd::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ul-mac-messages.h (module 'wimax'): std::vector<ns3::OfdmUlBurstProfile, std::allocator<ns3::OfdmUlBurstProfile> > ns3::Ucd::GetUlBurstProfiles() const [member function] cls.add_method('GetUlBurstProfiles', 'std::vector< ns3::OfdmUlBurstProfile >', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::SetChannelEncodings(ns3::OfdmUcdChannelEncodings channelEncodings) [member function] cls.add_method('SetChannelEncodings', 'void', [param('ns3::OfdmUcdChannelEncodings', 'channelEncodings')]) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::SetConfigurationChangeCount(uint8_t ucdCount) [member function] cls.add_method('SetConfigurationChangeCount', 'void', [param('uint8_t', 'ucdCount')]) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::SetNrUlBurstProfiles(uint8_t nrUlBurstProfiles) [member function] cls.add_method('SetNrUlBurstProfiles', 'void', [param('uint8_t', 'nrUlBurstProfiles')]) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::SetRangingBackoffEnd(uint8_t rangingBackoffEnd) [member function] cls.add_method('SetRangingBackoffEnd', 'void', [param('uint8_t', 'rangingBackoffEnd')]) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::SetRangingBackoffStart(uint8_t rangingBackoffStart) [member function] cls.add_method('SetRangingBackoffStart', 'void', [param('uint8_t', 'rangingBackoffStart')]) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::SetRequestBackoffEnd(uint8_t requestBackoffEnd) [member function] cls.add_method('SetRequestBackoffEnd', 'void', [param('uint8_t', 'requestBackoffEnd')]) ## ul-mac-messages.h (module 'wimax'): void ns3::Ucd::SetRequestBackoffStart(uint8_t requestBackoffStart) [member function] cls.add_method('SetRequestBackoffStart', 'void', [param('uint8_t', 'requestBackoffStart')]) return def register_Ns3UlJob_methods(root_module, cls): cls.add_binary_comparison_operator('==') ## ul-job.h (module 'wimax'): ns3::UlJob::UlJob(ns3::UlJob const & arg0) [copy constructor] cls.add_constructor([param('ns3::UlJob const &', 'arg0')]) ## ul-job.h (module 'wimax'): ns3::UlJob::UlJob() [constructor] cls.add_constructor([]) ## ul-job.h (module 'wimax'): ns3::Time ns3::UlJob::GetDeadline() [member function] cls.add_method('GetDeadline', 'ns3::Time', []) ## ul-job.h (module 'wimax'): ns3::Time ns3::UlJob::GetPeriod() [member function] cls.add_method('GetPeriod', 'ns3::Time', []) ## ul-job.h (module 'wimax'): ns3::Time ns3::UlJob::GetReleaseTime() [member function] cls.add_method('GetReleaseTime', 'ns3::Time', []) ## ul-job.h (module 'wimax'): ns3::ServiceFlow::SchedulingType ns3::UlJob::GetSchedulingType() [member function] cls.add_method('GetSchedulingType', 'ns3::ServiceFlow::SchedulingType', []) ## ul-job.h (module 'wimax'): ns3::ServiceFlow * ns3::UlJob::GetServiceFlow() [member function] cls.add_method('GetServiceFlow', 'ns3::ServiceFlow *', []) ## ul-job.h (module 'wimax'): uint32_t ns3::UlJob::GetSize() [member function] cls.add_method('GetSize', 'uint32_t', []) ## ul-job.h (module 'wimax'): ns3::SSRecord * ns3::UlJob::GetSsRecord() [member function] cls.add_method('GetSsRecord', 'ns3::SSRecord *', []) ## ul-job.h (module 'wimax'): ns3::ReqType ns3::UlJob::GetType() [member function] cls.add_method('GetType', 'ns3::ReqType', []) ## ul-job.h (module 'wimax'): void ns3::UlJob::SetDeadline(ns3::Time deadline) [member function] cls.add_method('SetDeadline', 'void', [param('ns3::Time', 'deadline')]) ## ul-job.h (module 'wimax'): void ns3::UlJob::SetPeriod(ns3::Time period) [member function] cls.add_method('SetPeriod', 'void', [param('ns3::Time', 'period')]) ## ul-job.h (module 'wimax'): void ns3::UlJob::SetReleaseTime(ns3::Time releaseTime) [member function] cls.add_method('SetReleaseTime', 'void', [param('ns3::Time', 'releaseTime')]) ## ul-job.h (module 'wimax'): void ns3::UlJob::SetSchedulingType(ns3::ServiceFlow::SchedulingType schedulingType) [member function] cls.add_method('SetSchedulingType', 'void', [param('ns3::ServiceFlow::SchedulingType', 'schedulingType')]) ## ul-job.h (module 'wimax'): void ns3::UlJob::SetServiceFlow(ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('SetServiceFlow', 'void', [param('ns3::ServiceFlow *', 'serviceFlow')]) ## ul-job.h (module 'wimax'): void ns3::UlJob::SetSize(uint32_t size) [member function] cls.add_method('SetSize', 'void', [param('uint32_t', 'size')]) ## ul-job.h (module 'wimax'): void ns3::UlJob::SetSsRecord(ns3::SSRecord * ssRecord) [member function] cls.add_method('SetSsRecord', 'void', [param('ns3::SSRecord *', 'ssRecord')]) ## ul-job.h (module 'wimax'): void ns3::UlJob::SetType(ns3::ReqType type) [member function] cls.add_method('SetType', 'void', [param('ns3::ReqType', 'type')]) return def register_Ns3UlMap_methods(root_module, cls): ## ul-mac-messages.h (module 'wimax'): ns3::UlMap::UlMap(ns3::UlMap const & arg0) [copy constructor] cls.add_constructor([param('ns3::UlMap const &', 'arg0')]) ## ul-mac-messages.h (module 'wimax'): ns3::UlMap::UlMap() [constructor] cls.add_constructor([]) ## ul-mac-messages.h (module 'wimax'): void ns3::UlMap::AddUlMapElement(ns3::OfdmUlMapIe ulMapElement) [member function] cls.add_method('AddUlMapElement', 'void', [param('ns3::OfdmUlMapIe', 'ulMapElement')]) ## ul-mac-messages.h (module 'wimax'): uint32_t ns3::UlMap::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ul-mac-messages.h (module 'wimax'): uint32_t ns3::UlMap::GetAllocationStartTime() const [member function] cls.add_method('GetAllocationStartTime', 'uint32_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): ns3::TypeId ns3::UlMap::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ul-mac-messages.h (module 'wimax'): std::string ns3::UlMap::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): uint32_t ns3::UlMap::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ul-mac-messages.h (module 'wimax'): static ns3::TypeId ns3::UlMap::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ul-mac-messages.h (module 'wimax'): uint8_t ns3::UlMap::GetUcdCount() const [member function] cls.add_method('GetUcdCount', 'uint8_t', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): std::list<ns3::OfdmUlMapIe, std::allocator<ns3::OfdmUlMapIe> > ns3::UlMap::GetUlMapElements() const [member function] cls.add_method('GetUlMapElements', 'std::list< ns3::OfdmUlMapIe >', [], is_const=True) ## ul-mac-messages.h (module 'wimax'): void ns3::UlMap::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ul-mac-messages.h (module 'wimax'): void ns3::UlMap::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ul-mac-messages.h (module 'wimax'): void ns3::UlMap::SetAllocationStartTime(uint32_t allocationStartTime) [member function] cls.add_method('SetAllocationStartTime', 'void', [param('uint32_t', 'allocationStartTime')]) ## ul-mac-messages.h (module 'wimax'): void ns3::UlMap::SetUcdCount(uint8_t ucdCount) [member function] cls.add_method('SetUcdCount', 'void', [param('uint8_t', 'ucdCount')]) return def register_Ns3UplinkScheduler_methods(root_module, cls): ## bs-uplink-scheduler.h (module 'wimax'): ns3::UplinkScheduler::UplinkScheduler(ns3::UplinkScheduler const & arg0) [copy constructor] cls.add_constructor([param('ns3::UplinkScheduler const &', 'arg0')]) ## bs-uplink-scheduler.h (module 'wimax'): ns3::UplinkScheduler::UplinkScheduler() [constructor] cls.add_constructor([]) ## bs-uplink-scheduler.h (module 'wimax'): ns3::UplinkScheduler::UplinkScheduler(ns3::Ptr<ns3::BaseStationNetDevice> bs) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::BaseStationNetDevice >', 'bs')]) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::AddUplinkAllocation(ns3::OfdmUlMapIe & ulMapIe, uint32_t const & allocationSize, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('AddUplinkAllocation', 'void', [param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('uint32_t const &', 'allocationSize'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::AllocateInitialRangingInterval(uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('AllocateInitialRangingInterval', 'void', [param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): uint32_t ns3::UplinkScheduler::CalculateAllocationStartTime() [member function] cls.add_method('CalculateAllocationStartTime', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): ns3::Ptr<ns3::BaseStationNetDevice> ns3::UplinkScheduler::GetBs() [member function] cls.add_method('GetBs', 'ns3::Ptr< ns3::BaseStationNetDevice >', [], is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::GetChannelDescriptorsToUpdate(bool & arg0, bool & arg1, bool & arg2, bool & arg3) [member function] cls.add_method('GetChannelDescriptorsToUpdate', 'void', [param('bool &', 'arg0'), param('bool &', 'arg1'), param('bool &', 'arg2'), param('bool &', 'arg3')], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): ns3::Time ns3::UplinkScheduler::GetDcdTimeStamp() const [member function] cls.add_method('GetDcdTimeStamp', 'ns3::Time', [], is_const=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): bool ns3::UplinkScheduler::GetIsInvIrIntrvlAllocated() const [member function] cls.add_method('GetIsInvIrIntrvlAllocated', 'bool', [], is_const=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): bool ns3::UplinkScheduler::GetIsIrIntrvlAllocated() const [member function] cls.add_method('GetIsIrIntrvlAllocated', 'bool', [], is_const=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): uint8_t ns3::UplinkScheduler::GetNrIrOppsAllocated() const [member function] cls.add_method('GetNrIrOppsAllocated', 'uint8_t', [], is_const=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): ns3::Time ns3::UplinkScheduler::GetTimeStampIrInterval() [member function] cls.add_method('GetTimeStampIrInterval', 'ns3::Time', [], is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): static ns3::TypeId ns3::UplinkScheduler::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bs-uplink-scheduler.h (module 'wimax'): ns3::Time ns3::UplinkScheduler::GetUcdTimeStamp() const [member function] cls.add_method('GetUcdTimeStamp', 'ns3::Time', [], is_const=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): std::list<ns3::OfdmUlMapIe, std::allocator<ns3::OfdmUlMapIe> > ns3::UplinkScheduler::GetUplinkAllocations() const [member function] cls.add_method('GetUplinkAllocations', 'std::list< ns3::OfdmUlMapIe >', [], is_const=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::InitOnce() [member function] cls.add_method('InitOnce', 'void', [], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::OnSetRequestedBandwidth(ns3::ServiceFlowRecord * sfr) [member function] cls.add_method('OnSetRequestedBandwidth', 'void', [param('ns3::ServiceFlowRecord *', 'sfr')], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::ProcessBandwidthRequest(ns3::BandwidthRequestHeader const & bwRequestHdr) [member function] cls.add_method('ProcessBandwidthRequest', 'void', [param('ns3::BandwidthRequestHeader const &', 'bwRequestHdr')], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::Schedule() [member function] cls.add_method('Schedule', 'void', [], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::ServiceBandwidthRequests(ns3::SSRecord const * ssRecord, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceBandwidthRequests', 'void', [param('ns3::SSRecord const *', 'ssRecord'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): bool ns3::UplinkScheduler::ServiceBandwidthRequests(ns3::ServiceFlow * serviceFlow, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceBandwidthRequests', 'bool', [param('ns3::ServiceFlow *', 'serviceFlow'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::ServiceUnsolicitedGrants(ns3::SSRecord const * ssRecord, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceUnsolicitedGrants', 'void', [param('ns3::SSRecord const *', 'ssRecord'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_pure_virtual=True, is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::SetBs(ns3::Ptr<ns3::BaseStationNetDevice> bs) [member function] cls.add_method('SetBs', 'void', [param('ns3::Ptr< ns3::BaseStationNetDevice >', 'bs')], is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::SetDcdTimeStamp(ns3::Time dcdTimeStamp) [member function] cls.add_method('SetDcdTimeStamp', 'void', [param('ns3::Time', 'dcdTimeStamp')], is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::SetIsInvIrIntrvlAllocated(bool isInvIrIntrvlAllocated) [member function] cls.add_method('SetIsInvIrIntrvlAllocated', 'void', [param('bool', 'isInvIrIntrvlAllocated')], is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::SetIsIrIntrvlAllocated(bool isIrIntrvlAllocated) [member function] cls.add_method('SetIsIrIntrvlAllocated', 'void', [param('bool', 'isIrIntrvlAllocated')], is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::SetNrIrOppsAllocated(uint8_t nrIrOppsAllocated) [member function] cls.add_method('SetNrIrOppsAllocated', 'void', [param('uint8_t', 'nrIrOppsAllocated')], is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::SetTimeStampIrInterval(ns3::Time timeStampIrInterval) [member function] cls.add_method('SetTimeStampIrInterval', 'void', [param('ns3::Time', 'timeStampIrInterval')], is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::SetUcdTimeStamp(ns3::Time ucdTimeStamp) [member function] cls.add_method('SetUcdTimeStamp', 'void', [param('ns3::Time', 'ucdTimeStamp')], is_virtual=True) ## bs-uplink-scheduler.h (module 'wimax'): void ns3::UplinkScheduler::SetupServiceFlow(ns3::SSRecord * ssRecord, ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('SetupServiceFlow', 'void', [param('ns3::SSRecord *', 'ssRecord'), param('ns3::ServiceFlow *', 'serviceFlow')], is_pure_virtual=True, is_virtual=True) return def register_Ns3UplinkSchedulerMBQoS_methods(root_module, cls): ## bs-uplink-scheduler-mbqos.h (module 'wimax'): ns3::UplinkSchedulerMBQoS::UplinkSchedulerMBQoS(ns3::UplinkSchedulerMBQoS const & arg0) [copy constructor] cls.add_constructor([param('ns3::UplinkSchedulerMBQoS const &', 'arg0')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): ns3::UplinkSchedulerMBQoS::UplinkSchedulerMBQoS() [constructor] cls.add_constructor([]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): ns3::UplinkSchedulerMBQoS::UplinkSchedulerMBQoS(ns3::Time time) [constructor] cls.add_constructor([param('ns3::Time', 'time')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::AddUplinkAllocation(ns3::OfdmUlMapIe & ulMapIe, uint32_t const & allocationSize, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('AddUplinkAllocation', 'void', [param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('uint32_t const &', 'allocationSize'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::AllocateInitialRangingInterval(uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('AllocateInitialRangingInterval', 'void', [param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): uint32_t ns3::UplinkSchedulerMBQoS::CalculateAllocationStartTime() [member function] cls.add_method('CalculateAllocationStartTime', 'uint32_t', [], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::CheckDeadline(uint32_t & availableSymbols) [member function] cls.add_method('CheckDeadline', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::CheckMinimumBandwidth(uint32_t & availableSymbols) [member function] cls.add_method('CheckMinimumBandwidth', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): uint32_t ns3::UplinkSchedulerMBQoS::CountSymbolsJobs(ns3::Ptr<ns3::UlJob> job) [member function] cls.add_method('CountSymbolsJobs', 'uint32_t', [param('ns3::Ptr< ns3::UlJob >', 'job')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): uint32_t ns3::UplinkSchedulerMBQoS::CountSymbolsQueue(std::list<ns3::Ptr<ns3::UlJob>, std::allocator<ns3::Ptr<ns3::UlJob> > > jobs) [member function] cls.add_method('CountSymbolsQueue', 'uint32_t', [param('std::list< ns3::Ptr< ns3::UlJob > >', 'jobs')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): ns3::Ptr<ns3::UlJob> ns3::UplinkSchedulerMBQoS::CreateUlJob(ns3::SSRecord * ssRecord, ns3::ServiceFlow::SchedulingType schedType, ns3::ReqType reqType) [member function] cls.add_method('CreateUlJob', 'ns3::Ptr< ns3::UlJob >', [param('ns3::SSRecord *', 'ssRecord'), param('ns3::ServiceFlow::SchedulingType', 'schedType'), param('ns3::ReqType', 'reqType')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): ns3::Ptr<ns3::UlJob> ns3::UplinkSchedulerMBQoS::DequeueJob(ns3::UlJob::JobPriority priority) [member function] cls.add_method('DequeueJob', 'ns3::Ptr< ns3::UlJob >', [param('ns3::UlJob::JobPriority', 'priority')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): ns3::Time ns3::UplinkSchedulerMBQoS::DetermineDeadline(ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('DetermineDeadline', 'ns3::Time', [param('ns3::ServiceFlow *', 'serviceFlow')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::EnqueueJob(ns3::UlJob::JobPriority priority, ns3::Ptr<ns3::UlJob> job) [member function] cls.add_method('EnqueueJob', 'void', [param('ns3::UlJob::JobPriority', 'priority'), param('ns3::Ptr< ns3::UlJob >', 'job')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::GetChannelDescriptorsToUpdate(bool & arg0, bool & arg1, bool & arg2, bool & arg3) [member function] cls.add_method('GetChannelDescriptorsToUpdate', 'void', [param('bool &', 'arg0'), param('bool &', 'arg1'), param('bool &', 'arg2'), param('bool &', 'arg3')], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): uint32_t ns3::UplinkSchedulerMBQoS::GetPendingSize(ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('GetPendingSize', 'uint32_t', [param('ns3::ServiceFlow *', 'serviceFlow')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): static ns3::TypeId ns3::UplinkSchedulerMBQoS::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): std::list<ns3::OfdmUlMapIe, std::allocator<ns3::OfdmUlMapIe> > ns3::UplinkSchedulerMBQoS::GetUplinkAllocations() const [member function] cls.add_method('GetUplinkAllocations', 'std::list< ns3::OfdmUlMapIe >', [], is_const=True, is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::InitOnce() [member function] cls.add_method('InitOnce', 'void', [], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::OnSetRequestedBandwidth(ns3::ServiceFlowRecord * sfr) [member function] cls.add_method('OnSetRequestedBandwidth', 'void', [param('ns3::ServiceFlowRecord *', 'sfr')], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::ProcessBandwidthRequest(ns3::BandwidthRequestHeader const & bwRequestHdr) [member function] cls.add_method('ProcessBandwidthRequest', 'void', [param('ns3::BandwidthRequestHeader const &', 'bwRequestHdr')], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::Schedule() [member function] cls.add_method('Schedule', 'void', [], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::ServiceBandwidthRequests(ns3::SSRecord const * ssRecord, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceBandwidthRequests', 'void', [param('ns3::SSRecord const *', 'ssRecord'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): bool ns3::UplinkSchedulerMBQoS::ServiceBandwidthRequests(ns3::ServiceFlow * serviceFlow, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceBandwidthRequests', 'bool', [param('ns3::ServiceFlow *', 'serviceFlow'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): bool ns3::UplinkSchedulerMBQoS::ServiceBandwidthRequestsBytes(ns3::ServiceFlow * serviceFlow, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols, uint32_t allocationSizeBytes) [member function] cls.add_method('ServiceBandwidthRequestsBytes', 'bool', [param('ns3::ServiceFlow *', 'serviceFlow'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols'), param('uint32_t', 'allocationSizeBytes')]) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::ServiceUnsolicitedGrants(ns3::SSRecord const * ssRecord, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceUnsolicitedGrants', 'void', [param('ns3::SSRecord const *', 'ssRecord'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::SetupServiceFlow(ns3::SSRecord * ssRecord, ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('SetupServiceFlow', 'void', [param('ns3::SSRecord *', 'ssRecord'), param('ns3::ServiceFlow *', 'serviceFlow')], is_virtual=True) ## bs-uplink-scheduler-mbqos.h (module 'wimax'): void ns3::UplinkSchedulerMBQoS::UplinkSchedWindowTimer() [member function] cls.add_method('UplinkSchedWindowTimer', 'void', []) return def register_Ns3UplinkSchedulerRtps_methods(root_module, cls): ## bs-uplink-scheduler-rtps.h (module 'wimax'): ns3::UplinkSchedulerRtps::UplinkSchedulerRtps(ns3::UplinkSchedulerRtps const & arg0) [copy constructor] cls.add_constructor([param('ns3::UplinkSchedulerRtps const &', 'arg0')]) ## bs-uplink-scheduler-rtps.h (module 'wimax'): ns3::UplinkSchedulerRtps::UplinkSchedulerRtps() [constructor] cls.add_constructor([]) ## bs-uplink-scheduler-rtps.h (module 'wimax'): ns3::UplinkSchedulerRtps::UplinkSchedulerRtps(ns3::Ptr<ns3::BaseStationNetDevice> bs) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::BaseStationNetDevice >', 'bs')]) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::AddUplinkAllocation(ns3::OfdmUlMapIe & ulMapIe, uint32_t const & allocationSize, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('AddUplinkAllocation', 'void', [param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('uint32_t const &', 'allocationSize'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::AllocateInitialRangingInterval(uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('AllocateInitialRangingInterval', 'void', [param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): uint32_t ns3::UplinkSchedulerRtps::CalculateAllocationStartTime() [member function] cls.add_method('CalculateAllocationStartTime', 'uint32_t', [], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::GetChannelDescriptorsToUpdate(bool & arg0, bool & arg1, bool & arg2, bool & arg3) [member function] cls.add_method('GetChannelDescriptorsToUpdate', 'void', [param('bool &', 'arg0'), param('bool &', 'arg1'), param('bool &', 'arg2'), param('bool &', 'arg3')], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): static ns3::TypeId ns3::UplinkSchedulerRtps::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): std::list<ns3::OfdmUlMapIe, std::allocator<ns3::OfdmUlMapIe> > ns3::UplinkSchedulerRtps::GetUplinkAllocations() const [member function] cls.add_method('GetUplinkAllocations', 'std::list< ns3::OfdmUlMapIe >', [], is_const=True, is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::InitOnce() [member function] cls.add_method('InitOnce', 'void', [], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::OnSetRequestedBandwidth(ns3::ServiceFlowRecord * sfr) [member function] cls.add_method('OnSetRequestedBandwidth', 'void', [param('ns3::ServiceFlowRecord *', 'sfr')], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::ProcessBandwidthRequest(ns3::BandwidthRequestHeader const & bwRequestHdr) [member function] cls.add_method('ProcessBandwidthRequest', 'void', [param('ns3::BandwidthRequestHeader const &', 'bwRequestHdr')], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::Schedule() [member function] cls.add_method('Schedule', 'void', [], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::ServiceBandwidthRequests(ns3::SSRecord const * ssRecord, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceBandwidthRequests', 'void', [param('ns3::SSRecord const *', 'ssRecord'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): bool ns3::UplinkSchedulerRtps::ServiceBandwidthRequests(ns3::ServiceFlow * serviceFlow, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceBandwidthRequests', 'bool', [param('ns3::ServiceFlow *', 'serviceFlow'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::ServiceUnsolicitedGrants(ns3::SSRecord const * ssRecord, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceUnsolicitedGrants', 'void', [param('ns3::SSRecord const *', 'ssRecord'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::SetupServiceFlow(ns3::SSRecord * ssRecord, ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('SetupServiceFlow', 'void', [param('ns3::SSRecord *', 'ssRecord'), param('ns3::ServiceFlow *', 'serviceFlow')], is_virtual=True) ## bs-uplink-scheduler-rtps.h (module 'wimax'): void ns3::UplinkSchedulerRtps::ULSchedulerRTPSConnection(uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ULSchedulerRTPSConnection', 'void', [param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')]) return def register_Ns3UplinkSchedulerSimple_methods(root_module, cls): ## bs-uplink-scheduler-simple.h (module 'wimax'): ns3::UplinkSchedulerSimple::UplinkSchedulerSimple(ns3::UplinkSchedulerSimple const & arg0) [copy constructor] cls.add_constructor([param('ns3::UplinkSchedulerSimple const &', 'arg0')]) ## bs-uplink-scheduler-simple.h (module 'wimax'): ns3::UplinkSchedulerSimple::UplinkSchedulerSimple() [constructor] cls.add_constructor([]) ## bs-uplink-scheduler-simple.h (module 'wimax'): ns3::UplinkSchedulerSimple::UplinkSchedulerSimple(ns3::Ptr<ns3::BaseStationNetDevice> bs) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::BaseStationNetDevice >', 'bs')]) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::AddUplinkAllocation(ns3::OfdmUlMapIe & ulMapIe, uint32_t const & allocationSize, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('AddUplinkAllocation', 'void', [param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('uint32_t const &', 'allocationSize'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::AllocateInitialRangingInterval(uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('AllocateInitialRangingInterval', 'void', [param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): uint32_t ns3::UplinkSchedulerSimple::CalculateAllocationStartTime() [member function] cls.add_method('CalculateAllocationStartTime', 'uint32_t', [], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::GetChannelDescriptorsToUpdate(bool & arg0, bool & arg1, bool & arg2, bool & arg3) [member function] cls.add_method('GetChannelDescriptorsToUpdate', 'void', [param('bool &', 'arg0'), param('bool &', 'arg1'), param('bool &', 'arg2'), param('bool &', 'arg3')], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): static ns3::TypeId ns3::UplinkSchedulerSimple::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): std::list<ns3::OfdmUlMapIe, std::allocator<ns3::OfdmUlMapIe> > ns3::UplinkSchedulerSimple::GetUplinkAllocations() const [member function] cls.add_method('GetUplinkAllocations', 'std::list< ns3::OfdmUlMapIe >', [], is_const=True, is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::InitOnce() [member function] cls.add_method('InitOnce', 'void', [], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::OnSetRequestedBandwidth(ns3::ServiceFlowRecord * sfr) [member function] cls.add_method('OnSetRequestedBandwidth', 'void', [param('ns3::ServiceFlowRecord *', 'sfr')], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::ProcessBandwidthRequest(ns3::BandwidthRequestHeader const & bwRequestHdr) [member function] cls.add_method('ProcessBandwidthRequest', 'void', [param('ns3::BandwidthRequestHeader const &', 'bwRequestHdr')], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::Schedule() [member function] cls.add_method('Schedule', 'void', [], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::ServiceBandwidthRequests(ns3::SSRecord const * ssRecord, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceBandwidthRequests', 'void', [param('ns3::SSRecord const *', 'ssRecord'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): bool ns3::UplinkSchedulerSimple::ServiceBandwidthRequests(ns3::ServiceFlow * serviceFlow, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceBandwidthRequests', 'bool', [param('ns3::ServiceFlow *', 'serviceFlow'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::ServiceUnsolicitedGrants(ns3::SSRecord const * ssRecord, ns3::ServiceFlow::SchedulingType schedulingType, ns3::OfdmUlMapIe & ulMapIe, ns3::WimaxPhy::ModulationType const modulationType, uint32_t & symbolsToAllocation, uint32_t & availableSymbols) [member function] cls.add_method('ServiceUnsolicitedGrants', 'void', [param('ns3::SSRecord const *', 'ssRecord'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType'), param('ns3::OfdmUlMapIe &', 'ulMapIe'), param('ns3::WimaxPhy::ModulationType const', 'modulationType'), param('uint32_t &', 'symbolsToAllocation'), param('uint32_t &', 'availableSymbols')], is_virtual=True) ## bs-uplink-scheduler-simple.h (module 'wimax'): void ns3::UplinkSchedulerSimple::SetupServiceFlow(ns3::SSRecord * ssRecord, ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('SetupServiceFlow', 'void', [param('ns3::SSRecord *', 'ssRecord'), param('ns3::ServiceFlow *', 'serviceFlow')], is_virtual=True) return def register_Ns3WimaxConnection_methods(root_module, cls): ## wimax-connection.h (module 'wimax'): ns3::WimaxConnection::WimaxConnection(ns3::WimaxConnection const & arg0) [copy constructor] cls.add_constructor([param('ns3::WimaxConnection const &', 'arg0')]) ## wimax-connection.h (module 'wimax'): ns3::WimaxConnection::WimaxConnection(ns3::Cid cid, ns3::Cid::Type type) [constructor] cls.add_constructor([param('ns3::Cid', 'cid'), param('ns3::Cid::Type', 'type')]) ## wimax-connection.h (module 'wimax'): void ns3::WimaxConnection::ClearFragmentsQueue() [member function] cls.add_method('ClearFragmentsQueue', 'void', []) ## wimax-connection.h (module 'wimax'): ns3::Ptr<ns3::Packet> ns3::WimaxConnection::Dequeue(ns3::MacHeaderType::HeaderType packetType=::ns3::MacHeaderType::HEADER_TYPE_GENERIC) [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', [param('ns3::MacHeaderType::HeaderType', 'packetType', default_value='::ns3::MacHeaderType::HEADER_TYPE_GENERIC')]) ## wimax-connection.h (module 'wimax'): ns3::Ptr<ns3::Packet> ns3::WimaxConnection::Dequeue(ns3::MacHeaderType::HeaderType packetType, uint32_t availableByte) [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', [param('ns3::MacHeaderType::HeaderType', 'packetType'), param('uint32_t', 'availableByte')]) ## wimax-connection.h (module 'wimax'): bool ns3::WimaxConnection::Enqueue(ns3::Ptr<ns3::Packet> packet, ns3::MacHeaderType const & hdrType, ns3::GenericMacHeader const & hdr) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::MacHeaderType const &', 'hdrType'), param('ns3::GenericMacHeader const &', 'hdr')]) ## wimax-connection.h (module 'wimax'): void ns3::WimaxConnection::FragmentEnqueue(ns3::Ptr<const ns3::Packet> fragment) [member function] cls.add_method('FragmentEnqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'fragment')]) ## wimax-connection.h (module 'wimax'): ns3::Cid ns3::WimaxConnection::GetCid() const [member function] cls.add_method('GetCid', 'ns3::Cid', [], is_const=True) ## wimax-connection.h (module 'wimax'): std::list<ns3::Ptr<ns3::Packet const>, std::allocator<ns3::Ptr<ns3::Packet const> > > const ns3::WimaxConnection::GetFragmentsQueue() const [member function] cls.add_method('GetFragmentsQueue', 'std::list< ns3::Ptr< ns3::Packet const > > const', [], is_const=True) ## wimax-connection.h (module 'wimax'): ns3::Ptr<ns3::WimaxMacQueue> ns3::WimaxConnection::GetQueue() const [member function] cls.add_method('GetQueue', 'ns3::Ptr< ns3::WimaxMacQueue >', [], is_const=True) ## wimax-connection.h (module 'wimax'): uint8_t ns3::WimaxConnection::GetSchedulingType() const [member function] cls.add_method('GetSchedulingType', 'uint8_t', [], is_const=True) ## wimax-connection.h (module 'wimax'): ns3::ServiceFlow * ns3::WimaxConnection::GetServiceFlow() const [member function] cls.add_method('GetServiceFlow', 'ns3::ServiceFlow *', [], is_const=True) ## wimax-connection.h (module 'wimax'): ns3::Cid::Type ns3::WimaxConnection::GetType() const [member function] cls.add_method('GetType', 'ns3::Cid::Type', [], is_const=True) ## wimax-connection.h (module 'wimax'): static ns3::TypeId ns3::WimaxConnection::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-connection.h (module 'wimax'): std::string ns3::WimaxConnection::GetTypeStr() const [member function] cls.add_method('GetTypeStr', 'std::string', [], is_const=True) ## wimax-connection.h (module 'wimax'): bool ns3::WimaxConnection::HasPackets() const [member function] cls.add_method('HasPackets', 'bool', [], is_const=True) ## wimax-connection.h (module 'wimax'): bool ns3::WimaxConnection::HasPackets(ns3::MacHeaderType::HeaderType packetType) const [member function] cls.add_method('HasPackets', 'bool', [param('ns3::MacHeaderType::HeaderType', 'packetType')], is_const=True) ## wimax-connection.h (module 'wimax'): void ns3::WimaxConnection::SetServiceFlow(ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('SetServiceFlow', 'void', [param('ns3::ServiceFlow *', 'serviceFlow')]) ## wimax-connection.h (module 'wimax'): void ns3::WimaxConnection::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3WimaxMacQueue_methods(root_module, cls): ## wimax-mac-queue.h (module 'wimax'): ns3::WimaxMacQueue::WimaxMacQueue(ns3::WimaxMacQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::WimaxMacQueue const &', 'arg0')]) ## wimax-mac-queue.h (module 'wimax'): ns3::WimaxMacQueue::WimaxMacQueue() [constructor] cls.add_constructor([]) ## wimax-mac-queue.h (module 'wimax'): ns3::WimaxMacQueue::WimaxMacQueue(uint32_t maxSize) [constructor] cls.add_constructor([param('uint32_t', 'maxSize')]) ## wimax-mac-queue.h (module 'wimax'): bool ns3::WimaxMacQueue::CheckForFragmentation(ns3::MacHeaderType::HeaderType packetType) [member function] cls.add_method('CheckForFragmentation', 'bool', [param('ns3::MacHeaderType::HeaderType', 'packetType')]) ## wimax-mac-queue.h (module 'wimax'): ns3::Ptr<ns3::Packet> ns3::WimaxMacQueue::Dequeue(ns3::MacHeaderType::HeaderType packetType) [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', [param('ns3::MacHeaderType::HeaderType', 'packetType')]) ## wimax-mac-queue.h (module 'wimax'): ns3::Ptr<ns3::Packet> ns3::WimaxMacQueue::Dequeue(ns3::MacHeaderType::HeaderType packetType, uint32_t availableByte) [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', [param('ns3::MacHeaderType::HeaderType', 'packetType'), param('uint32_t', 'availableByte')]) ## wimax-mac-queue.h (module 'wimax'): bool ns3::WimaxMacQueue::Enqueue(ns3::Ptr<ns3::Packet> packet, ns3::MacHeaderType const & hdrType, ns3::GenericMacHeader const & hdr) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::MacHeaderType const &', 'hdrType'), param('ns3::GenericMacHeader const &', 'hdr')]) ## wimax-mac-queue.h (module 'wimax'): uint32_t ns3::WimaxMacQueue::GetFirstPacketHdrSize(ns3::MacHeaderType::HeaderType packetType) [member function] cls.add_method('GetFirstPacketHdrSize', 'uint32_t', [param('ns3::MacHeaderType::HeaderType', 'packetType')]) ## wimax-mac-queue.h (module 'wimax'): uint32_t ns3::WimaxMacQueue::GetFirstPacketPayloadSize(ns3::MacHeaderType::HeaderType packetType) [member function] cls.add_method('GetFirstPacketPayloadSize', 'uint32_t', [param('ns3::MacHeaderType::HeaderType', 'packetType')]) ## wimax-mac-queue.h (module 'wimax'): uint32_t ns3::WimaxMacQueue::GetFirstPacketRequiredByte(ns3::MacHeaderType::HeaderType packetType) [member function] cls.add_method('GetFirstPacketRequiredByte', 'uint32_t', [param('ns3::MacHeaderType::HeaderType', 'packetType')]) ## wimax-mac-queue.h (module 'wimax'): uint32_t ns3::WimaxMacQueue::GetMaxSize() const [member function] cls.add_method('GetMaxSize', 'uint32_t', [], is_const=True) ## wimax-mac-queue.h (module 'wimax'): uint32_t ns3::WimaxMacQueue::GetNBytes() const [member function] cls.add_method('GetNBytes', 'uint32_t', [], is_const=True) ## wimax-mac-queue.h (module 'wimax'): std::deque<ns3::WimaxMacQueue::QueueElement, std::allocator<ns3::WimaxMacQueue::QueueElement> > const & ns3::WimaxMacQueue::GetPacketQueue() const [member function] cls.add_method('GetPacketQueue', 'std::deque< ns3::WimaxMacQueue::QueueElement > const &', [], is_const=True) ## wimax-mac-queue.h (module 'wimax'): uint32_t ns3::WimaxMacQueue::GetQueueLengthWithMACOverhead() [member function] cls.add_method('GetQueueLengthWithMACOverhead', 'uint32_t', []) ## wimax-mac-queue.h (module 'wimax'): uint32_t ns3::WimaxMacQueue::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## wimax-mac-queue.h (module 'wimax'): static ns3::TypeId ns3::WimaxMacQueue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-mac-queue.h (module 'wimax'): bool ns3::WimaxMacQueue::IsEmpty() const [member function] cls.add_method('IsEmpty', 'bool', [], is_const=True) ## wimax-mac-queue.h (module 'wimax'): bool ns3::WimaxMacQueue::IsEmpty(ns3::MacHeaderType::HeaderType packetType) const [member function] cls.add_method('IsEmpty', 'bool', [param('ns3::MacHeaderType::HeaderType', 'packetType')], is_const=True) ## wimax-mac-queue.h (module 'wimax'): ns3::Ptr<ns3::Packet> ns3::WimaxMacQueue::Peek(ns3::GenericMacHeader & hdr) const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet >', [param('ns3::GenericMacHeader &', 'hdr')], is_const=True) ## wimax-mac-queue.h (module 'wimax'): ns3::Ptr<ns3::Packet> ns3::WimaxMacQueue::Peek(ns3::GenericMacHeader & hdr, ns3::Time & timeStamp) const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet >', [param('ns3::GenericMacHeader &', 'hdr'), param('ns3::Time &', 'timeStamp')], is_const=True) ## wimax-mac-queue.h (module 'wimax'): ns3::Ptr<ns3::Packet> ns3::WimaxMacQueue::Peek(ns3::MacHeaderType::HeaderType packetType) const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet >', [param('ns3::MacHeaderType::HeaderType', 'packetType')], is_const=True) ## wimax-mac-queue.h (module 'wimax'): ns3::Ptr<ns3::Packet> ns3::WimaxMacQueue::Peek(ns3::MacHeaderType::HeaderType packetType, ns3::Time & timeStamp) const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet >', [param('ns3::MacHeaderType::HeaderType', 'packetType'), param('ns3::Time &', 'timeStamp')], is_const=True) ## wimax-mac-queue.h (module 'wimax'): void ns3::WimaxMacQueue::SetFragmentNumber(ns3::MacHeaderType::HeaderType packetType) [member function] cls.add_method('SetFragmentNumber', 'void', [param('ns3::MacHeaderType::HeaderType', 'packetType')]) ## wimax-mac-queue.h (module 'wimax'): void ns3::WimaxMacQueue::SetFragmentOffset(ns3::MacHeaderType::HeaderType packetType, uint32_t offset) [member function] cls.add_method('SetFragmentOffset', 'void', [param('ns3::MacHeaderType::HeaderType', 'packetType'), param('uint32_t', 'offset')]) ## wimax-mac-queue.h (module 'wimax'): void ns3::WimaxMacQueue::SetFragmentation(ns3::MacHeaderType::HeaderType packetType) [member function] cls.add_method('SetFragmentation', 'void', [param('ns3::MacHeaderType::HeaderType', 'packetType')]) ## wimax-mac-queue.h (module 'wimax'): void ns3::WimaxMacQueue::SetMaxSize(uint32_t maxSize) [member function] cls.add_method('SetMaxSize', 'void', [param('uint32_t', 'maxSize')]) return def register_Ns3WimaxMacToMacHeader_methods(root_module, cls): ## wimax-mac-to-mac-header.h (module 'wimax'): ns3::WimaxMacToMacHeader::WimaxMacToMacHeader(ns3::WimaxMacToMacHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::WimaxMacToMacHeader const &', 'arg0')]) ## wimax-mac-to-mac-header.h (module 'wimax'): ns3::WimaxMacToMacHeader::WimaxMacToMacHeader() [constructor] cls.add_constructor([]) ## wimax-mac-to-mac-header.h (module 'wimax'): ns3::WimaxMacToMacHeader::WimaxMacToMacHeader(uint32_t len) [constructor] cls.add_constructor([param('uint32_t', 'len')]) ## wimax-mac-to-mac-header.h (module 'wimax'): uint32_t ns3::WimaxMacToMacHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wimax-mac-to-mac-header.h (module 'wimax'): ns3::TypeId ns3::WimaxMacToMacHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wimax-mac-to-mac-header.h (module 'wimax'): uint32_t ns3::WimaxMacToMacHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-mac-to-mac-header.h (module 'wimax'): uint8_t ns3::WimaxMacToMacHeader::GetSizeOfLen() const [member function] cls.add_method('GetSizeOfLen', 'uint8_t', [], is_const=True) ## wimax-mac-to-mac-header.h (module 'wimax'): static ns3::TypeId ns3::WimaxMacToMacHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-mac-to-mac-header.h (module 'wimax'): void ns3::WimaxMacToMacHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wimax-mac-to-mac-header.h (module 'wimax'): void ns3::WimaxMacToMacHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3WimaxPhy_methods(root_module, cls): ## wimax-phy.h (module 'wimax'): ns3::WimaxPhy::WimaxPhy(ns3::WimaxPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::WimaxPhy const &', 'arg0')]) ## wimax-phy.h (module 'wimax'): ns3::WimaxPhy::WimaxPhy() [constructor] cls.add_constructor([]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::Attach(ns3::Ptr<ns3::WimaxChannel> channel) [member function] cls.add_method('Attach', 'void', [param('ns3::Ptr< ns3::WimaxChannel >', 'channel')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## wimax-phy.h (module 'wimax'): ns3::Ptr<ns3::WimaxChannel> ns3::WimaxPhy::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::WimaxChannel >', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint32_t ns3::WimaxPhy::GetChannelBandwidth() const [member function] cls.add_method('GetChannelBandwidth', 'uint32_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::EventId ns3::WimaxPhy::GetChnlSrchTimeoutEvent() const [member function] cls.add_method('GetChnlSrchTimeoutEvent', 'ns3::EventId', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint32_t ns3::WimaxPhy::GetDataRate(ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('GetDataRate', 'uint32_t', [param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::Ptr<ns3::NetDevice> ns3::WimaxPhy::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::Time ns3::WimaxPhy::GetFrameDuration() const [member function] cls.add_method('GetFrameDuration', 'ns3::Time', [], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::Time ns3::WimaxPhy::GetFrameDuration(uint8_t frameDurationCode) const [member function] cls.add_method('GetFrameDuration', 'ns3::Time', [param('uint8_t', 'frameDurationCode')], is_const=True) ## wimax-phy.h (module 'wimax'): uint8_t ns3::WimaxPhy::GetFrameDurationCode() const [member function] cls.add_method('GetFrameDurationCode', 'uint8_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::Time ns3::WimaxPhy::GetFrameDurationSec() const [member function] cls.add_method('GetFrameDurationSec', 'ns3::Time', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint32_t ns3::WimaxPhy::GetFrequency() const [member function] cls.add_method('GetFrequency', 'uint32_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): double ns3::WimaxPhy::GetGValue() const [member function] cls.add_method('GetGValue', 'double', [], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::Ptr<ns3::Object> ns3::WimaxPhy::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::Object >', [], is_virtual=True) ## wimax-phy.h (module 'wimax'): uint16_t ns3::WimaxPhy::GetNfft() const [member function] cls.add_method('GetNfft', 'uint16_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint64_t ns3::WimaxPhy::GetNrBytes(uint32_t symbols, ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('GetNrBytes', 'uint64_t', [param('uint32_t', 'symbols'), param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_const=True) ## wimax-phy.h (module 'wimax'): uint8_t ns3::WimaxPhy::GetNrCarriers() const [member function] cls.add_method('GetNrCarriers', 'uint8_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint64_t ns3::WimaxPhy::GetNrSymbols(uint32_t size, ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('GetNrSymbols', 'uint64_t', [param('uint32_t', 'size'), param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::WimaxPhy::PhyType ns3::WimaxPhy::GetPhyType() const [member function] cls.add_method('GetPhyType', 'ns3::WimaxPhy::PhyType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wimax-phy.h (module 'wimax'): ns3::Time ns3::WimaxPhy::GetPsDuration() const [member function] cls.add_method('GetPsDuration', 'ns3::Time', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint16_t ns3::WimaxPhy::GetPsPerFrame() const [member function] cls.add_method('GetPsPerFrame', 'uint16_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint16_t ns3::WimaxPhy::GetPsPerSymbol() const [member function] cls.add_method('GetPsPerSymbol', 'uint16_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::Callback<void, ns3::Ptr<ns3::PacketBurst const>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::WimaxPhy::GetReceiveCallback() const [member function] cls.add_method('GetReceiveCallback', 'ns3::Callback< void, ns3::Ptr< ns3::PacketBurst const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint16_t ns3::WimaxPhy::GetRtg() const [member function] cls.add_method('GetRtg', 'uint16_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint64_t ns3::WimaxPhy::GetRxFrequency() const [member function] cls.add_method('GetRxFrequency', 'uint64_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): double ns3::WimaxPhy::GetSamplingFactor() const [member function] cls.add_method('GetSamplingFactor', 'double', [], is_const=True) ## wimax-phy.h (module 'wimax'): double ns3::WimaxPhy::GetSamplingFrequency() const [member function] cls.add_method('GetSamplingFrequency', 'double', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint64_t ns3::WimaxPhy::GetScanningFrequency() const [member function] cls.add_method('GetScanningFrequency', 'uint64_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::WimaxPhy::PhyState ns3::WimaxPhy::GetState() const [member function] cls.add_method('GetState', 'ns3::WimaxPhy::PhyState', [], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::Time ns3::WimaxPhy::GetSymbolDuration() const [member function] cls.add_method('GetSymbolDuration', 'ns3::Time', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint32_t ns3::WimaxPhy::GetSymbolsPerFrame() const [member function] cls.add_method('GetSymbolsPerFrame', 'uint32_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): ns3::Time ns3::WimaxPhy::GetTransmissionTime(uint32_t size, ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('GetTransmissionTime', 'ns3::Time', [param('uint32_t', 'size'), param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_const=True) ## wimax-phy.h (module 'wimax'): uint16_t ns3::WimaxPhy::GetTtg() const [member function] cls.add_method('GetTtg', 'uint16_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): uint64_t ns3::WimaxPhy::GetTxFrequency() const [member function] cls.add_method('GetTxFrequency', 'uint64_t', [], is_const=True) ## wimax-phy.h (module 'wimax'): static ns3::TypeId ns3::WimaxPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-phy.h (module 'wimax'): bool ns3::WimaxPhy::IsDuplex() const [member function] cls.add_method('IsDuplex', 'bool', [], is_const=True) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::Send(ns3::SendParams * params) [member function] cls.add_method('Send', 'void', [param('ns3::SendParams *', 'params')], is_pure_virtual=True, is_virtual=True) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetChannelBandwidth(uint32_t channelBandwidth) [member function] cls.add_method('SetChannelBandwidth', 'void', [param('uint32_t', 'channelBandwidth')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetDataRates() [member function] cls.add_method('SetDataRates', 'void', []) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetDevice(ns3::Ptr<ns3::WimaxNetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::WimaxNetDevice >', 'device')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetDuplex(uint64_t rxFrequency, uint64_t txFrequency) [member function] cls.add_method('SetDuplex', 'void', [param('uint64_t', 'rxFrequency'), param('uint64_t', 'txFrequency')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetFrameDuration(ns3::Time frameDuration) [member function] cls.add_method('SetFrameDuration', 'void', [param('ns3::Time', 'frameDuration')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetFrequency(uint32_t frequency) [member function] cls.add_method('SetFrequency', 'void', [param('uint32_t', 'frequency')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetMobility(ns3::Ptr<ns3::Object> mobility) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::Object >', 'mobility')], is_virtual=True) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetNrCarriers(uint8_t nrCarriers) [member function] cls.add_method('SetNrCarriers', 'void', [param('uint8_t', 'nrCarriers')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetPhyParameters() [member function] cls.add_method('SetPhyParameters', 'void', []) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetPsDuration(ns3::Time psDuration) [member function] cls.add_method('SetPsDuration', 'void', [param('ns3::Time', 'psDuration')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetPsPerFrame(uint16_t psPerFrame) [member function] cls.add_method('SetPsPerFrame', 'void', [param('uint16_t', 'psPerFrame')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetPsPerSymbol(uint16_t psPerSymbol) [member function] cls.add_method('SetPsPerSymbol', 'void', [param('uint16_t', 'psPerSymbol')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetReceiveCallback(ns3::Callback<void, ns3::Ptr<ns3::PacketBurst const>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::PacketBurst const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetScanningCallback() const [member function] cls.add_method('SetScanningCallback', 'void', [], is_const=True) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetSimplex(uint64_t frequency) [member function] cls.add_method('SetSimplex', 'void', [param('uint64_t', 'frequency')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetState(ns3::WimaxPhy::PhyState state) [member function] cls.add_method('SetState', 'void', [param('ns3::WimaxPhy::PhyState', 'state')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetSymbolDuration(ns3::Time symbolDuration) [member function] cls.add_method('SetSymbolDuration', 'void', [param('ns3::Time', 'symbolDuration')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::SetSymbolsPerFrame(uint32_t symbolsPerFrame) [member function] cls.add_method('SetSymbolsPerFrame', 'void', [param('uint32_t', 'symbolsPerFrame')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::StartScanning(uint64_t frequency, ns3::Time timeout, ns3::Callback<void, bool, unsigned long, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('StartScanning', 'void', [param('uint64_t', 'frequency'), param('ns3::Time', 'timeout'), param('ns3::Callback< void, bool, unsigned long, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::DoAttach(ns3::Ptr<ns3::WimaxChannel> channel) [member function] cls.add_method('DoAttach', 'void', [param('ns3::Ptr< ns3::WimaxChannel >', 'channel')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): uint32_t ns3::WimaxPhy::DoGetDataRate(ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('DoGetDataRate', 'uint32_t', [param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): ns3::Time ns3::WimaxPhy::DoGetFrameDuration(uint8_t frameDurationCode) const [member function] cls.add_method('DoGetFrameDuration', 'ns3::Time', [param('uint8_t', 'frameDurationCode')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): uint8_t ns3::WimaxPhy::DoGetFrameDurationCode() const [member function] cls.add_method('DoGetFrameDurationCode', 'uint8_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): double ns3::WimaxPhy::DoGetGValue() const [member function] cls.add_method('DoGetGValue', 'double', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): uint16_t ns3::WimaxPhy::DoGetNfft() const [member function] cls.add_method('DoGetNfft', 'uint16_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): uint64_t ns3::WimaxPhy::DoGetNrBytes(uint32_t symbols, ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('DoGetNrBytes', 'uint64_t', [param('uint32_t', 'symbols'), param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): uint64_t ns3::WimaxPhy::DoGetNrSymbols(uint32_t size, ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('DoGetNrSymbols', 'uint64_t', [param('uint32_t', 'size'), param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): uint16_t ns3::WimaxPhy::DoGetRtg() const [member function] cls.add_method('DoGetRtg', 'uint16_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): double ns3::WimaxPhy::DoGetSamplingFactor() const [member function] cls.add_method('DoGetSamplingFactor', 'double', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): double ns3::WimaxPhy::DoGetSamplingFrequency() const [member function] cls.add_method('DoGetSamplingFrequency', 'double', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): ns3::Time ns3::WimaxPhy::DoGetTransmissionTime(uint32_t size, ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('DoGetTransmissionTime', 'ns3::Time', [param('uint32_t', 'size'), param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): uint16_t ns3::WimaxPhy::DoGetTtg() const [member function] cls.add_method('DoGetTtg', 'uint16_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::DoSetDataRates() [member function] cls.add_method('DoSetDataRates', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## wimax-phy.h (module 'wimax'): void ns3::WimaxPhy::DoSetPhyParameters() [member function] cls.add_method('DoSetPhyParameters', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3BSScheduler_methods(root_module, cls): ## bs-scheduler.h (module 'wimax'): ns3::BSScheduler::BSScheduler(ns3::BSScheduler const & arg0) [copy constructor] cls.add_constructor([param('ns3::BSScheduler const &', 'arg0')]) ## bs-scheduler.h (module 'wimax'): ns3::BSScheduler::BSScheduler() [constructor] cls.add_constructor([]) ## bs-scheduler.h (module 'wimax'): ns3::BSScheduler::BSScheduler(ns3::Ptr<ns3::BaseStationNetDevice> bs) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::BaseStationNetDevice >', 'bs')]) ## bs-scheduler.h (module 'wimax'): void ns3::BSScheduler::AddDownlinkBurst(ns3::Ptr<const ns3::WimaxConnection> connection, uint8_t diuc, ns3::WimaxPhy::ModulationType modulationType, ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('AddDownlinkBurst', 'void', [param('ns3::Ptr< ns3::WimaxConnection const >', 'connection'), param('uint8_t', 'diuc'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('ns3::Ptr< ns3::PacketBurst >', 'burst')], is_pure_virtual=True, is_virtual=True) ## bs-scheduler.h (module 'wimax'): bool ns3::BSScheduler::CheckForFragmentation(ns3::Ptr<ns3::WimaxConnection> connection, int availableSymbols, ns3::WimaxPhy::ModulationType modulationType) [member function] cls.add_method('CheckForFragmentation', 'bool', [param('ns3::Ptr< ns3::WimaxConnection >', 'connection'), param('int', 'availableSymbols'), param('ns3::WimaxPhy::ModulationType', 'modulationType')]) ## bs-scheduler.h (module 'wimax'): ns3::Ptr<ns3::PacketBurst> ns3::BSScheduler::CreateUgsBurst(ns3::ServiceFlow * serviceFlow, ns3::WimaxPhy::ModulationType modulationType, uint32_t availableSymbols) [member function] cls.add_method('CreateUgsBurst', 'ns3::Ptr< ns3::PacketBurst >', [param('ns3::ServiceFlow *', 'serviceFlow'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('uint32_t', 'availableSymbols')], is_pure_virtual=True, is_virtual=True) ## bs-scheduler.h (module 'wimax'): ns3::Ptr<ns3::BaseStationNetDevice> ns3::BSScheduler::GetBs() [member function] cls.add_method('GetBs', 'ns3::Ptr< ns3::BaseStationNetDevice >', [], is_virtual=True) ## bs-scheduler.h (module 'wimax'): std::list<std::pair<ns3::OfdmDlMapIe*, ns3::Ptr<ns3::PacketBurst> >,std::allocator<std::pair<ns3::OfdmDlMapIe*, ns3::Ptr<ns3::PacketBurst> > > > * ns3::BSScheduler::GetDownlinkBursts() const [member function] cls.add_method('GetDownlinkBursts', 'std::list< std::pair< ns3::OfdmDlMapIe *, ns3::Ptr< ns3::PacketBurst > > > *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## bs-scheduler.h (module 'wimax'): static ns3::TypeId ns3::BSScheduler::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bs-scheduler.h (module 'wimax'): void ns3::BSScheduler::Schedule() [member function] cls.add_method('Schedule', 'void', [], is_pure_virtual=True, is_virtual=True) ## bs-scheduler.h (module 'wimax'): bool ns3::BSScheduler::SelectConnection(ns3::Ptr<ns3::WimaxConnection> & connection) [member function] cls.add_method('SelectConnection', 'bool', [param('ns3::Ptr< ns3::WimaxConnection > &', 'connection')], is_pure_virtual=True, is_virtual=True) ## bs-scheduler.h (module 'wimax'): void ns3::BSScheduler::SetBs(ns3::Ptr<ns3::BaseStationNetDevice> bs) [member function] cls.add_method('SetBs', 'void', [param('ns3::Ptr< ns3::BaseStationNetDevice >', 'bs')], is_virtual=True) return def register_Ns3BSSchedulerRtps_methods(root_module, cls): ## bs-scheduler-rtps.h (module 'wimax'): ns3::BSSchedulerRtps::BSSchedulerRtps(ns3::BSSchedulerRtps const & arg0) [copy constructor] cls.add_constructor([param('ns3::BSSchedulerRtps const &', 'arg0')]) ## bs-scheduler-rtps.h (module 'wimax'): ns3::BSSchedulerRtps::BSSchedulerRtps() [constructor] cls.add_constructor([]) ## bs-scheduler-rtps.h (module 'wimax'): ns3::BSSchedulerRtps::BSSchedulerRtps(ns3::Ptr<ns3::BaseStationNetDevice> bs) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::BaseStationNetDevice >', 'bs')]) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::AddDownlinkBurst(ns3::Ptr<const ns3::WimaxConnection> connection, uint8_t diuc, ns3::WimaxPhy::ModulationType modulationType, ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('AddDownlinkBurst', 'void', [param('ns3::Ptr< ns3::WimaxConnection const >', 'connection'), param('uint8_t', 'diuc'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('ns3::Ptr< ns3::PacketBurst >', 'burst')], is_virtual=True) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::BSSchedulerBEConnection(uint32_t & availableSymbols) [member function] cls.add_method('BSSchedulerBEConnection', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::BSSchedulerBasicConnection(uint32_t & availableSymbols) [member function] cls.add_method('BSSchedulerBasicConnection', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::BSSchedulerBroadcastConnection(uint32_t & availableSymbols) [member function] cls.add_method('BSSchedulerBroadcastConnection', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::BSSchedulerInitialRangingConnection(uint32_t & availableSymbols) [member function] cls.add_method('BSSchedulerInitialRangingConnection', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::BSSchedulerNRTPSConnection(uint32_t & availableSymbols) [member function] cls.add_method('BSSchedulerNRTPSConnection', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::BSSchedulerPrimaryConnection(uint32_t & availableSymbols) [member function] cls.add_method('BSSchedulerPrimaryConnection', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::BSSchedulerRTPSConnection(uint32_t & availableSymbols) [member function] cls.add_method('BSSchedulerRTPSConnection', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::BSSchedulerUGSConnection(uint32_t & availableSymbols) [member function] cls.add_method('BSSchedulerUGSConnection', 'void', [param('uint32_t &', 'availableSymbols')]) ## bs-scheduler-rtps.h (module 'wimax'): ns3::Ptr<ns3::PacketBurst> ns3::BSSchedulerRtps::CreateUgsBurst(ns3::ServiceFlow * serviceFlow, ns3::WimaxPhy::ModulationType modulationType, uint32_t availableSymbols) [member function] cls.add_method('CreateUgsBurst', 'ns3::Ptr< ns3::PacketBurst >', [param('ns3::ServiceFlow *', 'serviceFlow'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('uint32_t', 'availableSymbols')], is_virtual=True) ## bs-scheduler-rtps.h (module 'wimax'): std::list<std::pair<ns3::OfdmDlMapIe*, ns3::Ptr<ns3::PacketBurst> >,std::allocator<std::pair<ns3::OfdmDlMapIe*, ns3::Ptr<ns3::PacketBurst> > > > * ns3::BSSchedulerRtps::GetDownlinkBursts() const [member function] cls.add_method('GetDownlinkBursts', 'std::list< std::pair< ns3::OfdmDlMapIe *, ns3::Ptr< ns3::PacketBurst > > > *', [], is_const=True, is_virtual=True) ## bs-scheduler-rtps.h (module 'wimax'): static ns3::TypeId ns3::BSSchedulerRtps::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bs-scheduler-rtps.h (module 'wimax'): void ns3::BSSchedulerRtps::Schedule() [member function] cls.add_method('Schedule', 'void', [], is_virtual=True) ## bs-scheduler-rtps.h (module 'wimax'): bool ns3::BSSchedulerRtps::SelectBEConnection(ns3::Ptr<ns3::WimaxConnection> & connection) [member function] cls.add_method('SelectBEConnection', 'bool', [param('ns3::Ptr< ns3::WimaxConnection > &', 'connection')]) ## bs-scheduler-rtps.h (module 'wimax'): bool ns3::BSSchedulerRtps::SelectConnection(ns3::Ptr<ns3::WimaxConnection> & connection) [member function] cls.add_method('SelectConnection', 'bool', [param('ns3::Ptr< ns3::WimaxConnection > &', 'connection')], is_virtual=True) ## bs-scheduler-rtps.h (module 'wimax'): bool ns3::BSSchedulerRtps::SelectIRandBCConnection(ns3::Ptr<ns3::WimaxConnection> & connection) [member function] cls.add_method('SelectIRandBCConnection', 'bool', [param('ns3::Ptr< ns3::WimaxConnection > &', 'connection')]) ## bs-scheduler-rtps.h (module 'wimax'): bool ns3::BSSchedulerRtps::SelectMenagementConnection(ns3::Ptr<ns3::WimaxConnection> & connection) [member function] cls.add_method('SelectMenagementConnection', 'bool', [param('ns3::Ptr< ns3::WimaxConnection > &', 'connection')]) ## bs-scheduler-rtps.h (module 'wimax'): bool ns3::BSSchedulerRtps::SelectNRTPSConnection(ns3::Ptr<ns3::WimaxConnection> & connection) [member function] cls.add_method('SelectNRTPSConnection', 'bool', [param('ns3::Ptr< ns3::WimaxConnection > &', 'connection')]) ## bs-scheduler-rtps.h (module 'wimax'): bool ns3::BSSchedulerRtps::SelectRTPSConnection(ns3::Ptr<ns3::WimaxConnection> & connection) [member function] cls.add_method('SelectRTPSConnection', 'bool', [param('ns3::Ptr< ns3::WimaxConnection > &', 'connection')]) ## bs-scheduler-rtps.h (module 'wimax'): bool ns3::BSSchedulerRtps::SelectUGSConnection(ns3::Ptr<ns3::WimaxConnection> & connection) [member function] cls.add_method('SelectUGSConnection', 'bool', [param('ns3::Ptr< ns3::WimaxConnection > &', 'connection')]) return def register_Ns3BSSchedulerSimple_methods(root_module, cls): ## bs-scheduler-simple.h (module 'wimax'): ns3::BSSchedulerSimple::BSSchedulerSimple(ns3::BSSchedulerSimple const & arg0) [copy constructor] cls.add_constructor([param('ns3::BSSchedulerSimple const &', 'arg0')]) ## bs-scheduler-simple.h (module 'wimax'): ns3::BSSchedulerSimple::BSSchedulerSimple() [constructor] cls.add_constructor([]) ## bs-scheduler-simple.h (module 'wimax'): ns3::BSSchedulerSimple::BSSchedulerSimple(ns3::Ptr<ns3::BaseStationNetDevice> bs) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::BaseStationNetDevice >', 'bs')]) ## bs-scheduler-simple.h (module 'wimax'): void ns3::BSSchedulerSimple::AddDownlinkBurst(ns3::Ptr<const ns3::WimaxConnection> connection, uint8_t diuc, ns3::WimaxPhy::ModulationType modulationType, ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('AddDownlinkBurst', 'void', [param('ns3::Ptr< ns3::WimaxConnection const >', 'connection'), param('uint8_t', 'diuc'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('ns3::Ptr< ns3::PacketBurst >', 'burst')], is_virtual=True) ## bs-scheduler-simple.h (module 'wimax'): ns3::Ptr<ns3::PacketBurst> ns3::BSSchedulerSimple::CreateUgsBurst(ns3::ServiceFlow * serviceFlow, ns3::WimaxPhy::ModulationType modulationType, uint32_t availableSymbols) [member function] cls.add_method('CreateUgsBurst', 'ns3::Ptr< ns3::PacketBurst >', [param('ns3::ServiceFlow *', 'serviceFlow'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('uint32_t', 'availableSymbols')], is_virtual=True) ## bs-scheduler-simple.h (module 'wimax'): std::list<std::pair<ns3::OfdmDlMapIe*, ns3::Ptr<ns3::PacketBurst> >,std::allocator<std::pair<ns3::OfdmDlMapIe*, ns3::Ptr<ns3::PacketBurst> > > > * ns3::BSSchedulerSimple::GetDownlinkBursts() const [member function] cls.add_method('GetDownlinkBursts', 'std::list< std::pair< ns3::OfdmDlMapIe *, ns3::Ptr< ns3::PacketBurst > > > *', [], is_const=True, is_virtual=True) ## bs-scheduler-simple.h (module 'wimax'): static ns3::TypeId ns3::BSSchedulerSimple::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bs-scheduler-simple.h (module 'wimax'): void ns3::BSSchedulerSimple::Schedule() [member function] cls.add_method('Schedule', 'void', [], is_virtual=True) ## bs-scheduler-simple.h (module 'wimax'): bool ns3::BSSchedulerSimple::SelectConnection(ns3::Ptr<ns3::WimaxConnection> & connection) [member function] cls.add_method('SelectConnection', 'bool', [param('ns3::Ptr< ns3::WimaxConnection > &', 'connection')], is_virtual=True) return def register_Ns3BandwidthRequestHeader_methods(root_module, cls): ## wimax-mac-header.h (module 'wimax'): ns3::BandwidthRequestHeader::BandwidthRequestHeader(ns3::BandwidthRequestHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::BandwidthRequestHeader const &', 'arg0')]) ## wimax-mac-header.h (module 'wimax'): ns3::BandwidthRequestHeader::BandwidthRequestHeader() [constructor] cls.add_constructor([]) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::BandwidthRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::BandwidthRequestHeader::GetBr() const [member function] cls.add_method('GetBr', 'uint32_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): ns3::Cid ns3::BandwidthRequestHeader::GetCid() const [member function] cls.add_method('GetCid', 'ns3::Cid', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::BandwidthRequestHeader::GetEc() const [member function] cls.add_method('GetEc', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::BandwidthRequestHeader::GetHcs() const [member function] cls.add_method('GetHcs', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::BandwidthRequestHeader::GetHt() const [member function] cls.add_method('GetHt', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): ns3::TypeId ns3::BandwidthRequestHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): std::string ns3::BandwidthRequestHeader::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::BandwidthRequestHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::BandwidthRequestHeader::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): static ns3::TypeId ns3::BandwidthRequestHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-mac-header.h (module 'wimax'): void ns3::BandwidthRequestHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::BandwidthRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::BandwidthRequestHeader::SetBr(uint32_t br) [member function] cls.add_method('SetBr', 'void', [param('uint32_t', 'br')]) ## wimax-mac-header.h (module 'wimax'): void ns3::BandwidthRequestHeader::SetCid(ns3::Cid cid) [member function] cls.add_method('SetCid', 'void', [param('ns3::Cid', 'cid')]) ## wimax-mac-header.h (module 'wimax'): void ns3::BandwidthRequestHeader::SetEc(uint8_t ec) [member function] cls.add_method('SetEc', 'void', [param('uint8_t', 'ec')]) ## wimax-mac-header.h (module 'wimax'): void ns3::BandwidthRequestHeader::SetHcs(uint8_t hcs) [member function] cls.add_method('SetHcs', 'void', [param('uint8_t', 'hcs')]) ## wimax-mac-header.h (module 'wimax'): void ns3::BandwidthRequestHeader::SetHt(uint8_t HT) [member function] cls.add_method('SetHt', 'void', [param('uint8_t', 'HT')]) ## wimax-mac-header.h (module 'wimax'): void ns3::BandwidthRequestHeader::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## wimax-mac-header.h (module 'wimax'): bool ns3::BandwidthRequestHeader::check_hcs() const [member function] cls.add_method('check_hcs', 'bool', [], is_const=True) return def register_Ns3BsServiceFlowManager_methods(root_module, cls): ## bs-service-flow-manager.h (module 'wimax'): ns3::BsServiceFlowManager::BsServiceFlowManager(ns3::BsServiceFlowManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::BsServiceFlowManager const &', 'arg0')]) ## bs-service-flow-manager.h (module 'wimax'): ns3::BsServiceFlowManager::BsServiceFlowManager(ns3::Ptr<ns3::BaseStationNetDevice> device) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::BaseStationNetDevice >', 'device')]) ## bs-service-flow-manager.h (module 'wimax'): void ns3::BsServiceFlowManager::AddMulticastServiceFlow(ns3::ServiceFlow sf, ns3::WimaxPhy::ModulationType modulation) [member function] cls.add_method('AddMulticastServiceFlow', 'void', [param('ns3::ServiceFlow', 'sf'), param('ns3::WimaxPhy::ModulationType', 'modulation')]) ## bs-service-flow-manager.h (module 'wimax'): void ns3::BsServiceFlowManager::AddServiceFlow(ns3::ServiceFlow * serviceFlow) [member function] cls.add_method('AddServiceFlow', 'void', [param('ns3::ServiceFlow *', 'serviceFlow')]) ## bs-service-flow-manager.h (module 'wimax'): void ns3::BsServiceFlowManager::AllocateServiceFlows(ns3::DsaReq const & dsaReq, ns3::Cid cid) [member function] cls.add_method('AllocateServiceFlows', 'void', [param('ns3::DsaReq const &', 'dsaReq'), param('ns3::Cid', 'cid')]) ## bs-service-flow-manager.h (module 'wimax'): void ns3::BsServiceFlowManager::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## bs-service-flow-manager.h (module 'wimax'): ns3::EventId ns3::BsServiceFlowManager::GetDsaAckTimeoutEvent() const [member function] cls.add_method('GetDsaAckTimeoutEvent', 'ns3::EventId', [], is_const=True) ## bs-service-flow-manager.h (module 'wimax'): ns3::ServiceFlow * ns3::BsServiceFlowManager::GetServiceFlow(uint32_t sfid) const [member function] cls.add_method('GetServiceFlow', 'ns3::ServiceFlow *', [param('uint32_t', 'sfid')], is_const=True) ## bs-service-flow-manager.h (module 'wimax'): ns3::ServiceFlow * ns3::BsServiceFlowManager::GetServiceFlow(ns3::Cid cid) const [member function] cls.add_method('GetServiceFlow', 'ns3::ServiceFlow *', [param('ns3::Cid', 'cid')], is_const=True) ## bs-service-flow-manager.h (module 'wimax'): std::vector<ns3::ServiceFlow*,std::allocator<ns3::ServiceFlow*> > ns3::BsServiceFlowManager::GetServiceFlows(ns3::ServiceFlow::SchedulingType schedulingType) const [member function] cls.add_method('GetServiceFlows', 'std::vector< ns3::ServiceFlow * >', [param('ns3::ServiceFlow::SchedulingType', 'schedulingType')], is_const=True) ## bs-service-flow-manager.h (module 'wimax'): void ns3::BsServiceFlowManager::ProcessDsaAck(ns3::DsaAck const & dsaAck, ns3::Cid cid) [member function] cls.add_method('ProcessDsaAck', 'void', [param('ns3::DsaAck const &', 'dsaAck'), param('ns3::Cid', 'cid')]) ## bs-service-flow-manager.h (module 'wimax'): ns3::ServiceFlow * ns3::BsServiceFlowManager::ProcessDsaReq(ns3::DsaReq const & dsaReq, ns3::Cid cid) [member function] cls.add_method('ProcessDsaReq', 'ns3::ServiceFlow *', [param('ns3::DsaReq const &', 'dsaReq'), param('ns3::Cid', 'cid')]) ## bs-service-flow-manager.h (module 'wimax'): void ns3::BsServiceFlowManager::SetMaxDsaRspRetries(uint8_t maxDsaRspRetries) [member function] cls.add_method('SetMaxDsaRspRetries', 'void', [param('uint8_t', 'maxDsaRspRetries')]) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3ConnectionManager_methods(root_module, cls): ## connection-manager.h (module 'wimax'): ns3::ConnectionManager::ConnectionManager(ns3::ConnectionManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConnectionManager const &', 'arg0')]) ## connection-manager.h (module 'wimax'): ns3::ConnectionManager::ConnectionManager() [constructor] cls.add_constructor([]) ## connection-manager.h (module 'wimax'): void ns3::ConnectionManager::AddConnection(ns3::Ptr<ns3::WimaxConnection> connection, ns3::Cid::Type type) [member function] cls.add_method('AddConnection', 'void', [param('ns3::Ptr< ns3::WimaxConnection >', 'connection'), param('ns3::Cid::Type', 'type')]) ## connection-manager.h (module 'wimax'): void ns3::ConnectionManager::AllocateManagementConnections(ns3::SSRecord * ssRecord, ns3::RngRsp * rngrsp) [member function] cls.add_method('AllocateManagementConnections', 'void', [param('ns3::SSRecord *', 'ssRecord'), param('ns3::RngRsp *', 'rngrsp')]) ## connection-manager.h (module 'wimax'): ns3::Ptr<ns3::WimaxConnection> ns3::ConnectionManager::CreateConnection(ns3::Cid::Type type) [member function] cls.add_method('CreateConnection', 'ns3::Ptr< ns3::WimaxConnection >', [param('ns3::Cid::Type', 'type')]) ## connection-manager.h (module 'wimax'): void ns3::ConnectionManager::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## connection-manager.h (module 'wimax'): ns3::Ptr<ns3::WimaxConnection> ns3::ConnectionManager::GetConnection(ns3::Cid cid) [member function] cls.add_method('GetConnection', 'ns3::Ptr< ns3::WimaxConnection >', [param('ns3::Cid', 'cid')]) ## connection-manager.h (module 'wimax'): std::vector<ns3::Ptr<ns3::WimaxConnection>, std::allocator<ns3::Ptr<ns3::WimaxConnection> > > ns3::ConnectionManager::GetConnections(ns3::Cid::Type type) const [member function] cls.add_method('GetConnections', 'std::vector< ns3::Ptr< ns3::WimaxConnection > >', [param('ns3::Cid::Type', 'type')], is_const=True) ## connection-manager.h (module 'wimax'): uint32_t ns3::ConnectionManager::GetNPackets(ns3::Cid::Type type, ns3::ServiceFlow::SchedulingType schedulingType) const [member function] cls.add_method('GetNPackets', 'uint32_t', [param('ns3::Cid::Type', 'type'), param('ns3::ServiceFlow::SchedulingType', 'schedulingType')], is_const=True) ## connection-manager.h (module 'wimax'): bool ns3::ConnectionManager::HasPackets() const [member function] cls.add_method('HasPackets', 'bool', [], is_const=True) ## connection-manager.h (module 'wimax'): void ns3::ConnectionManager::SetCidFactory(ns3::CidFactory * cidFactory) [member function] cls.add_method('SetCidFactory', 'void', [param('ns3::CidFactory *', 'cidFactory')]) return def register_Ns3Dcd_methods(root_module, cls): ## dl-mac-messages.h (module 'wimax'): ns3::Dcd::Dcd(ns3::Dcd const & arg0) [copy constructor] cls.add_constructor([param('ns3::Dcd const &', 'arg0')]) ## dl-mac-messages.h (module 'wimax'): ns3::Dcd::Dcd() [constructor] cls.add_constructor([]) ## dl-mac-messages.h (module 'wimax'): void ns3::Dcd::AddDlBurstProfile(ns3::OfdmDlBurstProfile dlBurstProfile) [member function] cls.add_method('AddDlBurstProfile', 'void', [param('ns3::OfdmDlBurstProfile', 'dlBurstProfile')]) ## dl-mac-messages.h (module 'wimax'): uint32_t ns3::Dcd::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## dl-mac-messages.h (module 'wimax'): ns3::OfdmDcdChannelEncodings ns3::Dcd::GetChannelEncodings() const [member function] cls.add_method('GetChannelEncodings', 'ns3::OfdmDcdChannelEncodings', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::Dcd::GetConfigurationChangeCount() const [member function] cls.add_method('GetConfigurationChangeCount', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): std::vector<ns3::OfdmDlBurstProfile, std::allocator<ns3::OfdmDlBurstProfile> > ns3::Dcd::GetDlBurstProfiles() const [member function] cls.add_method('GetDlBurstProfiles', 'std::vector< ns3::OfdmDlBurstProfile >', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): ns3::TypeId ns3::Dcd::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## dl-mac-messages.h (module 'wimax'): std::string ns3::Dcd::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::Dcd::GetNrDlBurstProfiles() const [member function] cls.add_method('GetNrDlBurstProfiles', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint32_t ns3::Dcd::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## dl-mac-messages.h (module 'wimax'): static ns3::TypeId ns3::Dcd::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## dl-mac-messages.h (module 'wimax'): void ns3::Dcd::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## dl-mac-messages.h (module 'wimax'): void ns3::Dcd::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## dl-mac-messages.h (module 'wimax'): void ns3::Dcd::SetChannelEncodings(ns3::OfdmDcdChannelEncodings channelEncodings) [member function] cls.add_method('SetChannelEncodings', 'void', [param('ns3::OfdmDcdChannelEncodings', 'channelEncodings')]) ## dl-mac-messages.h (module 'wimax'): void ns3::Dcd::SetConfigurationChangeCount(uint8_t configurationChangeCount) [member function] cls.add_method('SetConfigurationChangeCount', 'void', [param('uint8_t', 'configurationChangeCount')]) ## dl-mac-messages.h (module 'wimax'): void ns3::Dcd::SetNrDlBurstProfiles(uint8_t nrDlBurstProfiles) [member function] cls.add_method('SetNrDlBurstProfiles', 'void', [param('uint8_t', 'nrDlBurstProfiles')]) return def register_Ns3DlMap_methods(root_module, cls): ## dl-mac-messages.h (module 'wimax'): ns3::DlMap::DlMap(ns3::DlMap const & arg0) [copy constructor] cls.add_constructor([param('ns3::DlMap const &', 'arg0')]) ## dl-mac-messages.h (module 'wimax'): ns3::DlMap::DlMap() [constructor] cls.add_constructor([]) ## dl-mac-messages.h (module 'wimax'): void ns3::DlMap::AddDlMapElement(ns3::OfdmDlMapIe dlMapElement) [member function] cls.add_method('AddDlMapElement', 'void', [param('ns3::OfdmDlMapIe', 'dlMapElement')]) ## dl-mac-messages.h (module 'wimax'): uint32_t ns3::DlMap::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## dl-mac-messages.h (module 'wimax'): ns3::Mac48Address ns3::DlMap::GetBaseStationId() const [member function] cls.add_method('GetBaseStationId', 'ns3::Mac48Address', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint8_t ns3::DlMap::GetDcdCount() const [member function] cls.add_method('GetDcdCount', 'uint8_t', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): std::list<ns3::OfdmDlMapIe, std::allocator<ns3::OfdmDlMapIe> > ns3::DlMap::GetDlMapElements() const [member function] cls.add_method('GetDlMapElements', 'std::list< ns3::OfdmDlMapIe >', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): ns3::TypeId ns3::DlMap::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## dl-mac-messages.h (module 'wimax'): std::string ns3::DlMap::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## dl-mac-messages.h (module 'wimax'): uint32_t ns3::DlMap::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## dl-mac-messages.h (module 'wimax'): static ns3::TypeId ns3::DlMap::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## dl-mac-messages.h (module 'wimax'): void ns3::DlMap::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## dl-mac-messages.h (module 'wimax'): void ns3::DlMap::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## dl-mac-messages.h (module 'wimax'): void ns3::DlMap::SetBaseStationId(ns3::Mac48Address baseStationID) [member function] cls.add_method('SetBaseStationId', 'void', [param('ns3::Mac48Address', 'baseStationID')]) ## dl-mac-messages.h (module 'wimax'): void ns3::DlMap::SetDcdCount(uint8_t dcdCount) [member function] cls.add_method('SetDcdCount', 'void', [param('uint8_t', 'dcdCount')]) return def register_Ns3DsaAck_methods(root_module, cls): ## mac-messages.h (module 'wimax'): ns3::DsaAck::DsaAck(ns3::DsaAck const & arg0) [copy constructor] cls.add_constructor([param('ns3::DsaAck const &', 'arg0')]) ## mac-messages.h (module 'wimax'): ns3::DsaAck::DsaAck() [constructor] cls.add_constructor([]) ## mac-messages.h (module 'wimax'): uint32_t ns3::DsaAck::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mac-messages.h (module 'wimax'): uint16_t ns3::DsaAck::GetConfirmationCode() const [member function] cls.add_method('GetConfirmationCode', 'uint16_t', [], is_const=True) ## mac-messages.h (module 'wimax'): ns3::TypeId ns3::DsaAck::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): std::string ns3::DsaAck::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::DsaAck::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): uint16_t ns3::DsaAck::GetTransactionId() const [member function] cls.add_method('GetTransactionId', 'uint16_t', [], is_const=True) ## mac-messages.h (module 'wimax'): static ns3::TypeId ns3::DsaAck::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mac-messages.h (module 'wimax'): void ns3::DsaAck::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::DsaAck::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::DsaAck::SetConfirmationCode(uint16_t confirmationCode) [member function] cls.add_method('SetConfirmationCode', 'void', [param('uint16_t', 'confirmationCode')]) ## mac-messages.h (module 'wimax'): void ns3::DsaAck::SetTransactionId(uint16_t transactionId) [member function] cls.add_method('SetTransactionId', 'void', [param('uint16_t', 'transactionId')]) return def register_Ns3DsaReq_methods(root_module, cls): ## mac-messages.h (module 'wimax'): ns3::DsaReq::DsaReq(ns3::DsaReq const & arg0) [copy constructor] cls.add_constructor([param('ns3::DsaReq const &', 'arg0')]) ## mac-messages.h (module 'wimax'): ns3::DsaReq::DsaReq() [constructor] cls.add_constructor([]) ## mac-messages.h (module 'wimax'): ns3::DsaReq::DsaReq(ns3::ServiceFlow sf) [constructor] cls.add_constructor([param('ns3::ServiceFlow', 'sf')]) ## mac-messages.h (module 'wimax'): uint32_t ns3::DsaReq::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mac-messages.h (module 'wimax'): ns3::Cid ns3::DsaReq::GetCid() const [member function] cls.add_method('GetCid', 'ns3::Cid', [], is_const=True) ## mac-messages.h (module 'wimax'): ns3::TypeId ns3::DsaReq::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): std::string ns3::DsaReq::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::DsaReq::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): ns3::ServiceFlow ns3::DsaReq::GetServiceFlow() const [member function] cls.add_method('GetServiceFlow', 'ns3::ServiceFlow', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::DsaReq::GetSfid() const [member function] cls.add_method('GetSfid', 'uint32_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint16_t ns3::DsaReq::GetTransactionId() const [member function] cls.add_method('GetTransactionId', 'uint16_t', [], is_const=True) ## mac-messages.h (module 'wimax'): static ns3::TypeId ns3::DsaReq::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mac-messages.h (module 'wimax'): void ns3::DsaReq::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::DsaReq::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::DsaReq::SetCid(ns3::Cid cid) [member function] cls.add_method('SetCid', 'void', [param('ns3::Cid', 'cid')]) ## mac-messages.h (module 'wimax'): void ns3::DsaReq::SetServiceFlow(ns3::ServiceFlow sf) [member function] cls.add_method('SetServiceFlow', 'void', [param('ns3::ServiceFlow', 'sf')]) ## mac-messages.h (module 'wimax'): void ns3::DsaReq::SetSfid(uint32_t sfid) [member function] cls.add_method('SetSfid', 'void', [param('uint32_t', 'sfid')]) ## mac-messages.h (module 'wimax'): void ns3::DsaReq::SetTransactionId(uint16_t transactionId) [member function] cls.add_method('SetTransactionId', 'void', [param('uint16_t', 'transactionId')]) return def register_Ns3DsaRsp_methods(root_module, cls): ## mac-messages.h (module 'wimax'): ns3::DsaRsp::DsaRsp(ns3::DsaRsp const & arg0) [copy constructor] cls.add_constructor([param('ns3::DsaRsp const &', 'arg0')]) ## mac-messages.h (module 'wimax'): ns3::DsaRsp::DsaRsp() [constructor] cls.add_constructor([]) ## mac-messages.h (module 'wimax'): uint32_t ns3::DsaRsp::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mac-messages.h (module 'wimax'): ns3::Cid ns3::DsaRsp::GetCid() const [member function] cls.add_method('GetCid', 'ns3::Cid', [], is_const=True) ## mac-messages.h (module 'wimax'): uint16_t ns3::DsaRsp::GetConfirmationCode() const [member function] cls.add_method('GetConfirmationCode', 'uint16_t', [], is_const=True) ## mac-messages.h (module 'wimax'): ns3::TypeId ns3::DsaRsp::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): std::string ns3::DsaRsp::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::DsaRsp::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): ns3::ServiceFlow ns3::DsaRsp::GetServiceFlow() const [member function] cls.add_method('GetServiceFlow', 'ns3::ServiceFlow', [], is_const=True) ## mac-messages.h (module 'wimax'): uint32_t ns3::DsaRsp::GetSfid() const [member function] cls.add_method('GetSfid', 'uint32_t', [], is_const=True) ## mac-messages.h (module 'wimax'): uint16_t ns3::DsaRsp::GetTransactionId() const [member function] cls.add_method('GetTransactionId', 'uint16_t', [], is_const=True) ## mac-messages.h (module 'wimax'): static ns3::TypeId ns3::DsaRsp::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mac-messages.h (module 'wimax'): void ns3::DsaRsp::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::DsaRsp::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mac-messages.h (module 'wimax'): void ns3::DsaRsp::SetCid(ns3::Cid cid) [member function] cls.add_method('SetCid', 'void', [param('ns3::Cid', 'cid')]) ## mac-messages.h (module 'wimax'): void ns3::DsaRsp::SetConfirmationCode(uint16_t confirmationCode) [member function] cls.add_method('SetConfirmationCode', 'void', [param('uint16_t', 'confirmationCode')]) ## mac-messages.h (module 'wimax'): void ns3::DsaRsp::SetServiceFlow(ns3::ServiceFlow sf) [member function] cls.add_method('SetServiceFlow', 'void', [param('ns3::ServiceFlow', 'sf')]) ## mac-messages.h (module 'wimax'): void ns3::DsaRsp::SetSfid(uint32_t sfid) [member function] cls.add_method('SetSfid', 'void', [param('uint32_t', 'sfid')]) ## mac-messages.h (module 'wimax'): void ns3::DsaRsp::SetTransactionId(uint16_t transactionId) [member function] cls.add_method('SetTransactionId', 'void', [param('uint16_t', 'transactionId')]) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3FixedRssLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::FixedRssLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::FixedRssLossModel::FixedRssLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::FixedRssLossModel::SetRss(double rss) [member function] cls.add_method('SetRss', 'void', [param('double', 'rss')]) ## propagation-loss-model.h (module 'propagation'): double ns3::FixedRssLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3FragmentationSubheader_methods(root_module, cls): ## wimax-mac-header.h (module 'wimax'): ns3::FragmentationSubheader::FragmentationSubheader(ns3::FragmentationSubheader const & arg0) [copy constructor] cls.add_constructor([param('ns3::FragmentationSubheader const &', 'arg0')]) ## wimax-mac-header.h (module 'wimax'): ns3::FragmentationSubheader::FragmentationSubheader() [constructor] cls.add_constructor([]) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::FragmentationSubheader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::FragmentationSubheader::GetFc() const [member function] cls.add_method('GetFc', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::FragmentationSubheader::GetFsn() const [member function] cls.add_method('GetFsn', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): ns3::TypeId ns3::FragmentationSubheader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): std::string ns3::FragmentationSubheader::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::FragmentationSubheader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): static ns3::TypeId ns3::FragmentationSubheader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-mac-header.h (module 'wimax'): void ns3::FragmentationSubheader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::FragmentationSubheader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::FragmentationSubheader::SetFc(uint8_t fc) [member function] cls.add_method('SetFc', 'void', [param('uint8_t', 'fc')]) ## wimax-mac-header.h (module 'wimax'): void ns3::FragmentationSubheader::SetFsn(uint8_t fsn) [member function] cls.add_method('SetFsn', 'void', [param('uint8_t', 'fsn')]) return def register_Ns3FriisPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::FriisPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::FriisPropagationLossModel::FriisPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetLambda(double frequency, double speed) [member function] cls.add_method('SetLambda', 'void', [param('double', 'frequency'), param('double', 'speed')]) ## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetLambda(double lambda) [member function] cls.add_method('SetLambda', 'void', [param('double', 'lambda')]) ## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetSystemLoss(double systemLoss) [member function] cls.add_method('SetSystemLoss', 'void', [param('double', 'systemLoss')]) ## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetMinDistance(double minDistance) [member function] cls.add_method('SetMinDistance', 'void', [param('double', 'minDistance')]) ## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetMinDistance() const [member function] cls.add_method('GetMinDistance', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetLambda() const [member function] cls.add_method('GetLambda', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetSystemLoss() const [member function] cls.add_method('GetSystemLoss', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3GenericMacHeader_methods(root_module, cls): ## wimax-mac-header.h (module 'wimax'): ns3::GenericMacHeader::GenericMacHeader(ns3::GenericMacHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::GenericMacHeader const &', 'arg0')]) ## wimax-mac-header.h (module 'wimax'): ns3::GenericMacHeader::GenericMacHeader() [constructor] cls.add_constructor([]) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::GenericMacHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::GenericMacHeader::GetCi() const [member function] cls.add_method('GetCi', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): ns3::Cid ns3::GenericMacHeader::GetCid() const [member function] cls.add_method('GetCid', 'ns3::Cid', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::GenericMacHeader::GetEc() const [member function] cls.add_method('GetEc', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::GenericMacHeader::GetEks() const [member function] cls.add_method('GetEks', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::GenericMacHeader::GetHcs() const [member function] cls.add_method('GetHcs', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::GenericMacHeader::GetHt() const [member function] cls.add_method('GetHt', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): ns3::TypeId ns3::GenericMacHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): uint16_t ns3::GenericMacHeader::GetLen() const [member function] cls.add_method('GetLen', 'uint16_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): std::string ns3::GenericMacHeader::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::GenericMacHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::GenericMacHeader::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): static ns3::TypeId ns3::GenericMacHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::SetCi(uint8_t ci) [member function] cls.add_method('SetCi', 'void', [param('uint8_t', 'ci')]) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::SetCid(ns3::Cid cid) [member function] cls.add_method('SetCid', 'void', [param('ns3::Cid', 'cid')]) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::SetEc(uint8_t ec) [member function] cls.add_method('SetEc', 'void', [param('uint8_t', 'ec')]) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::SetEks(uint8_t eks) [member function] cls.add_method('SetEks', 'void', [param('uint8_t', 'eks')]) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::SetHcs(uint8_t hcs) [member function] cls.add_method('SetHcs', 'void', [param('uint8_t', 'hcs')]) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::SetHt(uint8_t HT) [member function] cls.add_method('SetHt', 'void', [param('uint8_t', 'HT')]) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::SetLen(uint16_t len) [member function] cls.add_method('SetLen', 'void', [param('uint16_t', 'len')]) ## wimax-mac-header.h (module 'wimax'): void ns3::GenericMacHeader::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## wimax-mac-header.h (module 'wimax'): bool ns3::GenericMacHeader::check_hcs() const [member function] cls.add_method('check_hcs', 'bool', [], is_const=True) return def register_Ns3GrantManagementSubheader_methods(root_module, cls): ## wimax-mac-header.h (module 'wimax'): ns3::GrantManagementSubheader::GrantManagementSubheader(ns3::GrantManagementSubheader const & arg0) [copy constructor] cls.add_constructor([param('ns3::GrantManagementSubheader const &', 'arg0')]) ## wimax-mac-header.h (module 'wimax'): ns3::GrantManagementSubheader::GrantManagementSubheader() [constructor] cls.add_constructor([]) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::GrantManagementSubheader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wimax-mac-header.h (module 'wimax'): ns3::TypeId ns3::GrantManagementSubheader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): std::string ns3::GrantManagementSubheader::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint16_t ns3::GrantManagementSubheader::GetPbr() const [member function] cls.add_method('GetPbr', 'uint16_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::GrantManagementSubheader::GetPm() const [member function] cls.add_method('GetPm', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): uint32_t ns3::GrantManagementSubheader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): uint8_t ns3::GrantManagementSubheader::GetSi() const [member function] cls.add_method('GetSi', 'uint8_t', [], is_const=True) ## wimax-mac-header.h (module 'wimax'): static ns3::TypeId ns3::GrantManagementSubheader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-mac-header.h (module 'wimax'): void ns3::GrantManagementSubheader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::GrantManagementSubheader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## wimax-mac-header.h (module 'wimax'): void ns3::GrantManagementSubheader::SetPbr(uint16_t pbr) [member function] cls.add_method('SetPbr', 'void', [param('uint16_t', 'pbr')]) ## wimax-mac-header.h (module 'wimax'): void ns3::GrantManagementSubheader::SetPm(uint8_t pm) [member function] cls.add_method('SetPm', 'void', [param('uint8_t', 'pm')]) ## wimax-mac-header.h (module 'wimax'): void ns3::GrantManagementSubheader::SetSi(uint8_t si) [member function] cls.add_method('SetSi', 'void', [param('uint8_t', 'si')]) return def register_Ns3IpcsClassifier_methods(root_module, cls): ## ipcs-classifier.h (module 'wimax'): ns3::IpcsClassifier::IpcsClassifier(ns3::IpcsClassifier const & arg0) [copy constructor] cls.add_constructor([param('ns3::IpcsClassifier const &', 'arg0')]) ## ipcs-classifier.h (module 'wimax'): ns3::IpcsClassifier::IpcsClassifier() [constructor] cls.add_constructor([]) ## ipcs-classifier.h (module 'wimax'): ns3::ServiceFlow * ns3::IpcsClassifier::Classify(ns3::Ptr<const ns3::Packet> packet, ns3::Ptr<ns3::ServiceFlowManager> sfm, ns3::ServiceFlow::Direction dir) [member function] cls.add_method('Classify', 'ns3::ServiceFlow *', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Ptr< ns3::ServiceFlowManager >', 'sfm'), param('ns3::ServiceFlow::Direction', 'dir')]) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3LogDistancePropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::LogDistancePropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::LogDistancePropagationLossModel::LogDistancePropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::LogDistancePropagationLossModel::SetPathLossExponent(double n) [member function] cls.add_method('SetPathLossExponent', 'void', [param('double', 'n')]) ## propagation-loss-model.h (module 'propagation'): double ns3::LogDistancePropagationLossModel::GetPathLossExponent() const [member function] cls.add_method('GetPathLossExponent', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): void ns3::LogDistancePropagationLossModel::SetReference(double referenceDistance, double referenceLoss) [member function] cls.add_method('SetReference', 'void', [param('double', 'referenceDistance'), param('double', 'referenceLoss')]) ## propagation-loss-model.h (module 'propagation'): double ns3::LogDistancePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3MatrixPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::MatrixPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::MatrixPropagationLossModel::MatrixPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::MatrixPropagationLossModel::SetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, double loss, bool symmetric=true) [member function] cls.add_method('SetLoss', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('double', 'loss'), param('bool', 'symmetric', default_value='true')]) ## propagation-loss-model.h (module 'propagation'): void ns3::MatrixPropagationLossModel::SetDefaultLoss(double arg0) [member function] cls.add_method('SetDefaultLoss', 'void', [param('double', 'arg0')]) ## propagation-loss-model.h (module 'propagation'): double ns3::MatrixPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3NakagamiPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::NakagamiPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::NakagamiPropagationLossModel::NakagamiPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): double ns3::NakagamiPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::NotifyDeviceAdded(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('NotifyDeviceAdded', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')], visibility='private', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) return def register_Ns3RandomVariableChecker_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::RandomVariableChecker::RandomVariableChecker() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::RandomVariableChecker::RandomVariableChecker(ns3::RandomVariableChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomVariableChecker const &', 'arg0')]) return def register_Ns3RandomVariableValue_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::RandomVariableValue::RandomVariableValue() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::RandomVariableValue::RandomVariableValue(ns3::RandomVariableValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomVariableValue const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::RandomVariableValue::RandomVariableValue(ns3::RandomVariable const & value) [constructor] cls.add_constructor([param('ns3::RandomVariable const &', 'value')]) ## random-variable.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::RandomVariableValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## random-variable.h (module 'core'): bool ns3::RandomVariableValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## random-variable.h (module 'core'): ns3::RandomVariable ns3::RandomVariableValue::Get() const [member function] cls.add_method('Get', 'ns3::RandomVariable', [], is_const=True) ## random-variable.h (module 'core'): std::string ns3::RandomVariableValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## random-variable.h (module 'core'): void ns3::RandomVariableValue::Set(ns3::RandomVariable const & value) [member function] cls.add_method('Set', 'void', [param('ns3::RandomVariable const &', 'value')]) return def register_Ns3SimpleOfdmWimaxPhy_methods(root_module, cls): ## simple-ofdm-wimax-phy.h (module 'wimax'): ns3::SimpleOfdmWimaxPhy::SimpleOfdmWimaxPhy(ns3::SimpleOfdmWimaxPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::SimpleOfdmWimaxPhy const &', 'arg0')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): ns3::SimpleOfdmWimaxPhy::SimpleOfdmWimaxPhy() [constructor] cls.add_constructor([]) ## simple-ofdm-wimax-phy.h (module 'wimax'): ns3::SimpleOfdmWimaxPhy::SimpleOfdmWimaxPhy(char * tracesPath) [constructor] cls.add_constructor([param('char *', 'tracesPath')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::ActivateLoss(bool loss) [member function] cls.add_method('ActivateLoss', 'void', [param('bool', 'loss')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::DoAttach(ns3::Ptr<ns3::WimaxChannel> channel) [member function] cls.add_method('DoAttach', 'void', [param('ns3::Ptr< ns3::WimaxChannel >', 'channel')], is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): uint32_t ns3::SimpleOfdmWimaxPhy::GetBandwidth() const [member function] cls.add_method('GetBandwidth', 'uint32_t', [], is_const=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): double ns3::SimpleOfdmWimaxPhy::GetNoiseFigure() const [member function] cls.add_method('GetNoiseFigure', 'double', [], is_const=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): ns3::WimaxPhy::PhyType ns3::SimpleOfdmWimaxPhy::GetPhyType() const [member function] cls.add_method('GetPhyType', 'ns3::WimaxPhy::PhyType', [], is_const=True, is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): double ns3::SimpleOfdmWimaxPhy::GetTxPower() const [member function] cls.add_method('GetTxPower', 'double', [], is_const=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): static ns3::TypeId ns3::SimpleOfdmWimaxPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::NotifyRxBegin(ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('NotifyRxBegin', 'void', [param('ns3::Ptr< ns3::PacketBurst >', 'burst')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::NotifyRxDrop(ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('NotifyRxDrop', 'void', [param('ns3::Ptr< ns3::PacketBurst >', 'burst')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::NotifyRxEnd(ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('NotifyRxEnd', 'void', [param('ns3::Ptr< ns3::PacketBurst >', 'burst')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::NotifyTxBegin(ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('NotifyTxBegin', 'void', [param('ns3::Ptr< ns3::PacketBurst >', 'burst')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::NotifyTxDrop(ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('NotifyTxDrop', 'void', [param('ns3::Ptr< ns3::PacketBurst >', 'burst')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::NotifyTxEnd(ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('NotifyTxEnd', 'void', [param('ns3::Ptr< ns3::PacketBurst >', 'burst')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::Send(ns3::Ptr<ns3::PacketBurst> burst, ns3::WimaxPhy::ModulationType modulationType, uint8_t direction) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::PacketBurst >', 'burst'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('uint8_t', 'direction')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::Send(ns3::SendParams * params) [member function] cls.add_method('Send', 'void', [param('ns3::SendParams *', 'params')], is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::SetBandwidth(uint32_t BW) [member function] cls.add_method('SetBandwidth', 'void', [param('uint32_t', 'BW')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::SetNoiseFigure(double nf) [member function] cls.add_method('SetNoiseFigure', 'void', [param('double', 'nf')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::SetReceiveCallback(ns3::Callback<void,ns3::Ptr<ns3::PacketBurst>,ns3::Ptr<ns3::WimaxConnection>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::PacketBurst >, ns3::Ptr< ns3::WimaxConnection >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::SetSNRToBlockErrorRateTracesPath(char * tracesPath) [member function] cls.add_method('SetSNRToBlockErrorRateTracesPath', 'void', [param('char *', 'tracesPath')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::SetTxPower(double txPower) [member function] cls.add_method('SetTxPower', 'void', [param('double', 'txPower')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::StartReceive(uint32_t burstSize, bool isFirstBlock, uint64_t frequency, ns3::WimaxPhy::ModulationType modulationType, uint8_t direction, double rxPower, ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('StartReceive', 'void', [param('uint32_t', 'burstSize'), param('bool', 'isFirstBlock'), param('uint64_t', 'frequency'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('uint8_t', 'direction'), param('double', 'rxPower'), param('ns3::Ptr< ns3::PacketBurst >', 'burst')]) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): uint32_t ns3::SimpleOfdmWimaxPhy::DoGetDataRate(ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('DoGetDataRate', 'uint32_t', [param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): ns3::Time ns3::SimpleOfdmWimaxPhy::DoGetFrameDuration(uint8_t frameDurationCode) const [member function] cls.add_method('DoGetFrameDuration', 'ns3::Time', [param('uint8_t', 'frameDurationCode')], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): uint8_t ns3::SimpleOfdmWimaxPhy::DoGetFrameDurationCode() const [member function] cls.add_method('DoGetFrameDurationCode', 'uint8_t', [], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): double ns3::SimpleOfdmWimaxPhy::DoGetGValue() const [member function] cls.add_method('DoGetGValue', 'double', [], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): uint16_t ns3::SimpleOfdmWimaxPhy::DoGetNfft() const [member function] cls.add_method('DoGetNfft', 'uint16_t', [], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): uint64_t ns3::SimpleOfdmWimaxPhy::DoGetNrBytes(uint32_t symbols, ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('DoGetNrBytes', 'uint64_t', [param('uint32_t', 'symbols'), param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): uint64_t ns3::SimpleOfdmWimaxPhy::DoGetNrSymbols(uint32_t size, ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('DoGetNrSymbols', 'uint64_t', [param('uint32_t', 'size'), param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): uint16_t ns3::SimpleOfdmWimaxPhy::DoGetRtg() const [member function] cls.add_method('DoGetRtg', 'uint16_t', [], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): double ns3::SimpleOfdmWimaxPhy::DoGetSamplingFactor() const [member function] cls.add_method('DoGetSamplingFactor', 'double', [], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): double ns3::SimpleOfdmWimaxPhy::DoGetSamplingFrequency() const [member function] cls.add_method('DoGetSamplingFrequency', 'double', [], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): ns3::Time ns3::SimpleOfdmWimaxPhy::DoGetTransmissionTime(uint32_t size, ns3::WimaxPhy::ModulationType modulationType) const [member function] cls.add_method('DoGetTransmissionTime', 'ns3::Time', [param('uint32_t', 'size'), param('ns3::WimaxPhy::ModulationType', 'modulationType')], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): uint16_t ns3::SimpleOfdmWimaxPhy::DoGetTtg() const [member function] cls.add_method('DoGetTtg', 'uint16_t', [], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::DoSetDataRates() [member function] cls.add_method('DoSetDataRates', 'void', [], visibility='private', is_virtual=True) ## simple-ofdm-wimax-phy.h (module 'wimax'): void ns3::SimpleOfdmWimaxPhy::DoSetPhyParameters() [member function] cls.add_method('DoSetPhyParameters', 'void', [], visibility='private', is_virtual=True) return def register_Ns3TimeChecker_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker(ns3::TimeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeChecker const &', 'arg0')]) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3UintegerValue_methods(root_module, cls): ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor] cls.add_constructor([]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor] cls.add_constructor([param('uint64_t const &', 'value')]) ## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function] cls.add_method('Get', 'uint64_t', [], is_const=True) ## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function] cls.add_method('Set', 'void', [param('uint64_t const &', 'value')]) return def register_Ns3WimaxChannel_methods(root_module, cls): ## wimax-channel.h (module 'wimax'): ns3::WimaxChannel::WimaxChannel(ns3::WimaxChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::WimaxChannel const &', 'arg0')]) ## wimax-channel.h (module 'wimax'): ns3::WimaxChannel::WimaxChannel() [constructor] cls.add_constructor([]) ## wimax-channel.h (module 'wimax'): void ns3::WimaxChannel::Attach(ns3::Ptr<ns3::WimaxPhy> phy) [member function] cls.add_method('Attach', 'void', [param('ns3::Ptr< ns3::WimaxPhy >', 'phy')]) ## wimax-channel.h (module 'wimax'): ns3::Ptr<ns3::NetDevice> ns3::WimaxChannel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## wimax-channel.h (module 'wimax'): uint32_t ns3::WimaxChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-channel.h (module 'wimax'): void ns3::WimaxChannel::DoAttach(ns3::Ptr<ns3::WimaxPhy> phy) [member function] cls.add_method('DoAttach', 'void', [param('ns3::Ptr< ns3::WimaxPhy >', 'phy')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wimax-channel.h (module 'wimax'): ns3::Ptr<ns3::NetDevice> ns3::WimaxChannel::DoGetDevice(uint32_t i) const [member function] cls.add_method('DoGetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wimax-channel.h (module 'wimax'): uint32_t ns3::WimaxChannel::DoGetNDevices() const [member function] cls.add_method('DoGetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3WimaxNetDevice_methods(root_module, cls): ## wimax-net-device.h (module 'wimax'): ns3::WimaxNetDevice::m_direction [variable] cls.add_static_attribute('m_direction', 'uint8_t', is_const=False) ## wimax-net-device.h (module 'wimax'): ns3::WimaxNetDevice::m_frameStartTime [variable] cls.add_static_attribute('m_frameStartTime', 'ns3::Time', is_const=False) ## wimax-net-device.h (module 'wimax'): ns3::WimaxNetDevice::m_traceRx [variable] cls.add_instance_attribute('m_traceRx', 'ns3::TracedCallback< ns3::Ptr< ns3::Packet const >, ns3::Mac48Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', is_const=False) ## wimax-net-device.h (module 'wimax'): ns3::WimaxNetDevice::m_traceTx [variable] cls.add_instance_attribute('m_traceTx', 'ns3::TracedCallback< ns3::Ptr< ns3::Packet const >, ns3::Mac48Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', is_const=False) ## wimax-net-device.h (module 'wimax'): static ns3::TypeId ns3::WimaxNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wimax-net-device.h (module 'wimax'): ns3::WimaxNetDevice::WimaxNetDevice() [constructor] cls.add_constructor([]) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetTtg(uint16_t ttg) [member function] cls.add_method('SetTtg', 'void', [param('uint16_t', 'ttg')]) ## wimax-net-device.h (module 'wimax'): uint16_t ns3::WimaxNetDevice::GetTtg() const [member function] cls.add_method('GetTtg', 'uint16_t', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetRtg(uint16_t rtg) [member function] cls.add_method('SetRtg', 'void', [param('uint16_t', 'rtg')]) ## wimax-net-device.h (module 'wimax'): uint16_t ns3::WimaxNetDevice::GetRtg() const [member function] cls.add_method('GetRtg', 'uint16_t', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::Attach(ns3::Ptr<ns3::WimaxChannel> channel) [member function] cls.add_method('Attach', 'void', [param('ns3::Ptr< ns3::WimaxChannel >', 'channel')]) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetPhy(ns3::Ptr<ns3::WimaxPhy> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::WimaxPhy >', 'phy')]) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::WimaxPhy> ns3::WimaxNetDevice::GetPhy() const [member function] cls.add_method('GetPhy', 'ns3::Ptr< ns3::WimaxPhy >', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetChannel(ns3::Ptr<ns3::WimaxChannel> wimaxChannel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::WimaxChannel >', 'wimaxChannel')]) ## wimax-net-device.h (module 'wimax'): uint64_t ns3::WimaxNetDevice::GetChannel(uint8_t index) const [member function] cls.add_method('GetChannel', 'uint64_t', [param('uint8_t', 'index')], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetNrFrames(uint32_t nrFrames) [member function] cls.add_method('SetNrFrames', 'void', [param('uint32_t', 'nrFrames')]) ## wimax-net-device.h (module 'wimax'): uint32_t ns3::WimaxNetDevice::GetNrFrames() const [member function] cls.add_method('GetNrFrames', 'uint32_t', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetMacAddress(ns3::Mac48Address address) [member function] cls.add_method('SetMacAddress', 'void', [param('ns3::Mac48Address', 'address')]) ## wimax-net-device.h (module 'wimax'): ns3::Mac48Address ns3::WimaxNetDevice::GetMacAddress() const [member function] cls.add_method('GetMacAddress', 'ns3::Mac48Address', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetState(uint8_t state) [member function] cls.add_method('SetState', 'void', [param('uint8_t', 'state')]) ## wimax-net-device.h (module 'wimax'): uint8_t ns3::WimaxNetDevice::GetState() const [member function] cls.add_method('GetState', 'uint8_t', [], is_const=True) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::WimaxConnection> ns3::WimaxNetDevice::GetInitialRangingConnection() const [member function] cls.add_method('GetInitialRangingConnection', 'ns3::Ptr< ns3::WimaxConnection >', [], is_const=True) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::WimaxConnection> ns3::WimaxNetDevice::GetBroadcastConnection() const [member function] cls.add_method('GetBroadcastConnection', 'ns3::Ptr< ns3::WimaxConnection >', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetCurrentDcd(ns3::Dcd dcd) [member function] cls.add_method('SetCurrentDcd', 'void', [param('ns3::Dcd', 'dcd')]) ## wimax-net-device.h (module 'wimax'): ns3::Dcd ns3::WimaxNetDevice::GetCurrentDcd() const [member function] cls.add_method('GetCurrentDcd', 'ns3::Dcd', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetCurrentUcd(ns3::Ucd ucd) [member function] cls.add_method('SetCurrentUcd', 'void', [param('ns3::Ucd', 'ucd')]) ## wimax-net-device.h (module 'wimax'): ns3::Ucd ns3::WimaxNetDevice::GetCurrentUcd() const [member function] cls.add_method('GetCurrentUcd', 'ns3::Ucd', [], is_const=True) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::ConnectionManager> ns3::WimaxNetDevice::GetConnectionManager() const [member function] cls.add_method('GetConnectionManager', 'ns3::Ptr< ns3::ConnectionManager >', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetConnectionManager(ns3::Ptr<ns3::ConnectionManager> connectionManager) [member function] cls.add_method('SetConnectionManager', 'void', [param('ns3::Ptr< ns3::ConnectionManager >', 'connectionManager')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::BurstProfileManager> ns3::WimaxNetDevice::GetBurstProfileManager() const [member function] cls.add_method('GetBurstProfileManager', 'ns3::Ptr< ns3::BurstProfileManager >', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetBurstProfileManager(ns3::Ptr<ns3::BurstProfileManager> burstProfileManager) [member function] cls.add_method('SetBurstProfileManager', 'void', [param('ns3::Ptr< ns3::BurstProfileManager >', 'burstProfileManager')]) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::BandwidthManager> ns3::WimaxNetDevice::GetBandwidthManager() const [member function] cls.add_method('GetBandwidthManager', 'ns3::Ptr< ns3::BandwidthManager >', [], is_const=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetBandwidthManager(ns3::Ptr<ns3::BandwidthManager> bandwidthManager) [member function] cls.add_method('SetBandwidthManager', 'void', [param('ns3::Ptr< ns3::BandwidthManager >', 'bandwidthManager')]) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::CreateDefaultConnections() [member function] cls.add_method('CreateDefaultConnections', 'void', []) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::Start() [member function] cls.add_method('Start', 'void', [], is_pure_virtual=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::Stop() [member function] cls.add_method('Stop', 'void', [], is_pure_virtual=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetReceiveCallback() [member function] cls.add_method('SetReceiveCallback', 'void', []) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::ForwardUp(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address const & source, ns3::Mac48Address const & dest) [member function] cls.add_method('ForwardUp', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address const &', 'source'), param('ns3::Mac48Address const &', 'dest')]) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::Enqueue(ns3::Ptr<ns3::Packet> packet, ns3::MacHeaderType const & hdrType, ns3::Ptr<ns3::WimaxConnection> connection) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::MacHeaderType const &', 'hdrType'), param('ns3::Ptr< ns3::WimaxConnection >', 'connection')], is_pure_virtual=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::ForwardDown(ns3::Ptr<ns3::PacketBurst> burst, ns3::WimaxPhy::ModulationType modulationType) [member function] cls.add_method('ForwardDown', 'void', [param('ns3::Ptr< ns3::PacketBurst >', 'burst'), param('ns3::WimaxPhy::ModulationType', 'modulationType')]) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetName(std::string const name) [member function] cls.add_method('SetName', 'void', [param('std::string const', 'name')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): std::string ns3::WimaxNetDevice::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): uint32_t ns3::WimaxNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::Channel> ns3::WimaxNetDevice::GetPhyChannel() const [member function] cls.add_method('GetPhyChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::Channel> ns3::WimaxNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Address ns3::WimaxNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): uint16_t ns3::WimaxNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Address ns3::WimaxNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Address ns3::WimaxNetDevice::GetMulticast() const [member function] cls.add_method('GetMulticast', 'ns3::Address', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Address ns3::WimaxNetDevice::MakeMulticastAddress(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('MakeMulticastAddress', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::Node> ns3::WimaxNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> ns3::WimaxNetDevice::GetPromiscReceiveCallback() [member function] cls.add_method('GetPromiscReceiveCallback', 'ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', []) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Address ns3::WimaxNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Address ns3::WimaxNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::IsPromisc() [member function] cls.add_method('IsPromisc', 'bool', []) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::NotifyPromiscTrace(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('NotifyPromiscTrace', 'void', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## wimax-net-device.h (module 'wimax'): bool ns3::WimaxNetDevice::DoSend(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address const & source, ns3::Mac48Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('DoSend', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address const &', 'source'), param('ns3::Mac48Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wimax-net-device.h (module 'wimax'): void ns3::WimaxNetDevice::DoReceive(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('DoReceive', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wimax-net-device.h (module 'wimax'): ns3::Ptr<ns3::WimaxChannel> ns3::WimaxNetDevice::DoGetChannel() const [member function] cls.add_method('DoGetChannel', 'ns3::Ptr< ns3::WimaxChannel >', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3BaseStationNetDevice_methods(root_module, cls): ## bs-net-device.h (module 'wimax'): static ns3::TypeId ns3::BaseStationNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bs-net-device.h (module 'wimax'): ns3::BaseStationNetDevice::BaseStationNetDevice() [constructor] cls.add_constructor([]) ## bs-net-device.h (module 'wimax'): ns3::BaseStationNetDevice::BaseStationNetDevice(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::WimaxPhy> phy) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::WimaxPhy >', 'phy')]) ## bs-net-device.h (module 'wimax'): ns3::BaseStationNetDevice::BaseStationNetDevice(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::WimaxPhy> phy, ns3::Ptr<ns3::UplinkScheduler> uplinkScheduler, ns3::Ptr<ns3::BSScheduler> bsScheduler) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::WimaxPhy >', 'phy'), param('ns3::Ptr< ns3::UplinkScheduler >', 'uplinkScheduler'), param('ns3::Ptr< ns3::BSScheduler >', 'bsScheduler')]) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetInitialRangingInterval(ns3::Time initialRangInterval) [member function] cls.add_method('SetInitialRangingInterval', 'void', [param('ns3::Time', 'initialRangInterval')]) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::InitBaseStationNetDevice() [member function] cls.add_method('InitBaseStationNetDevice', 'void', []) ## bs-net-device.h (module 'wimax'): ns3::Time ns3::BaseStationNetDevice::GetInitialRangingInterval() const [member function] cls.add_method('GetInitialRangingInterval', 'ns3::Time', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetDcdInterval(ns3::Time dcdInterval) [member function] cls.add_method('SetDcdInterval', 'void', [param('ns3::Time', 'dcdInterval')]) ## bs-net-device.h (module 'wimax'): ns3::Time ns3::BaseStationNetDevice::GetDcdInterval() const [member function] cls.add_method('GetDcdInterval', 'ns3::Time', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetUcdInterval(ns3::Time ucdInterval) [member function] cls.add_method('SetUcdInterval', 'void', [param('ns3::Time', 'ucdInterval')]) ## bs-net-device.h (module 'wimax'): ns3::Time ns3::BaseStationNetDevice::GetUcdInterval() const [member function] cls.add_method('GetUcdInterval', 'ns3::Time', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetIntervalT8(ns3::Time interval) [member function] cls.add_method('SetIntervalT8', 'void', [param('ns3::Time', 'interval')]) ## bs-net-device.h (module 'wimax'): ns3::Time ns3::BaseStationNetDevice::GetIntervalT8() const [member function] cls.add_method('GetIntervalT8', 'ns3::Time', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetMaxRangingCorrectionRetries(uint8_t maxRangCorrectionRetries) [member function] cls.add_method('SetMaxRangingCorrectionRetries', 'void', [param('uint8_t', 'maxRangCorrectionRetries')]) ## bs-net-device.h (module 'wimax'): uint8_t ns3::BaseStationNetDevice::GetMaxRangingCorrectionRetries() const [member function] cls.add_method('GetMaxRangingCorrectionRetries', 'uint8_t', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetMaxInvitedRangRetries(uint8_t maxInvitedRangRetries) [member function] cls.add_method('SetMaxInvitedRangRetries', 'void', [param('uint8_t', 'maxInvitedRangRetries')]) ## bs-net-device.h (module 'wimax'): uint8_t ns3::BaseStationNetDevice::GetMaxInvitedRangRetries() const [member function] cls.add_method('GetMaxInvitedRangRetries', 'uint8_t', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetRangReqOppSize(uint8_t rangReqOppSize) [member function] cls.add_method('SetRangReqOppSize', 'void', [param('uint8_t', 'rangReqOppSize')]) ## bs-net-device.h (module 'wimax'): uint8_t ns3::BaseStationNetDevice::GetRangReqOppSize() const [member function] cls.add_method('GetRangReqOppSize', 'uint8_t', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetBwReqOppSize(uint8_t bwReqOppSize) [member function] cls.add_method('SetBwReqOppSize', 'void', [param('uint8_t', 'bwReqOppSize')]) ## bs-net-device.h (module 'wimax'): uint8_t ns3::BaseStationNetDevice::GetBwReqOppSize() const [member function] cls.add_method('GetBwReqOppSize', 'uint8_t', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetNrDlSymbols(uint32_t dlSymbols) [member function] cls.add_method('SetNrDlSymbols', 'void', [param('uint32_t', 'dlSymbols')]) ## bs-net-device.h (module 'wimax'): uint32_t ns3::BaseStationNetDevice::GetNrDlSymbols() const [member function] cls.add_method('GetNrDlSymbols', 'uint32_t', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetNrUlSymbols(uint32_t ulSymbols) [member function] cls.add_method('SetNrUlSymbols', 'void', [param('uint32_t', 'ulSymbols')]) ## bs-net-device.h (module 'wimax'): uint32_t ns3::BaseStationNetDevice::GetNrUlSymbols() const [member function] cls.add_method('GetNrUlSymbols', 'uint32_t', [], is_const=True) ## bs-net-device.h (module 'wimax'): uint32_t ns3::BaseStationNetDevice::GetNrDcdSent() const [member function] cls.add_method('GetNrDcdSent', 'uint32_t', [], is_const=True) ## bs-net-device.h (module 'wimax'): uint32_t ns3::BaseStationNetDevice::GetNrUcdSent() const [member function] cls.add_method('GetNrUcdSent', 'uint32_t', [], is_const=True) ## bs-net-device.h (module 'wimax'): ns3::Time ns3::BaseStationNetDevice::GetDlSubframeStartTime() const [member function] cls.add_method('GetDlSubframeStartTime', 'ns3::Time', [], is_const=True) ## bs-net-device.h (module 'wimax'): ns3::Time ns3::BaseStationNetDevice::GetUlSubframeStartTime() const [member function] cls.add_method('GetUlSubframeStartTime', 'ns3::Time', [], is_const=True) ## bs-net-device.h (module 'wimax'): uint8_t ns3::BaseStationNetDevice::GetRangingOppNumber() const [member function] cls.add_method('GetRangingOppNumber', 'uint8_t', [], is_const=True) ## bs-net-device.h (module 'wimax'): ns3::Ptr<ns3::SSManager> ns3::BaseStationNetDevice::GetSSManager() const [member function] cls.add_method('GetSSManager', 'ns3::Ptr< ns3::SSManager >', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetSSManager(ns3::Ptr<ns3::SSManager> ssManager) [member function] cls.add_method('SetSSManager', 'void', [param('ns3::Ptr< ns3::SSManager >', 'ssManager')]) ## bs-net-device.h (module 'wimax'): ns3::Ptr<ns3::UplinkScheduler> ns3::BaseStationNetDevice::GetUplinkScheduler() const [member function] cls.add_method('GetUplinkScheduler', 'ns3::Ptr< ns3::UplinkScheduler >', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetUplinkScheduler(ns3::Ptr<ns3::UplinkScheduler> ulScheduler) [member function] cls.add_method('SetUplinkScheduler', 'void', [param('ns3::Ptr< ns3::UplinkScheduler >', 'ulScheduler')]) ## bs-net-device.h (module 'wimax'): ns3::Ptr<ns3::BSLinkManager> ns3::BaseStationNetDevice::GetLinkManager() const [member function] cls.add_method('GetLinkManager', 'ns3::Ptr< ns3::BSLinkManager >', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetBSScheduler(ns3::Ptr<ns3::BSScheduler> bsSchedule) [member function] cls.add_method('SetBSScheduler', 'void', [param('ns3::Ptr< ns3::BSScheduler >', 'bsSchedule')]) ## bs-net-device.h (module 'wimax'): ns3::Ptr<ns3::BSScheduler> ns3::BaseStationNetDevice::GetBSScheduler() const [member function] cls.add_method('GetBSScheduler', 'ns3::Ptr< ns3::BSScheduler >', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetLinkManager(ns3::Ptr<ns3::BSLinkManager> linkManager) [member function] cls.add_method('SetLinkManager', 'void', [param('ns3::Ptr< ns3::BSLinkManager >', 'linkManager')]) ## bs-net-device.h (module 'wimax'): ns3::Ptr<ns3::IpcsClassifier> ns3::BaseStationNetDevice::GetBsClassifier() const [member function] cls.add_method('GetBsClassifier', 'ns3::Ptr< ns3::IpcsClassifier >', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetBsClassifier(ns3::Ptr<ns3::IpcsClassifier> classifier) [member function] cls.add_method('SetBsClassifier', 'void', [param('ns3::Ptr< ns3::IpcsClassifier >', 'classifier')]) ## bs-net-device.h (module 'wimax'): ns3::Time ns3::BaseStationNetDevice::GetPsDuration() const [member function] cls.add_method('GetPsDuration', 'ns3::Time', [], is_const=True) ## bs-net-device.h (module 'wimax'): ns3::Time ns3::BaseStationNetDevice::GetSymbolDuration() const [member function] cls.add_method('GetSymbolDuration', 'ns3::Time', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## bs-net-device.h (module 'wimax'): bool ns3::BaseStationNetDevice::Enqueue(ns3::Ptr<ns3::Packet> packet, ns3::MacHeaderType const & hdrType, ns3::Ptr<ns3::WimaxConnection> connection) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::MacHeaderType const &', 'hdrType'), param('ns3::Ptr< ns3::WimaxConnection >', 'connection')], is_virtual=True) ## bs-net-device.h (module 'wimax'): ns3::Ptr<ns3::WimaxConnection> ns3::BaseStationNetDevice::GetConnection(ns3::Cid cid) [member function] cls.add_method('GetConnection', 'ns3::Ptr< ns3::WimaxConnection >', [param('ns3::Cid', 'cid')]) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::MarkUplinkAllocations() [member function] cls.add_method('MarkUplinkAllocations', 'void', []) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::MarkRangingOppStart(ns3::Time rangingOppStartTime) [member function] cls.add_method('MarkRangingOppStart', 'void', [param('ns3::Time', 'rangingOppStartTime')]) ## bs-net-device.h (module 'wimax'): ns3::Ptr<ns3::BsServiceFlowManager> ns3::BaseStationNetDevice::GetServiceFlowManager() const [member function] cls.add_method('GetServiceFlowManager', 'ns3::Ptr< ns3::BsServiceFlowManager >', [], is_const=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::SetServiceFlowManager(ns3::Ptr<ns3::BsServiceFlowManager> arg0) [member function] cls.add_method('SetServiceFlowManager', 'void', [param('ns3::Ptr< ns3::BsServiceFlowManager >', 'arg0')]) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## bs-net-device.h (module 'wimax'): bool ns3::BaseStationNetDevice::DoSend(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address const & source, ns3::Mac48Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('DoSend', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address const &', 'source'), param('ns3::Mac48Address const &', 'dest'), param('uint16_t', 'protocolNumber')], visibility='private', is_virtual=True) ## bs-net-device.h (module 'wimax'): void ns3::BaseStationNetDevice::DoReceive(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('DoReceive', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')], visibility='private', is_virtual=True) return def register_Ns3SimpleOfdmWimaxChannel_methods(root_module, cls): ## simple-ofdm-wimax-channel.h (module 'wimax'): ns3::SimpleOfdmWimaxChannel::SimpleOfdmWimaxChannel(ns3::SimpleOfdmWimaxChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SimpleOfdmWimaxChannel const &', 'arg0')]) ## simple-ofdm-wimax-channel.h (module 'wimax'): ns3::SimpleOfdmWimaxChannel::SimpleOfdmWimaxChannel() [constructor] cls.add_constructor([]) ## simple-ofdm-wimax-channel.h (module 'wimax'): ns3::SimpleOfdmWimaxChannel::SimpleOfdmWimaxChannel(ns3::SimpleOfdmWimaxChannel::PropModel propModel) [constructor] cls.add_constructor([param('ns3::SimpleOfdmWimaxChannel::PropModel', 'propModel')]) ## simple-ofdm-wimax-channel.h (module 'wimax'): void ns3::SimpleOfdmWimaxChannel::Send(ns3::Time BlockTime, uint32_t burstSize, ns3::Ptr<ns3::WimaxPhy> phy, bool isFirstBlock, bool isLastBlock, uint64_t frequency, ns3::WimaxPhy::ModulationType modulationType, uint8_t direction, double txPowerDbm, ns3::Ptr<ns3::PacketBurst> burst) [member function] cls.add_method('Send', 'void', [param('ns3::Time', 'BlockTime'), param('uint32_t', 'burstSize'), param('ns3::Ptr< ns3::WimaxPhy >', 'phy'), param('bool', 'isFirstBlock'), param('bool', 'isLastBlock'), param('uint64_t', 'frequency'), param('ns3::WimaxPhy::ModulationType', 'modulationType'), param('uint8_t', 'direction'), param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::PacketBurst >', 'burst')]) ## simple-ofdm-wimax-channel.h (module 'wimax'): void ns3::SimpleOfdmWimaxChannel::SetPropagationModel(ns3::SimpleOfdmWimaxChannel::PropModel propModel) [member function] cls.add_method('SetPropagationModel', 'void', [param('ns3::SimpleOfdmWimaxChannel::PropModel', 'propModel')]) ## simple-ofdm-wimax-channel.h (module 'wimax'): void ns3::SimpleOfdmWimaxChannel::DoAttach(ns3::Ptr<ns3::WimaxPhy> phy) [member function] cls.add_method('DoAttach', 'void', [param('ns3::Ptr< ns3::WimaxPhy >', 'phy')], visibility='private', is_virtual=True) ## simple-ofdm-wimax-channel.h (module 'wimax'): ns3::Ptr<ns3::NetDevice> ns3::SimpleOfdmWimaxChannel::DoGetDevice(uint32_t i) const [member function] cls.add_method('DoGetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True, visibility='private', is_virtual=True) ## simple-ofdm-wimax-channel.h (module 'wimax'): uint32_t ns3::SimpleOfdmWimaxChannel::DoGetNDevices() const [member function] cls.add_method('DoGetNDevices', 'uint32_t', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3SubscriberStationNetDevice_methods(root_module, cls): ## ss-net-device.h (module 'wimax'): ns3::SubscriberStationNetDevice::m_linkManager [variable] cls.add_instance_attribute('m_linkManager', 'ns3::Ptr< ns3::SSLinkManager >', is_const=False) ## ss-net-device.h (module 'wimax'): static ns3::TypeId ns3::SubscriberStationNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ss-net-device.h (module 'wimax'): ns3::SubscriberStationNetDevice::SubscriberStationNetDevice() [constructor] cls.add_constructor([]) ## ss-net-device.h (module 'wimax'): ns3::SubscriberStationNetDevice::SubscriberStationNetDevice(ns3::Ptr<ns3::Node> arg0, ns3::Ptr<ns3::WimaxPhy> arg1) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'arg0'), param('ns3::Ptr< ns3::WimaxPhy >', 'arg1')]) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::InitSubscriberStationNetDevice() [member function] cls.add_method('InitSubscriberStationNetDevice', 'void', []) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetLostDlMapInterval(ns3::Time lostDlMapInterval) [member function] cls.add_method('SetLostDlMapInterval', 'void', [param('ns3::Time', 'lostDlMapInterval')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetLostDlMapInterval() const [member function] cls.add_method('GetLostDlMapInterval', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetLostUlMapInterval(ns3::Time lostUlMapInterval) [member function] cls.add_method('SetLostUlMapInterval', 'void', [param('ns3::Time', 'lostUlMapInterval')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetLostUlMapInterval() const [member function] cls.add_method('GetLostUlMapInterval', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetMaxDcdInterval(ns3::Time maxDcdInterval) [member function] cls.add_method('SetMaxDcdInterval', 'void', [param('ns3::Time', 'maxDcdInterval')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetMaxDcdInterval() const [member function] cls.add_method('GetMaxDcdInterval', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetMaxUcdInterval(ns3::Time maxUcdInterval) [member function] cls.add_method('SetMaxUcdInterval', 'void', [param('ns3::Time', 'maxUcdInterval')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetMaxUcdInterval() const [member function] cls.add_method('GetMaxUcdInterval', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetIntervalT1(ns3::Time interval1) [member function] cls.add_method('SetIntervalT1', 'void', [param('ns3::Time', 'interval1')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetIntervalT1() const [member function] cls.add_method('GetIntervalT1', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetIntervalT2(ns3::Time interval2) [member function] cls.add_method('SetIntervalT2', 'void', [param('ns3::Time', 'interval2')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetIntervalT2() const [member function] cls.add_method('GetIntervalT2', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetIntervalT3(ns3::Time interval3) [member function] cls.add_method('SetIntervalT3', 'void', [param('ns3::Time', 'interval3')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetIntervalT3() const [member function] cls.add_method('GetIntervalT3', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetIntervalT7(ns3::Time interval7) [member function] cls.add_method('SetIntervalT7', 'void', [param('ns3::Time', 'interval7')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetIntervalT7() const [member function] cls.add_method('GetIntervalT7', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetIntervalT12(ns3::Time interval12) [member function] cls.add_method('SetIntervalT12', 'void', [param('ns3::Time', 'interval12')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetIntervalT12() const [member function] cls.add_method('GetIntervalT12', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetIntervalT20(ns3::Time interval20) [member function] cls.add_method('SetIntervalT20', 'void', [param('ns3::Time', 'interval20')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetIntervalT20() const [member function] cls.add_method('GetIntervalT20', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetIntervalT21(ns3::Time interval21) [member function] cls.add_method('SetIntervalT21', 'void', [param('ns3::Time', 'interval21')]) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetIntervalT21() const [member function] cls.add_method('GetIntervalT21', 'ns3::Time', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetMaxContentionRangingRetries(uint8_t maxContentionRangingRetries) [member function] cls.add_method('SetMaxContentionRangingRetries', 'void', [param('uint8_t', 'maxContentionRangingRetries')]) ## ss-net-device.h (module 'wimax'): uint8_t ns3::SubscriberStationNetDevice::GetMaxContentionRangingRetries() const [member function] cls.add_method('GetMaxContentionRangingRetries', 'uint8_t', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetBasicConnection(ns3::Ptr<ns3::WimaxConnection> basicConnection) [member function] cls.add_method('SetBasicConnection', 'void', [param('ns3::Ptr< ns3::WimaxConnection >', 'basicConnection')]) ## ss-net-device.h (module 'wimax'): ns3::Ptr<ns3::WimaxConnection> ns3::SubscriberStationNetDevice::GetBasicConnection() const [member function] cls.add_method('GetBasicConnection', 'ns3::Ptr< ns3::WimaxConnection >', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetPrimaryConnection(ns3::Ptr<ns3::WimaxConnection> primaryConnection) [member function] cls.add_method('SetPrimaryConnection', 'void', [param('ns3::Ptr< ns3::WimaxConnection >', 'primaryConnection')]) ## ss-net-device.h (module 'wimax'): ns3::Ptr<ns3::WimaxConnection> ns3::SubscriberStationNetDevice::GetPrimaryConnection() const [member function] cls.add_method('GetPrimaryConnection', 'ns3::Ptr< ns3::WimaxConnection >', [], is_const=True) ## ss-net-device.h (module 'wimax'): ns3::Cid ns3::SubscriberStationNetDevice::GetBasicCid() const [member function] cls.add_method('GetBasicCid', 'ns3::Cid', [], is_const=True) ## ss-net-device.h (module 'wimax'): ns3::Cid ns3::SubscriberStationNetDevice::GetPrimaryCid() const [member function] cls.add_method('GetPrimaryCid', 'ns3::Cid', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetModulationType(ns3::WimaxPhy::ModulationType modulationType) [member function] cls.add_method('SetModulationType', 'void', [param('ns3::WimaxPhy::ModulationType', 'modulationType')]) ## ss-net-device.h (module 'wimax'): ns3::WimaxPhy::ModulationType ns3::SubscriberStationNetDevice::GetModulationType() const [member function] cls.add_method('GetModulationType', 'ns3::WimaxPhy::ModulationType', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetAreManagementConnectionsAllocated(bool areManagementConnectionsAllocated) [member function] cls.add_method('SetAreManagementConnectionsAllocated', 'void', [param('bool', 'areManagementConnectionsAllocated')]) ## ss-net-device.h (module 'wimax'): bool ns3::SubscriberStationNetDevice::GetAreManagementConnectionsAllocated() const [member function] cls.add_method('GetAreManagementConnectionsAllocated', 'bool', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetAreServiceFlowsAllocated(bool areServiceFlowsAllocated) [member function] cls.add_method('SetAreServiceFlowsAllocated', 'void', [param('bool', 'areServiceFlowsAllocated')]) ## ss-net-device.h (module 'wimax'): bool ns3::SubscriberStationNetDevice::GetAreServiceFlowsAllocated() const [member function] cls.add_method('GetAreServiceFlowsAllocated', 'bool', [], is_const=True) ## ss-net-device.h (module 'wimax'): ns3::Ptr<ns3::SSScheduler> ns3::SubscriberStationNetDevice::GetScheduler() const [member function] cls.add_method('GetScheduler', 'ns3::Ptr< ns3::SSScheduler >', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetScheduler(ns3::Ptr<ns3::SSScheduler> ssScheduler) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::Ptr< ns3::SSScheduler >', 'ssScheduler')]) ## ss-net-device.h (module 'wimax'): bool ns3::SubscriberStationNetDevice::HasServiceFlows() const [member function] cls.add_method('HasServiceFlows', 'bool', [], is_const=True) ## ss-net-device.h (module 'wimax'): bool ns3::SubscriberStationNetDevice::Enqueue(ns3::Ptr<ns3::Packet> packet, ns3::MacHeaderType const & hdrType, ns3::Ptr<ns3::WimaxConnection> connection) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::MacHeaderType const &', 'hdrType'), param('ns3::Ptr< ns3::WimaxConnection >', 'connection')], is_virtual=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SendBurst(uint8_t uiuc, uint16_t nrSymbols, ns3::Ptr<ns3::WimaxConnection> connection, ns3::MacHeaderType::HeaderType packetType=::ns3::MacHeaderType::HEADER_TYPE_GENERIC) [member function] cls.add_method('SendBurst', 'void', [param('uint8_t', 'uiuc'), param('uint16_t', 'nrSymbols'), param('ns3::Ptr< ns3::WimaxConnection >', 'connection'), param('ns3::MacHeaderType::HeaderType', 'packetType', default_value='::ns3::MacHeaderType::HEADER_TYPE_GENERIC')]) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::AddServiceFlow(ns3::ServiceFlow * sf) [member function] cls.add_method('AddServiceFlow', 'void', [param('ns3::ServiceFlow *', 'sf')]) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::AddServiceFlow(ns3::ServiceFlow sf) [member function] cls.add_method('AddServiceFlow', 'void', [param('ns3::ServiceFlow', 'sf')]) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetTimer(ns3::EventId eventId, ns3::EventId & event) [member function] cls.add_method('SetTimer', 'void', [param('ns3::EventId', 'eventId'), param('ns3::EventId &', 'event')]) ## ss-net-device.h (module 'wimax'): bool ns3::SubscriberStationNetDevice::IsRegistered() const [member function] cls.add_method('IsRegistered', 'bool', [], is_const=True) ## ss-net-device.h (module 'wimax'): ns3::Time ns3::SubscriberStationNetDevice::GetTimeToAllocation(ns3::Time defferTime) [member function] cls.add_method('GetTimeToAllocation', 'ns3::Time', [param('ns3::Time', 'defferTime')]) ## ss-net-device.h (module 'wimax'): ns3::Ptr<ns3::IpcsClassifier> ns3::SubscriberStationNetDevice::GetIpcsClassifier() const [member function] cls.add_method('GetIpcsClassifier', 'ns3::Ptr< ns3::IpcsClassifier >', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetIpcsPacketClassifier(ns3::Ptr<ns3::IpcsClassifier> arg0) [member function] cls.add_method('SetIpcsPacketClassifier', 'void', [param('ns3::Ptr< ns3::IpcsClassifier >', 'arg0')]) ## ss-net-device.h (module 'wimax'): ns3::Ptr<ns3::SSLinkManager> ns3::SubscriberStationNetDevice::GetLinkManager() const [member function] cls.add_method('GetLinkManager', 'ns3::Ptr< ns3::SSLinkManager >', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetLinkManager(ns3::Ptr<ns3::SSLinkManager> arg0) [member function] cls.add_method('SetLinkManager', 'void', [param('ns3::Ptr< ns3::SSLinkManager >', 'arg0')]) ## ss-net-device.h (module 'wimax'): ns3::Ptr<ns3::SsServiceFlowManager> ns3::SubscriberStationNetDevice::GetServiceFlowManager() const [member function] cls.add_method('GetServiceFlowManager', 'ns3::Ptr< ns3::SsServiceFlowManager >', [], is_const=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::SetServiceFlowManager(ns3::Ptr<ns3::SsServiceFlowManager> arg0) [member function] cls.add_method('SetServiceFlowManager', 'void', [param('ns3::Ptr< ns3::SsServiceFlowManager >', 'arg0')]) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## ss-net-device.h (module 'wimax'): bool ns3::SubscriberStationNetDevice::DoSend(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address const & source, ns3::Mac48Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('DoSend', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address const &', 'source'), param('ns3::Mac48Address const &', 'dest'), param('uint16_t', 'protocolNumber')], visibility='private', is_virtual=True) ## ss-net-device.h (module 'wimax'): void ns3::SubscriberStationNetDevice::DoReceive(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('DoReceive', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')], visibility='private', is_virtual=True) return def register_functions(root_module): module = root_module ## crc8.h (module 'wimax'): extern uint8_t ns3::CRC8Calculate(uint8_t const * data, int length) [free function] module.add_function('CRC8Calculate', 'uint8_t', [param('uint8_t const *', 'data'), param('int', 'length')]) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_internal(module.get_submodule('internal'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_internal(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
gpl-2.0
-860,766,160,695,467,900
63.299965
748
0.607314
false
aterrel/dynd-python
dynd/tests/test_python_scalar.py
1
3627
import sys import unittest from dynd import nd, ndt from datetime import date if sys.version_info >= (3, 0): unicode = str class TestPythonScalar(unittest.TestCase): def test_bool(self): # Boolean true/false a = nd.array(True) self.assertEqual(nd.type_of(a), ndt.bool) self.assertEqual(type(nd.as_py(a)), bool) self.assertEqual(nd.as_py(a), True) a = nd.array(False) self.assertEqual(nd.type_of(a), ndt.bool) self.assertEqual(type(nd.as_py(a)), bool) self.assertEqual(nd.as_py(a), False) def test_int(self): # Integer that fits in 32 bits a = nd.array(10) self.assertEqual(nd.type_of(a), ndt.int32) self.assertEqual(type(nd.as_py(a)), int) self.assertEqual(nd.as_py(a), 10) a = nd.array(-2000000000) self.assertEqual(nd.type_of(a), ndt.int32) self.assertEqual(type(nd.as_py(a)), int) self.assertEqual(nd.as_py(a), -2000000000) # Integer that requires 64 bits a = nd.array(2200000000) self.assertEqual(nd.type_of(a), ndt.int64) self.assertEqual(nd.as_py(a), 2200000000) a = nd.array(-2200000000) self.assertEqual(nd.type_of(a), ndt.int64) self.assertEqual(nd.as_py(a), -2200000000) def test_float(self): # Floating point a = nd.array(5.125) self.assertEqual(nd.type_of(a), ndt.float64) self.assertEqual(type(nd.as_py(a)), float) self.assertEqual(nd.as_py(a), 5.125) def test_complex(self): # Complex floating point a = nd.array(5.125 - 2.5j) self.assertEqual(nd.type_of(a), ndt.complex_float64) self.assertEqual(type(nd.as_py(a)), complex) self.assertEqual(nd.as_py(a), 5.125 - 2.5j) def test_date(self): # Date a = nd.array(date(2012,12,12)) self.assertEqual(nd.type_of(a), ndt.date) self.assertEqual(type(nd.as_py(a)), date) self.assertEqual(nd.as_py(a), date(2012,12,12)) def test_string(self): a = nd.array('abcdef') self.assertEqual(nd.type_of(a), ndt.string) self.assertEqual(type(nd.as_py(a)), unicode) self.assertEqual(nd.as_py(a), u'abcdef') a = nd.array(u'abcdef') self.assertEqual(nd.type_of(a), ndt.string) self.assertEqual(type(nd.as_py(a)), unicode) self.assertEqual(nd.as_py(a), u'abcdef') def test_utf_encodings(self): # Ensure all of the UTF encodings work ok for a basic string x = u'\uc548\ub155 hello' # UTF-8 a = nd.array(x) a = a.ucast(ndt.make_fixedstring(16, 'utf_8')) a = a.eval() self.assertEqual(nd.type_of(a), ndt.make_fixedstring(16, 'utf_8')) self.assertEqual(type(nd.as_py(a)), unicode) self.assertEqual(nd.as_py(a), x) # UTF-16 a = nd.array(x) a = a.ucast(ndt.make_fixedstring(8, 'utf_16')) a = a.eval() self.assertEqual(nd.type_of(a), ndt.make_fixedstring(8, 'utf_16')) self.assertEqual(type(nd.as_py(a)), unicode) self.assertEqual(nd.as_py(a), x) # UTF-32 a = nd.array(x) a = a.ucast(ndt.make_fixedstring(8, 'utf_32')) a = a.eval() self.assertEqual(nd.type_of(a), ndt.make_fixedstring(8, 'utf_32')) self.assertEqual(type(nd.as_py(a)), unicode) self.assertEqual(nd.as_py(a), x) def test_len(self): # Can't get the length of a zero-dimensional dynd array a = nd.array(10) self.assertRaises(ValueError, len, a) if __name__ == '__main__': unittest.main()
bsd-2-clause
3,345,892,055,432,648,700
34.558824
74
0.584505
false
XiaosongWei/crosswalk-test-suite
webapi/tct-package-tizen-tests/inst.wgt.py
4
6752
#!/usr/bin/env python import os import shutil import glob import time import sys import subprocess import string from optparse import OptionParser, make_option SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PKG_NAME = os.path.basename(SCRIPT_DIR) PARAMETERS = None #XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/5000/dbus/user_bus_socket" SRC_DIR = "" PKG_SRC_DIR = "" def doCMD(cmd): # Do not need handle timeout in this short script, let tool do it print "-->> \"%s\"" % cmd output = [] cmd_return_code = 1 cmd_proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) while True: output_line = cmd_proc.stdout.readline().strip("\r\n") cmd_return_code = cmd_proc.poll() if output_line == '' and cmd_return_code is not None: break sys.stdout.write("%s\n" % output_line) sys.stdout.flush() output.append(output_line) return (cmd_return_code, output) def updateCMD(cmd=None): if "pkgcmd" in cmd: cmd = "su - %s -c '%s;%s'" % (PARAMETERS.user, XW_ENV, cmd) return cmd def getUSERID(): if PARAMETERS.mode == "SDB": cmd = "sdb -s %s shell id -u %s" % ( PARAMETERS.device, PARAMETERS.user) else: cmd = "ssh %s \"id -u %s\"" % ( PARAMETERS.device, PARAMETERS.user) return doCMD(cmd) def getPKGID(pkg_name=None): if PARAMETERS.mode == "SDB": cmd = "sdb -s %s shell %s" % ( PARAMETERS.device, updateCMD('pkgcmd -l')) else: cmd = "ssh %s \"%s\"" % ( PARAMETERS.device, updateCMD('pkgcmd -l')) (return_code, output) = doCMD(cmd) if return_code != 0: return None test_pkg_id = None for line in output: if line.find("[" + pkg_name + "]") != -1: pkgidIndex = line.split().index("pkgid") test_pkg_id = line.split()[pkgidIndex + 1].strip("[]") break return test_pkg_id def doRemoteCMD(cmd=None): if PARAMETERS.mode == "SDB": cmd = "sdb -s %s shell %s" % (PARAMETERS.device, updateCMD(cmd)) else: cmd = "ssh %s \"%s\"" % (PARAMETERS.device, updateCMD(cmd)) return doCMD(cmd) def doRemoteCopy(src=None, dest=None): if PARAMETERS.mode == "SDB": cmd_prefix = "sdb -s %s push" % PARAMETERS.device cmd = "%s %s %s" % (cmd_prefix, src, dest) else: cmd = "scp -r %s %s:/%s" % (src, PARAMETERS.device, dest) (return_code, output) = doCMD(cmd) doRemoteCMD("sync") if return_code != 0: return True else: return False def uninstPKGs(): action_status = True for root, dirs, files in os.walk(SCRIPT_DIR): if root.endswith("mediasrc"): continue for file in files: if file.endswith(".wgt"): pkg_id = getPKGID(os.path.basename(os.path.splitext(file)[0])) if not pkg_id: action_status = False continue (return_code, output) = doRemoteCMD( "pkgcmd -u -t wgt -q -n %s" % pkg_id) for line in output: if "Failure" in line: action_status = False break (return_code, output) = doRemoteCMD( "rm -rf %s" % PKG_SRC_DIR) if return_code != 0: action_status = False (return_code, output) = doRemoteCMD( "rm -rf %s/Others" % SRC_DIR) if return_code != 0: action_status = False return action_status def instPKGs(): action_status = True (return_code, output) = doRemoteCMD( "mkdir -p %s" % PKG_SRC_DIR) if return_code != 0: action_status = False for root, dirs, files in os.walk(SCRIPT_DIR): if root.endswith("mediasrc"): continue for file in files: if file.endswith(".wgt"): if not doRemoteCopy( os.path.join(root, file), "%s/%s" % (SRC_DIR, file)): action_status = False (return_code, output) = doRemoteCMD( "pkgcmd -i -t wgt -q -p %s/%s" % (SRC_DIR, file)) doRemoteCMD("rm -rf %s/%s" % (SRC_DIR, file)) for line in output: if "Failure" in line: action_status = False break if not doRemoteCopy("%s/mediasrc" % SCRIPT_DIR, "%s/Others" % SRC_DIR): action_status = False return action_status def main(): try: usage = "usage: inst.py -i" opts_parser = OptionParser(usage=usage) opts_parser.add_option( "-m", dest="mode", action="store", help="Specify mode") opts_parser.add_option( "-s", dest="device", action="store", help="Specify device") opts_parser.add_option( "-i", dest="binstpkg", action="store_true", help="Install package") opts_parser.add_option( "-u", dest="buninstpkg", action="store_true", help="Uninstall package") opts_parser.add_option( "-a", dest="user", action="store", help="User name") global PARAMETERS (PARAMETERS, args) = opts_parser.parse_args() except Exception as e: print "Got wrong option: %s, exit ..." % e sys.exit(1) if not PARAMETERS.user: PARAMETERS.user = "app" global SRC_DIR, PKG_SRC_DIR SRC_DIR = "/home/%s/content" % PARAMETERS.user PKG_SRC_DIR = "%s/tct/opt/%s" % (SRC_DIR, PKG_NAME) if not PARAMETERS.mode: PARAMETERS.mode = "SDB" if PARAMETERS.mode == "SDB": if not PARAMETERS.device: (return_code, output) = doCMD("sdb devices") for line in output: if str.find(line, "\tdevice") != -1: PARAMETERS.device = line.split("\t")[0] break else: PARAMETERS.mode = "SSH" if not PARAMETERS.device: print "No device provided" sys.exit(1) user_info = getUSERID() re_code = user_info[0] if re_code == 0: global XW_ENV userid = user_info[1][0] XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/%s/dbus/user_bus_socket" % str( userid) else: print "[Error] cmd commands error : %s" % str(user_info[1]) sys.exit(1) if PARAMETERS.binstpkg and PARAMETERS.buninstpkg: print "-i and -u are conflict" sys.exit(1) if PARAMETERS.buninstpkg: if not uninstPKGs(): sys.exit(1) else: if not instPKGs(): sys.exit(1) if __name__ == "__main__": main() sys.exit(0)
bsd-3-clause
1,754,156,531,313,168,100
28.229437
101
0.540581
false
kawasaki2013/python-for-android-x86
python-modules/twisted/twisted/trial/test/suppression.py
61
1357
# -*- test-case-name: twisted.trial.test.test_tests -*- # Copyright (c) 2008 Twisted Matrix Laboratories. # See LICENSE for details. """ Test cases used to make sure that warning supression works at the module, method, and class levels. """ import warnings from twisted.trial import unittest, util METHOD_WARNING_MSG = "method warning message" CLASS_WARNING_MSG = "class warning message" MODULE_WARNING_MSG = "module warning message" class MethodWarning(Warning): pass class ClassWarning(Warning): pass class ModuleWarning(Warning): pass class EmitMixin: def _emit(self): warnings.warn(METHOD_WARNING_MSG, MethodWarning) warnings.warn(CLASS_WARNING_MSG, ClassWarning) warnings.warn(MODULE_WARNING_MSG, ModuleWarning) class TestSuppression(unittest.TestCase, EmitMixin): def testSuppressMethod(self): self._emit() testSuppressMethod.suppress = [util.suppress(message=METHOD_WARNING_MSG)] def testSuppressClass(self): self._emit() def testOverrideSuppressClass(self): self._emit() testOverrideSuppressClass.suppress = [] TestSuppression.suppress = [util.suppress(message=CLASS_WARNING_MSG)] class TestSuppression2(unittest.TestCase, EmitMixin): def testSuppressModule(self): self._emit() suppress = [util.suppress(message=MODULE_WARNING_MSG)]
apache-2.0
1,610,576,381,281,320,700
22.807018
77
0.725866
false
chugunovyar/factoryForBuild
env/lib/python2.7/site-packages/scipy/sparse/linalg/_expm_multiply.py
82
20126
"""Compute the action of the matrix exponential. """ from __future__ import division, print_function, absolute_import import numpy as np import scipy.linalg import scipy.sparse.linalg from scipy.sparse.linalg import LinearOperator, aslinearoperator __all__ = ['expm_multiply'] def _exact_inf_norm(A): # A compatibility function which should eventually disappear. if scipy.sparse.isspmatrix(A): return max(abs(A).sum(axis=1).flat) else: return np.linalg.norm(A, np.inf) def _exact_1_norm(A): # A compatibility function which should eventually disappear. if scipy.sparse.isspmatrix(A): return max(abs(A).sum(axis=0).flat) else: return np.linalg.norm(A, 1) def _trace(A): # A compatibility function which should eventually disappear. if scipy.sparse.isspmatrix(A): return A.diagonal().sum() else: return np.trace(A) def _ident_like(A): # A compatibility function which should eventually disappear. if scipy.sparse.isspmatrix(A): return scipy.sparse.construct.eye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format) else: return np.eye(A.shape[0], A.shape[1], dtype=A.dtype) def expm_multiply(A, B, start=None, stop=None, num=None, endpoint=None): """ Compute the action of the matrix exponential of A on B. Parameters ---------- A : transposable linear operator The operator whose exponential is of interest. B : ndarray The matrix or vector to be multiplied by the matrix exponential of A. start : scalar, optional The starting time point of the sequence. stop : scalar, optional The end time point of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced time points, so that `stop` is excluded. Note that the step size changes when `endpoint` is False. num : int, optional Number of time points to use. endpoint : bool, optional If True, `stop` is the last time point. Otherwise, it is not included. Returns ------- expm_A_B : ndarray The result of the action :math:`e^{t_k A} B`. Notes ----- The optional arguments defining the sequence of evenly spaced time points are compatible with the arguments of `numpy.linspace`. The output ndarray shape is somewhat complicated so I explain it here. The ndim of the output could be either 1, 2, or 3. It would be 1 if you are computing the expm action on a single vector at a single time point. It would be 2 if you are computing the expm action on a vector at multiple time points, or if you are computing the expm action on a matrix at a single time point. It would be 3 if you want the action on a matrix with multiple columns at multiple time points. If multiple time points are requested, expm_A_B[0] will always be the action of the expm at the first time point, regardless of whether the action is on a vector or a matrix. References ---------- .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2011) "Computing the Action of the Matrix Exponential, with an Application to Exponential Integrators." SIAM Journal on Scientific Computing, 33 (2). pp. 488-511. ISSN 1064-8275 http://eprints.ma.man.ac.uk/1591/ .. [2] Nicholas J. Higham and Awad H. Al-Mohy (2010) "Computing Matrix Functions." Acta Numerica, 19. 159-208. ISSN 0962-4929 http://eprints.ma.man.ac.uk/1451/ """ if all(arg is None for arg in (start, stop, num, endpoint)): X = _expm_multiply_simple(A, B) else: X, status = _expm_multiply_interval(A, B, start, stop, num, endpoint) return X def _expm_multiply_simple(A, B, t=1.0, balance=False): """ Compute the action of the matrix exponential at a single time point. Parameters ---------- A : transposable linear operator The operator whose exponential is of interest. B : ndarray The matrix to be multiplied by the matrix exponential of A. t : float A time point. balance : bool Indicates whether or not to apply balancing. Returns ------- F : ndarray :math:`e^{t A} B` Notes ----- This is algorithm (3.2) in Al-Mohy and Higham (2011). """ if balance: raise NotImplementedError if len(A.shape) != 2 or A.shape[0] != A.shape[1]: raise ValueError('expected A to be like a square matrix') if A.shape[1] != B.shape[0]: raise ValueError('the matrices A and B have incompatible shapes') ident = _ident_like(A) n = A.shape[0] if len(B.shape) == 1: n0 = 1 elif len(B.shape) == 2: n0 = B.shape[1] else: raise ValueError('expected B to be like a matrix or a vector') u_d = 2**-53 tol = u_d mu = _trace(A) / float(n) A = A - mu * ident A_1_norm = _exact_1_norm(A) if t*A_1_norm == 0: m_star, s = 0, 1 else: ell = 2 norm_info = LazyOperatorNormInfo(t*A, A_1_norm=t*A_1_norm, ell=ell) m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell) return _expm_multiply_simple_core(A, B, t, mu, m_star, s, tol, balance) def _expm_multiply_simple_core(A, B, t, mu, m_star, s, tol=None, balance=False): """ A helper function. """ if balance: raise NotImplementedError if tol is None: u_d = 2 ** -53 tol = u_d F = B eta = np.exp(t*mu / float(s)) for i in range(s): c1 = _exact_inf_norm(B) for j in range(m_star): coeff = t / float(s*(j+1)) B = coeff * A.dot(B) c2 = _exact_inf_norm(B) F = F + B if c1 + c2 <= tol * _exact_inf_norm(F): break c1 = c2 F = eta * F B = F return F # This table helps to compute bounds. # They seem to have been difficult to calculate, involving symbolic # manipulation of equations, followed by numerical root finding. _theta = { # The first 30 values are from table A.3 of Computing Matrix Functions. 1: 2.29e-16, 2: 2.58e-8, 3: 1.39e-5, 4: 3.40e-4, 5: 2.40e-3, 6: 9.07e-3, 7: 2.38e-2, 8: 5.00e-2, 9: 8.96e-2, 10: 1.44e-1, # 11 11: 2.14e-1, 12: 3.00e-1, 13: 4.00e-1, 14: 5.14e-1, 15: 6.41e-1, 16: 7.81e-1, 17: 9.31e-1, 18: 1.09, 19: 1.26, 20: 1.44, # 21 21: 1.62, 22: 1.82, 23: 2.01, 24: 2.22, 25: 2.43, 26: 2.64, 27: 2.86, 28: 3.08, 29: 3.31, 30: 3.54, # The rest are from table 3.1 of # Computing the Action of the Matrix Exponential. 35: 4.7, 40: 6.0, 45: 7.2, 50: 8.5, 55: 9.9, } def _onenormest_matrix_power(A, p, t=2, itmax=5, compute_v=False, compute_w=False): """ Efficiently estimate the 1-norm of A^p. Parameters ---------- A : ndarray Matrix whose 1-norm of a power is to be computed. p : int Non-negative integer power. t : int, optional A positive parameter controlling the tradeoff between accuracy versus time and memory usage. Larger values take longer and use more memory but give more accurate output. itmax : int, optional Use at most this many iterations. compute_v : bool, optional Request a norm-maximizing linear operator input vector if True. compute_w : bool, optional Request a norm-maximizing linear operator output vector if True. Returns ------- est : float An underestimate of the 1-norm of the sparse matrix. v : ndarray, optional The vector such that ||Av||_1 == est*||v||_1. It can be thought of as an input to the linear operator that gives an output with particularly large norm. w : ndarray, optional The vector Av which has relatively large 1-norm. It can be thought of as an output of the linear operator that is relatively large in norm compared to the input. """ #XXX Eventually turn this into an API function in the _onenormest module, #XXX and remove its underscore, #XXX but wait until expm_multiply goes into scipy. return scipy.sparse.linalg.onenormest(aslinearoperator(A) ** p) class LazyOperatorNormInfo: """ Information about an operator is lazily computed. The information includes the exact 1-norm of the operator, in addition to estimates of 1-norms of powers of the operator. This uses the notation of Computing the Action (2011). This class is specialized enough to probably not be of general interest outside of this module. """ def __init__(self, A, A_1_norm=None, ell=2): """ Provide the operator and some norm-related information. Parameters ---------- A : linear operator The operator of interest. A_1_norm : float, optional The exact 1-norm of A. ell : int, optional A technical parameter controlling norm estimation quality. """ self._A = A self._A_1_norm = A_1_norm self._ell = ell self._d = {} def onenorm(self): """ Compute the exact 1-norm. """ if self._A_1_norm is None: self._A_1_norm = _exact_1_norm(self._A) return self._A_1_norm def d(self, p): """ Lazily estimate d_p(A) ~= || A^p ||^(1/p) where ||.|| is the 1-norm. """ if p not in self._d: est = _onenormest_matrix_power(self._A, p, self._ell) self._d[p] = est ** (1.0 / p) return self._d[p] def alpha(self, p): """ Lazily compute max(d(p), d(p+1)). """ return max(self.d(p), self.d(p+1)) def _compute_cost_div_m(m, p, norm_info): """ A helper function for computing bounds. This is equation (3.10). It measures cost in terms of the number of required matrix products. Parameters ---------- m : int A valid key of _theta. p : int A matrix power. norm_info : LazyOperatorNormInfo Information about 1-norms of related operators. Returns ------- cost_div_m : int Required number of matrix products divided by m. """ return int(np.ceil(norm_info.alpha(p) / _theta[m])) def _compute_p_max(m_max): """ Compute the largest positive integer p such that p*(p-1) <= m_max + 1. Do this in a slightly dumb way, but safe and not too slow. Parameters ---------- m_max : int A count related to bounds. """ sqrt_m_max = np.sqrt(m_max) p_low = int(np.floor(sqrt_m_max)) p_high = int(np.ceil(sqrt_m_max + 1)) return max(p for p in range(p_low, p_high+1) if p*(p-1) <= m_max + 1) def _fragment_3_1(norm_info, n0, tol, m_max=55, ell=2): """ A helper function for the _expm_multiply_* functions. Parameters ---------- norm_info : LazyOperatorNormInfo Information about norms of certain linear operators of interest. n0 : int Number of columns in the _expm_multiply_* B matrix. tol : float Expected to be :math:`2^{-24}` for single precision or :math:`2^{-53}` for double precision. m_max : int A value related to a bound. ell : int The number of columns used in the 1-norm approximation. This is usually taken to be small, maybe between 1 and 5. Returns ------- best_m : int Related to bounds for error control. best_s : int Amount of scaling. Notes ----- This is code fragment (3.1) in Al-Mohy and Higham (2011). The discussion of default values for m_max and ell is given between the definitions of equation (3.11) and the definition of equation (3.12). """ if ell < 1: raise ValueError('expected ell to be a positive integer') best_m = None best_s = None if _condition_3_13(norm_info.onenorm(), n0, m_max, ell): for m, theta in _theta.items(): s = int(np.ceil(norm_info.onenorm() / theta)) if best_m is None or m * s < best_m * best_s: best_m = m best_s = s else: # Equation (3.11). for p in range(2, _compute_p_max(m_max) + 1): for m in range(p*(p-1)-1, m_max+1): if m in _theta: s = _compute_cost_div_m(m, p, norm_info) if best_m is None or m * s < best_m * best_s: best_m = m best_s = s best_s = max(best_s, 1) return best_m, best_s def _condition_3_13(A_1_norm, n0, m_max, ell): """ A helper function for the _expm_multiply_* functions. Parameters ---------- A_1_norm : float The precomputed 1-norm of A. n0 : int Number of columns in the _expm_multiply_* B matrix. m_max : int A value related to a bound. ell : int The number of columns used in the 1-norm approximation. This is usually taken to be small, maybe between 1 and 5. Returns ------- value : bool Indicates whether or not the condition has been met. Notes ----- This is condition (3.13) in Al-Mohy and Higham (2011). """ # This is the rhs of equation (3.12). p_max = _compute_p_max(m_max) a = 2 * ell * p_max * (p_max + 3) # Evaluate the condition (3.13). b = _theta[m_max] / float(n0 * m_max) return A_1_norm <= a * b def _expm_multiply_interval(A, B, start=None, stop=None, num=None, endpoint=None, balance=False, status_only=False): """ Compute the action of the matrix exponential at multiple time points. Parameters ---------- A : transposable linear operator The operator whose exponential is of interest. B : ndarray The matrix to be multiplied by the matrix exponential of A. start : scalar, optional The starting time point of the sequence. stop : scalar, optional The end time point of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced time points, so that `stop` is excluded. Note that the step size changes when `endpoint` is False. num : int, optional Number of time points to use. endpoint : bool, optional If True, `stop` is the last time point. Otherwise, it is not included. balance : bool Indicates whether or not to apply balancing. status_only : bool A flag that is set to True for some debugging and testing operations. Returns ------- F : ndarray :math:`e^{t_k A} B` status : int An integer status for testing and debugging. Notes ----- This is algorithm (5.2) in Al-Mohy and Higham (2011). There seems to be a typo, where line 15 of the algorithm should be moved to line 6.5 (between lines 6 and 7). """ if balance: raise NotImplementedError if len(A.shape) != 2 or A.shape[0] != A.shape[1]: raise ValueError('expected A to be like a square matrix') if A.shape[1] != B.shape[0]: raise ValueError('the matrices A and B have incompatible shapes') ident = _ident_like(A) n = A.shape[0] if len(B.shape) == 1: n0 = 1 elif len(B.shape) == 2: n0 = B.shape[1] else: raise ValueError('expected B to be like a matrix or a vector') u_d = 2**-53 tol = u_d mu = _trace(A) / float(n) # Get the linspace samples, attempting to preserve the linspace defaults. linspace_kwargs = {'retstep': True} if num is not None: linspace_kwargs['num'] = num if endpoint is not None: linspace_kwargs['endpoint'] = endpoint samples, step = np.linspace(start, stop, **linspace_kwargs) # Convert the linspace output to the notation used by the publication. nsamples = len(samples) if nsamples < 2: raise ValueError('at least two time points are required') q = nsamples - 1 h = step t_0 = samples[0] t_q = samples[q] # Define the output ndarray. # Use an ndim=3 shape, such that the last two indices # are the ones that may be involved in level 3 BLAS operations. X_shape = (nsamples,) + B.shape X = np.empty(X_shape, dtype=float) t = t_q - t_0 A = A - mu * ident A_1_norm = _exact_1_norm(A) if t*A_1_norm == 0: m_star, s = 0, 1 else: ell = 2 norm_info = LazyOperatorNormInfo(t*A, A_1_norm=t*A_1_norm, ell=ell) m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell) # Compute the expm action up to the initial time point. X[0] = _expm_multiply_simple_core(A, B, t_0, mu, m_star, s) # Compute the expm action at the rest of the time points. if q <= s: if status_only: return 0 else: return _expm_multiply_interval_core_0(A, X, h, mu, m_star, s, q) elif q > s and not (q % s): if status_only: return 1 else: return _expm_multiply_interval_core_1(A, X, h, mu, m_star, s, q, tol) elif q > s and (q % s): if status_only: return 2 else: return _expm_multiply_interval_core_2(A, X, h, mu, m_star, s, q, tol) else: raise Exception('internal error') def _expm_multiply_interval_core_0(A, X, h, mu, m_star, s, q): """ A helper function, for the case q <= s. """ for k in range(q): X[k+1] = _expm_multiply_simple_core(A, X[k], h, mu, m_star, s) return X, 0 def _expm_multiply_interval_core_1(A, X, h, mu, m_star, s, q, tol): """ A helper function, for the case q > s and q % s == 0. """ d = q // s input_shape = X.shape[1:] K_shape = (m_star + 1, ) + input_shape K = np.empty(K_shape, dtype=float) for i in range(s): Z = X[i*d] K[0] = Z high_p = 0 for k in range(1, d+1): F = K[0] c1 = _exact_inf_norm(F) for p in range(1, m_star+1): if p > high_p: K[p] = h * A.dot(K[p-1]) / float(p) coeff = float(pow(k, p)) F = F + coeff * K[p] inf_norm_K_p_1 = _exact_inf_norm(K[p]) c2 = coeff * inf_norm_K_p_1 if c1 + c2 <= tol * _exact_inf_norm(F): break c1 = c2 X[k + i*d] = np.exp(k*h*mu) * F return X, 1 def _expm_multiply_interval_core_2(A, X, h, mu, m_star, s, q, tol): """ A helper function, for the case q > s and q % s > 0. """ d = q // s j = q // d r = q - d * j input_shape = X.shape[1:] K_shape = (m_star + 1, ) + input_shape K = np.empty(K_shape, dtype=float) for i in range(j + 1): Z = X[i*d] K[0] = Z high_p = 0 if i < j: effective_d = d else: effective_d = r for k in range(1, effective_d+1): F = K[0] c1 = _exact_inf_norm(F) for p in range(1, m_star+1): if p == high_p + 1: K[p] = h * A.dot(K[p-1]) / float(p) high_p = p coeff = float(pow(k, p)) F = F + coeff * K[p] inf_norm_K_p_1 = _exact_inf_norm(K[p]) c2 = coeff * inf_norm_K_p_1 if c1 + c2 <= tol * _exact_inf_norm(F): break c1 = c2 X[k + i*d] = np.exp(k*h*mu) * F return X, 2
gpl-3.0
-675,685,019,988,497,700
29.310241
80
0.560519
false
talus-framework/talus-master
git_repo/template/talus/job.py
1
10393
#!/usr/bin/env python # encoding: utf-8 import ast import docutils import docutils.examples import inspect import logging import os import re import sys logging.basicConfig(level=logging.DEBUG) from talus.fileset import FileSet class TalusError(Exception): pass class PyFuncTypeComponent(object): def __init__(self, raw): self.raw = raw self.type = "component" match = re.match(r'^Component\(([a-zA-Z0-9_]+)\)$', raw) if match is None: raise TalusError("Could not determine the component name from: {!r}".format(raw)) self.name = match.group(1) class PyFuncTypeFileSet(object): def __init__(self): self.type = "fileset" self.name = "FileSet" class PyFuncTypeNative(object): def __init__(self, native_type): self.type = "native" if native_type not in ["str", "list", "tuple", "dict", "int", "float", "unicode", "bool"]: raise TalusError("Unsupported native type specified for parameter: {!r}".format(native_type)) self.name = native_type class PyFuncParam(object): def __init__(self, unparsed_name, desc): self.desc = desc self.type, self.name = self.get_type_and_name(unparsed_name) def get_type_and_name(self, data): parts = data.split() if len(parts) != 3: raise TalusError("Error! Param declarations need to be of the form" + "\n\n\t:param <type> <param-name>: <desc>" + "\n\nBut you gave:\n\n\t{}".format(data)) param, type, name = parts if type.startswith("Component"): type = PyFuncTypeComponent(type) elif type == "FileSet": type = PyFuncTypeFileSet() else: type = PyFuncTypeNative(type) return type, name class PyFunc(object): def __init__(self, log, filename, func_node): self.filename = filename self.node = func_node self.name = func_node.name self._log = log.getChild(self.name) self.doc = "" if hasattr(func_node.body[0], "value") and isinstance(func_node.body[0].value, ast.Str): self.doc = func_node.body[0].value.s try: self.params = self.get_params(self.doc) except TalusError as e: raise TalusError(e.message + "\n\nError at {}:{}".format(self.filename, self.node.lineno)) def get_params(self, docstring): self._log.debug("determining params") # these need to be IN ORDER!!!! params = [] doc, _ = docutils.examples.internals(unicode(docstring)) if len(doc.children) == 0: return params for quote in doc.children: if not isinstance(quote, docutils.nodes.block_quote): continue for field in quote: if not isinstance(field, docutils.nodes.field_list): continue for f in field: name = str(f[0][0]) desc = str(f[1][0][0]) # simple test to avoid :returns: and such if "param" in name: params.append(PyFuncParam(name, desc)) return params class PyClass(object): def __init__(self, log, filename, cls_node): self.filename = filename self._log = log.getChild(cls_node.name) if "components" in self.filename: self.type = "component" self.param_method = "init" elif "tools" in self.filename: self.type = "tool" self.param_method = "run" self.node = cls_node self.desc = "" self.name = cls_node.name self.bases = self.get_bases() self.methods = {} for idx, node in enumerate(cls_node.body): if idx == 0 and isinstance(node, ast.Expr) and isinstance(node.value, ast.Str): self.desc = node.value.s elif isinstance(node, ast.FunctionDef): method = PyFunc(self._log, filename, node) self.methods[method.name] = method def get_bases(self): res = [] for x in self.node.bases: if isinstance(x, ast.Attribute): res.append(x.attr) elif isinstance(x, ast.Name): res.append(x.id) return res def get_run_params(self, query_func): self._log.debug("getting run params") params = {} if self.param_method in self.methods: for param in self.methods[self.param_method].params: self._log.debug(" param: {} ({} - {})".format(param.name, param.type.type, param.type.name)) if param.type.type == "component" and not query_func(param.type.name): raise TalusError("Invalid component specified ({}) in {}:{}".format( param.type.name, self.filename, self.name )) params[param.name] = dict( name=param.name, type=dict( type=param.type.type, # native or component name=param.type.name # str/list/etc or component name ), desc=param.desc ) else: self._log.debug("no {} method was specified?".format(self.param_method)) return params class Job(object): """This is the class that will run a task.""" def __init__(self, id, idx, params, tool, fileset_id, progress_callback, results_callback): """TODO: to be defined1. :idx: TODO :params: TODO :tool: TODO :fileset_id: The id of the default fileset that files should be added to """ self._id = id self._idx = idx self._params = params self._tool = tool self._fileset_id = fileset_id self._fileset = FileSet(self._fileset_id) self._progress_callback = progress_callback self._results_callback = results_callback self._log = logging.getLogger("JOB:{}".format(self._id)) def add_file(self, contents, content_type="application/octet-stream", filename=None, **metadata): """Add a file to the default result fileset """ return self._fileset.add( contents=contents, filename=filename, content_type=content_type, **metadata ) def run(self): self._log.debug("preparing to run job") try: tool_cls = self._get_tool_cls() real_params = self._convert_params(self._params, tool_cls) tool = tool_cls( idx=self._idx, progress_cb=self._progress_callback, results_cb=self._results_callback, parent_log=self._log, job=self ) self._log.debug("RUNNING TOOL") tool.run(**real_params) except TalusError as e: self._log.error(e.message) self._log.debug("FINISHED RUNNING TOOL") def _camel_to_under(self, name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def _get_tool_cls(self): mod_name = self._camel_to_under(self._tool) mod = __import__("talus.tools." + mod_name, globals(), locals(), fromlist=[str(self._tool)]) return getattr(mod, self._tool) def _get_component_cls(self, cls_name): mod_name = self._camel_to_under(cls_name) mod_base = __import__("talus.components", globals(), locals(), fromlist=[str(mod_name)]) mod = getattr(mod_base, mod_name) return getattr(mod, cls_name) def _convert_params(self, params, code_cls): filename = inspect.getfile(code_cls) param_types = self._get_param_types(code_cls) real_params = {} for name, val in params.iteritems(): if name not in param_types: raise TalusError("unmapped argument: {!r}".format(name)) real_params[name] = self._convert_val(param_types[name]["type"], val) return real_params def _to_bool(self, val): if type(val) is bool: return val if type(val) is str: return val.lower() == "true" return not (not val) def _convert_val(self, param_type, val): if param_type["type"] == "native": switch = { "str": lambda x: str(x), "list": lambda x: list(x), "tuple": lambda x: tuple(x), "dict": lambda x: dict(x), "int": lambda x: int(x), "float": lambda x: float(x), "unicode": lambda x: unicode(x) "bool" : self._to_bool, } return switch[param_type["name"]](val) elif param_type["type"] == "fileset": val = FileSet(val) return val elif param_type["type"] == "component": # val should be like this: # { "class": "SpecificComponent", "params": {} } # # allow for inheritance by letting the json specify the # specific class that will be used component_cls = self._get_component_cls(val["class"]) component_args = self._convert_params(val["params"], component_cls) val = component_cls(parent_log=self._log, job=self) val.init(**component_args) return val def _get_param_types(self, cls): cls_name = cls.__name__ filename = inspect.getfile(cls) filename = filename.replace(".pyc", ".py") with open(filename, "r") as f: source = f.read() pyclass = None mod = ast.parse(source) for node in mod.body: if isinstance(node, ast.ClassDef): cls = PyClass(self._log, filename, node) if cls.name == cls_name: pyclass = cls break # make the query func always return true - this is assuming the # pre-receive hook has done its job and prevented invalid components # from slipping in return pyclass.get_run_params(lambda x: True)
bsd-3-clause
-8,976,641,196,884,589,000
31.993651
109
0.536611
false
infobloxopen/infoblox-netmri
infoblox_netmri/api/broker/v3_6_0/device_wireless_broker.py
16
73313
from ..broker import Broker class DeviceWirelessBroker(Broker): controller = "device_wirelesses" def index(self, **kwargs): """Lists the available device wirelesses. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using this method is most efficient. **Inputs** | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DeviceID: The internal NetMRI identifier of each device from which wireless setting was collected. :type DeviceID: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceID: The internal NetMRI identifier of each device from which wireless setting was collected. :type DeviceID: Array of Integer | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DeviceWirelessID: The internal NetMRI identifier of the device wireless. :type DeviceWirelessID: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceWirelessID: The internal NetMRI identifier of the device wireless. :type DeviceWirelessID: Array of Integer | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param InterfaceID: The internal NetMRI identifier of a local interface for the device wireless. :type InterfaceID: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param InterfaceID: The internal NetMRI identifier of a local interface for the device wireless. :type InterfaceID: Array of Integer | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param StationID: The internal NetMRI identifier of a station. :type StationID: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param StationID: The internal NetMRI identifier of a station. :type StationID: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceGroupID: The internal NetMRI identifier of the device groups to which to limit the results. :type DeviceGroupID: Array of Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param timestamp: The data returned will represent the device wirelesses as of this date and time. If omitted, the result will indicate the most recently collected data. :type timestamp: DateTime | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param methods: A list of device wireless methods. The listed methods will be called on each device wireless returned and included in the output. Available methods are: device, interface. :type methods: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param include: A list of associated object types to include in the output. The listed associations will be returned as outputs named according to the association name (see outputs below). Available includes are: device, interface. :type include: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 0 :param start: The record number to return in the selected page of data. It will always appear, although it may not be the first record. See the :limit for more information. :type start: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 1000 :param limit: The size of the page of data, that is, the maximum number of records returned. The limit size will be used to break the data up into pages and the first page with the start record will be returned. So if you have 100 records and use a :limit of 10 and a :start of 10, you will get records 10-19. The maximum limit is 10000. :type limit: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` DeviceWirelessID :param sort: The data field(s) to use for sorting the output. Default is DeviceWirelessID. Valid values are DeviceWirelessID, DeviceWirelessStartTime, DeviceWirelessEndTime, DeviceWirelessChangedCols, DeviceWirelessTimestamp, DataSourceID, DeviceID, ifIndex, InterfaceID, StationID, DesiredSSID, StationRole, WEPEnabledInd, WEPAllowedInd, WEPOnlyTrafficInd, WEPICVErrorCount, WEPDefaultKeyLen1, WEPDefaultKeyLen2, WEPDefaultKeyLen3, WEPDefaultKeyLen4. :type sort: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` asc :param dir: The direction(s) in which to sort the data. Default is 'asc'. Valid values are 'asc' and 'desc'. :type dir: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param select: The list of attributes to return for each DeviceWireless. Valid values are DeviceWirelessID, DeviceWirelessStartTime, DeviceWirelessEndTime, DeviceWirelessChangedCols, DeviceWirelessTimestamp, DataSourceID, DeviceID, ifIndex, InterfaceID, StationID, DesiredSSID, StationRole, WEPEnabledInd, WEPAllowedInd, WEPOnlyTrafficInd, WEPICVErrorCount, WEPDefaultKeyLen1, WEPDefaultKeyLen2, WEPDefaultKeyLen3, WEPDefaultKeyLen4. If empty or omitted, all attributes will be returned. :type select: Array | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_field: The field name for NIOS GOTO that is used for locating a row position of records. :type goto_field: String | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_value: The value of goto_field for NIOS GOTO that is used for locating a row position of records. :type goto_value: String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return device_wirelesses: An array of the DeviceWireless objects that match the specified input criteria. :rtype device_wirelesses: Array of DeviceWireless """ return self.api_list_request(self._get_method_fullname("index"), kwargs) def show(self, **kwargs): """Shows the details for the specified device wireless. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param DeviceWirelessID: The internal NetMRI identifier of the device wireless. :type DeviceWirelessID: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param methods: A list of device wireless methods. The listed methods will be called on each device wireless returned and included in the output. Available methods are: device, interface. :type methods: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param include: A list of associated object types to include in the output. The listed associations will be returned as outputs named according to the association name (see outputs below). Available includes are: device, interface. :type include: Array of String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return device_wireless: The device wireless identified by the specified DeviceWirelessID. :rtype device_wireless: DeviceWireless """ return self.api_request(self._get_method_fullname("show"), kwargs) def search(self, **kwargs): """Lists the available device wirelesses matching the input criteria. This method provides a more flexible search interface than the index method, but searching using this method is more demanding on the system and will not perform to the same level as the index method. The input fields listed below will be used as in the index method, to filter the result, along with the optional query string and XML filter described below. **Inputs** | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DataSourceID: The internal NetMRI identifier for the collector NetMRI that collected this data record. :type DataSourceID: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DataSourceID: The internal NetMRI identifier for the collector NetMRI that collected this data record. :type DataSourceID: Array of Integer | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DesiredSSID: The service set identifier(SSID) of desired wireless device. :type DesiredSSID: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DesiredSSID: The service set identifier(SSID) of desired wireless device. :type DesiredSSID: Array of String | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DeviceID: The internal NetMRI identifier of each device from which wireless setting was collected. :type DeviceID: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceID: The internal NetMRI identifier of each device from which wireless setting was collected. :type DeviceID: Array of Integer | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DeviceWirelessChangedCols: The fields that changed between this revision of the record and the previous revision. :type DeviceWirelessChangedCols: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceWirelessChangedCols: The fields that changed between this revision of the record and the previous revision. :type DeviceWirelessChangedCols: Array of String | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DeviceWirelessEndTime: The ending effective time of this record, or empty if still in effect. :type DeviceWirelessEndTime: DateTime | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceWirelessEndTime: The ending effective time of this record, or empty if still in effect. :type DeviceWirelessEndTime: Array of DateTime | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DeviceWirelessID: The internal NetMRI identifier of the device wireless. :type DeviceWirelessID: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceWirelessID: The internal NetMRI identifier of the device wireless. :type DeviceWirelessID: Array of Integer | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DeviceWirelessStartTime: The starting effective time of this record. :type DeviceWirelessStartTime: DateTime | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceWirelessStartTime: The starting effective time of this record. :type DeviceWirelessStartTime: Array of DateTime | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param DeviceWirelessTimestamp: The date and time this record was collected or calculated. :type DeviceWirelessTimestamp: DateTime | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceWirelessTimestamp: The date and time this record was collected or calculated. :type DeviceWirelessTimestamp: Array of DateTime | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param InterfaceID: The internal NetMRI identifier of a local interface for the device wireless. :type InterfaceID: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param InterfaceID: The internal NetMRI identifier of a local interface for the device wireless. :type InterfaceID: Array of Integer | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param StationID: The internal NetMRI identifier of a station. :type StationID: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param StationID: The internal NetMRI identifier of a station. :type StationID: Array of String | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param StationRole: The role name of the station. :type StationRole: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param StationRole: The role name of the station. :type StationRole: Array of String | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param WEPAllowedInd: A flag indicates whether a wired equivalent privacy is allowed or not? :type WEPAllowedInd: Boolean | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param WEPAllowedInd: A flag indicates whether a wired equivalent privacy is allowed or not? :type WEPAllowedInd: Array of Boolean | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param WEPDefaultKeyLen1: The initial default key length of wired equivalent privacy. :type WEPDefaultKeyLen1: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param WEPDefaultKeyLen1: The initial default key length of wired equivalent privacy. :type WEPDefaultKeyLen1: Array of String | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param WEPDefaultKeyLen2: The second default key length of wired equivalent privacy. :type WEPDefaultKeyLen2: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param WEPDefaultKeyLen2: The second default key length of wired equivalent privacy. :type WEPDefaultKeyLen2: Array of String | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param WEPDefaultKeyLen3: The third default key length of wired equivalent privacy. :type WEPDefaultKeyLen3: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param WEPDefaultKeyLen3: The third default key length of wired equivalent privacy. :type WEPDefaultKeyLen3: Array of String | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param WEPDefaultKeyLen4: The fourth default key length of wired equivalent privacy. :type WEPDefaultKeyLen4: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param WEPDefaultKeyLen4: The fourth default key length of wired equivalent privacy. :type WEPDefaultKeyLen4: Array of String | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param WEPEnabledInd: A flag indicates whether a wired equivalent privacy is enabled or not? :type WEPEnabledInd: Boolean | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param WEPEnabledInd: A flag indicates whether a wired equivalent privacy is enabled or not? :type WEPEnabledInd: Array of Boolean | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param WEPICVErrorCount: The total number of integrity check errors in WEP. :type WEPICVErrorCount: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param WEPICVErrorCount: The total number of integrity check errors in WEP. :type WEPICVErrorCount: Array of Integer | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param WEPOnlyTrafficInd: A flag indicates whether a wired equivalent privacy is traffic or not? :type WEPOnlyTrafficInd: Boolean | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param WEPOnlyTrafficInd: A flag indicates whether a wired equivalent privacy is traffic or not? :type WEPOnlyTrafficInd: Array of Boolean | ``api version min:`` 2.4 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param ifIndex: The SNMP index of a local interface for the device wireless table entry. :type ifIndex: String | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param ifIndex: The SNMP index of a local interface for the device wireless table entry. :type ifIndex: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceGroupID: The internal NetMRI identifier of the device groups to which to limit the results. :type DeviceGroupID: Array of Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param timestamp: The data returned will represent the device wirelesses as of this date and time. If omitted, the result will indicate the most recently collected data. :type timestamp: DateTime | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param methods: A list of device wireless methods. The listed methods will be called on each device wireless returned and included in the output. Available methods are: device, interface. :type methods: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param include: A list of associated object types to include in the output. The listed associations will be returned as outputs named according to the association name (see outputs below). Available includes are: device, interface. :type include: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 0 :param start: The record number to return in the selected page of data. It will always appear, although it may not be the first record. See the :limit for more information. :type start: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 1000 :param limit: The size of the page of data, that is, the maximum number of records returned. The limit size will be used to break the data up into pages and the first page with the start record will be returned. So if you have 100 records and use a :limit of 10 and a :start of 10, you will get records 10-19. The maximum limit is 10000. :type limit: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` DeviceWirelessID :param sort: The data field(s) to use for sorting the output. Default is DeviceWirelessID. Valid values are DeviceWirelessID, DeviceWirelessStartTime, DeviceWirelessEndTime, DeviceWirelessChangedCols, DeviceWirelessTimestamp, DataSourceID, DeviceID, ifIndex, InterfaceID, StationID, DesiredSSID, StationRole, WEPEnabledInd, WEPAllowedInd, WEPOnlyTrafficInd, WEPICVErrorCount, WEPDefaultKeyLen1, WEPDefaultKeyLen2, WEPDefaultKeyLen3, WEPDefaultKeyLen4. :type sort: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` asc :param dir: The direction(s) in which to sort the data. Default is 'asc'. Valid values are 'asc' and 'desc'. :type dir: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param select: The list of attributes to return for each DeviceWireless. Valid values are DeviceWirelessID, DeviceWirelessStartTime, DeviceWirelessEndTime, DeviceWirelessChangedCols, DeviceWirelessTimestamp, DataSourceID, DeviceID, ifIndex, InterfaceID, StationID, DesiredSSID, StationRole, WEPEnabledInd, WEPAllowedInd, WEPOnlyTrafficInd, WEPICVErrorCount, WEPDefaultKeyLen1, WEPDefaultKeyLen2, WEPDefaultKeyLen3, WEPDefaultKeyLen4. If empty or omitted, all attributes will be returned. :type select: Array | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_field: The field name for NIOS GOTO that is used for locating a row position of records. :type goto_field: String | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_value: The value of goto_field for NIOS GOTO that is used for locating a row position of records. :type goto_value: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param query: This value will be matched against device wirelesses, looking to see if one or more of the listed attributes contain the passed value. You may also surround the value with '/' and '/' to perform a regular expression search rather than a containment operation. Any record that matches will be returned. The attributes searched are: DataSourceID, DesiredSSID, DeviceID, DeviceWirelessChangedCols, DeviceWirelessEndTime, DeviceWirelessID, DeviceWirelessStartTime, DeviceWirelessTimestamp, InterfaceID, StationID, StationRole, WEPAllowedInd, WEPDefaultKeyLen1, WEPDefaultKeyLen2, WEPDefaultKeyLen3, WEPDefaultKeyLen4, WEPEnabledInd, WEPICVErrorCount, WEPOnlyTrafficInd, ifIndex. :type query: String | ``api version min:`` 2.3 | ``api version max:`` None | ``required:`` False | ``default:`` None :param xml_filter: A SetFilter XML structure to further refine the search. The SetFilter will be applied AFTER any search query or field values, but before any limit options. The limit and pagination will be enforced after the filter. Remind that this kind of filter may be costly and inefficient if not associated with a database filtering. :type xml_filter: String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return device_wirelesses: An array of the DeviceWireless objects that match the specified input criteria. :rtype device_wirelesses: Array of DeviceWireless """ return self.api_list_request(self._get_method_fullname("search"), kwargs) def find(self, **kwargs): """Lists the available device wirelesses matching the input specification. This provides the most flexible search specification of all the query mechanisms, enabling searching using comparison operations other than equality. However, it is more complex to use and will not perform as efficiently as the index or search methods. In the input descriptions below, 'field names' refers to the following fields: DataSourceID, DesiredSSID, DeviceID, DeviceWirelessChangedCols, DeviceWirelessEndTime, DeviceWirelessID, DeviceWirelessStartTime, DeviceWirelessTimestamp, InterfaceID, StationID, StationRole, WEPAllowedInd, WEPDefaultKeyLen1, WEPDefaultKeyLen2, WEPDefaultKeyLen3, WEPDefaultKeyLen4, WEPEnabledInd, WEPICVErrorCount, WEPOnlyTrafficInd, ifIndex. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_DataSourceID: The operator to apply to the field DataSourceID. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DataSourceID: The internal NetMRI identifier for the collector NetMRI that collected this data record. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_DataSourceID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_DataSourceID: If op_DataSourceID is specified, the field named in this input will be compared to the value in DataSourceID using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DataSourceID must be specified if op_DataSourceID is specified. :type val_f_DataSourceID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_DataSourceID: If op_DataSourceID is specified, this value will be compared to the value in DataSourceID using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_DataSourceID must be specified if op_DataSourceID is specified. :type val_c_DataSourceID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_DesiredSSID: The operator to apply to the field DesiredSSID. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DesiredSSID: The service set identifier(SSID) of desired wireless device. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_DesiredSSID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_DesiredSSID: If op_DesiredSSID is specified, the field named in this input will be compared to the value in DesiredSSID using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DesiredSSID must be specified if op_DesiredSSID is specified. :type val_f_DesiredSSID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_DesiredSSID: If op_DesiredSSID is specified, this value will be compared to the value in DesiredSSID using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_DesiredSSID must be specified if op_DesiredSSID is specified. :type val_c_DesiredSSID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_DeviceID: The operator to apply to the field DeviceID. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DeviceID: The internal NetMRI identifier of each device from which wireless setting was collected. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_DeviceID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_DeviceID: If op_DeviceID is specified, the field named in this input will be compared to the value in DeviceID using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DeviceID must be specified if op_DeviceID is specified. :type val_f_DeviceID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_DeviceID: If op_DeviceID is specified, this value will be compared to the value in DeviceID using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_DeviceID must be specified if op_DeviceID is specified. :type val_c_DeviceID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_DeviceWirelessChangedCols: The operator to apply to the field DeviceWirelessChangedCols. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DeviceWirelessChangedCols: The fields that changed between this revision of the record and the previous revision. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_DeviceWirelessChangedCols: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_DeviceWirelessChangedCols: If op_DeviceWirelessChangedCols is specified, the field named in this input will be compared to the value in DeviceWirelessChangedCols using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DeviceWirelessChangedCols must be specified if op_DeviceWirelessChangedCols is specified. :type val_f_DeviceWirelessChangedCols: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_DeviceWirelessChangedCols: If op_DeviceWirelessChangedCols is specified, this value will be compared to the value in DeviceWirelessChangedCols using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_DeviceWirelessChangedCols must be specified if op_DeviceWirelessChangedCols is specified. :type val_c_DeviceWirelessChangedCols: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_DeviceWirelessEndTime: The operator to apply to the field DeviceWirelessEndTime. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DeviceWirelessEndTime: The ending effective time of this record, or empty if still in effect. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_DeviceWirelessEndTime: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_DeviceWirelessEndTime: If op_DeviceWirelessEndTime is specified, the field named in this input will be compared to the value in DeviceWirelessEndTime using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DeviceWirelessEndTime must be specified if op_DeviceWirelessEndTime is specified. :type val_f_DeviceWirelessEndTime: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_DeviceWirelessEndTime: If op_DeviceWirelessEndTime is specified, this value will be compared to the value in DeviceWirelessEndTime using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_DeviceWirelessEndTime must be specified if op_DeviceWirelessEndTime is specified. :type val_c_DeviceWirelessEndTime: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_DeviceWirelessID: The operator to apply to the field DeviceWirelessID. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DeviceWirelessID: The internal NetMRI identifier of the device wireless. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_DeviceWirelessID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_DeviceWirelessID: If op_DeviceWirelessID is specified, the field named in this input will be compared to the value in DeviceWirelessID using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DeviceWirelessID must be specified if op_DeviceWirelessID is specified. :type val_f_DeviceWirelessID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_DeviceWirelessID: If op_DeviceWirelessID is specified, this value will be compared to the value in DeviceWirelessID using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_DeviceWirelessID must be specified if op_DeviceWirelessID is specified. :type val_c_DeviceWirelessID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_DeviceWirelessStartTime: The operator to apply to the field DeviceWirelessStartTime. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DeviceWirelessStartTime: The starting effective time of this record. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_DeviceWirelessStartTime: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_DeviceWirelessStartTime: If op_DeviceWirelessStartTime is specified, the field named in this input will be compared to the value in DeviceWirelessStartTime using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DeviceWirelessStartTime must be specified if op_DeviceWirelessStartTime is specified. :type val_f_DeviceWirelessStartTime: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_DeviceWirelessStartTime: If op_DeviceWirelessStartTime is specified, this value will be compared to the value in DeviceWirelessStartTime using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_DeviceWirelessStartTime must be specified if op_DeviceWirelessStartTime is specified. :type val_c_DeviceWirelessStartTime: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_DeviceWirelessTimestamp: The operator to apply to the field DeviceWirelessTimestamp. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. DeviceWirelessTimestamp: The date and time this record was collected or calculated. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_DeviceWirelessTimestamp: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_DeviceWirelessTimestamp: If op_DeviceWirelessTimestamp is specified, the field named in this input will be compared to the value in DeviceWirelessTimestamp using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_DeviceWirelessTimestamp must be specified if op_DeviceWirelessTimestamp is specified. :type val_f_DeviceWirelessTimestamp: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_DeviceWirelessTimestamp: If op_DeviceWirelessTimestamp is specified, this value will be compared to the value in DeviceWirelessTimestamp using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_DeviceWirelessTimestamp must be specified if op_DeviceWirelessTimestamp is specified. :type val_c_DeviceWirelessTimestamp: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_InterfaceID: The operator to apply to the field InterfaceID. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. InterfaceID: The internal NetMRI identifier of a local interface for the device wireless. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_InterfaceID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_InterfaceID: If op_InterfaceID is specified, the field named in this input will be compared to the value in InterfaceID using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_InterfaceID must be specified if op_InterfaceID is specified. :type val_f_InterfaceID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_InterfaceID: If op_InterfaceID is specified, this value will be compared to the value in InterfaceID using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_InterfaceID must be specified if op_InterfaceID is specified. :type val_c_InterfaceID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_StationID: The operator to apply to the field StationID. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. StationID: The internal NetMRI identifier of a station. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_StationID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_StationID: If op_StationID is specified, the field named in this input will be compared to the value in StationID using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_StationID must be specified if op_StationID is specified. :type val_f_StationID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_StationID: If op_StationID is specified, this value will be compared to the value in StationID using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_StationID must be specified if op_StationID is specified. :type val_c_StationID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_StationRole: The operator to apply to the field StationRole. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. StationRole: The role name of the station. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_StationRole: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_StationRole: If op_StationRole is specified, the field named in this input will be compared to the value in StationRole using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_StationRole must be specified if op_StationRole is specified. :type val_f_StationRole: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_StationRole: If op_StationRole is specified, this value will be compared to the value in StationRole using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_StationRole must be specified if op_StationRole is specified. :type val_c_StationRole: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_WEPAllowedInd: The operator to apply to the field WEPAllowedInd. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. WEPAllowedInd: A flag indicates whether a wired equivalent privacy is allowed or not? For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_WEPAllowedInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_WEPAllowedInd: If op_WEPAllowedInd is specified, the field named in this input will be compared to the value in WEPAllowedInd using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_WEPAllowedInd must be specified if op_WEPAllowedInd is specified. :type val_f_WEPAllowedInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_WEPAllowedInd: If op_WEPAllowedInd is specified, this value will be compared to the value in WEPAllowedInd using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_WEPAllowedInd must be specified if op_WEPAllowedInd is specified. :type val_c_WEPAllowedInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_WEPDefaultKeyLen1: The operator to apply to the field WEPDefaultKeyLen1. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. WEPDefaultKeyLen1: The initial default key length of wired equivalent privacy. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_WEPDefaultKeyLen1: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_WEPDefaultKeyLen1: If op_WEPDefaultKeyLen1 is specified, the field named in this input will be compared to the value in WEPDefaultKeyLen1 using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_WEPDefaultKeyLen1 must be specified if op_WEPDefaultKeyLen1 is specified. :type val_f_WEPDefaultKeyLen1: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_WEPDefaultKeyLen1: If op_WEPDefaultKeyLen1 is specified, this value will be compared to the value in WEPDefaultKeyLen1 using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_WEPDefaultKeyLen1 must be specified if op_WEPDefaultKeyLen1 is specified. :type val_c_WEPDefaultKeyLen1: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_WEPDefaultKeyLen2: The operator to apply to the field WEPDefaultKeyLen2. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. WEPDefaultKeyLen2: The second default key length of wired equivalent privacy. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_WEPDefaultKeyLen2: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_WEPDefaultKeyLen2: If op_WEPDefaultKeyLen2 is specified, the field named in this input will be compared to the value in WEPDefaultKeyLen2 using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_WEPDefaultKeyLen2 must be specified if op_WEPDefaultKeyLen2 is specified. :type val_f_WEPDefaultKeyLen2: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_WEPDefaultKeyLen2: If op_WEPDefaultKeyLen2 is specified, this value will be compared to the value in WEPDefaultKeyLen2 using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_WEPDefaultKeyLen2 must be specified if op_WEPDefaultKeyLen2 is specified. :type val_c_WEPDefaultKeyLen2: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_WEPDefaultKeyLen3: The operator to apply to the field WEPDefaultKeyLen3. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. WEPDefaultKeyLen3: The third default key length of wired equivalent privacy. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_WEPDefaultKeyLen3: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_WEPDefaultKeyLen3: If op_WEPDefaultKeyLen3 is specified, the field named in this input will be compared to the value in WEPDefaultKeyLen3 using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_WEPDefaultKeyLen3 must be specified if op_WEPDefaultKeyLen3 is specified. :type val_f_WEPDefaultKeyLen3: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_WEPDefaultKeyLen3: If op_WEPDefaultKeyLen3 is specified, this value will be compared to the value in WEPDefaultKeyLen3 using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_WEPDefaultKeyLen3 must be specified if op_WEPDefaultKeyLen3 is specified. :type val_c_WEPDefaultKeyLen3: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_WEPDefaultKeyLen4: The operator to apply to the field WEPDefaultKeyLen4. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. WEPDefaultKeyLen4: The fourth default key length of wired equivalent privacy. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_WEPDefaultKeyLen4: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_WEPDefaultKeyLen4: If op_WEPDefaultKeyLen4 is specified, the field named in this input will be compared to the value in WEPDefaultKeyLen4 using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_WEPDefaultKeyLen4 must be specified if op_WEPDefaultKeyLen4 is specified. :type val_f_WEPDefaultKeyLen4: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_WEPDefaultKeyLen4: If op_WEPDefaultKeyLen4 is specified, this value will be compared to the value in WEPDefaultKeyLen4 using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_WEPDefaultKeyLen4 must be specified if op_WEPDefaultKeyLen4 is specified. :type val_c_WEPDefaultKeyLen4: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_WEPEnabledInd: The operator to apply to the field WEPEnabledInd. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. WEPEnabledInd: A flag indicates whether a wired equivalent privacy is enabled or not? For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_WEPEnabledInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_WEPEnabledInd: If op_WEPEnabledInd is specified, the field named in this input will be compared to the value in WEPEnabledInd using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_WEPEnabledInd must be specified if op_WEPEnabledInd is specified. :type val_f_WEPEnabledInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_WEPEnabledInd: If op_WEPEnabledInd is specified, this value will be compared to the value in WEPEnabledInd using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_WEPEnabledInd must be specified if op_WEPEnabledInd is specified. :type val_c_WEPEnabledInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_WEPICVErrorCount: The operator to apply to the field WEPICVErrorCount. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. WEPICVErrorCount: The total number of integrity check errors in WEP. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_WEPICVErrorCount: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_WEPICVErrorCount: If op_WEPICVErrorCount is specified, the field named in this input will be compared to the value in WEPICVErrorCount using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_WEPICVErrorCount must be specified if op_WEPICVErrorCount is specified. :type val_f_WEPICVErrorCount: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_WEPICVErrorCount: If op_WEPICVErrorCount is specified, this value will be compared to the value in WEPICVErrorCount using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_WEPICVErrorCount must be specified if op_WEPICVErrorCount is specified. :type val_c_WEPICVErrorCount: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_WEPOnlyTrafficInd: The operator to apply to the field WEPOnlyTrafficInd. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. WEPOnlyTrafficInd: A flag indicates whether a wired equivalent privacy is traffic or not? For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_WEPOnlyTrafficInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_WEPOnlyTrafficInd: If op_WEPOnlyTrafficInd is specified, the field named in this input will be compared to the value in WEPOnlyTrafficInd using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_WEPOnlyTrafficInd must be specified if op_WEPOnlyTrafficInd is specified. :type val_f_WEPOnlyTrafficInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_WEPOnlyTrafficInd: If op_WEPOnlyTrafficInd is specified, this value will be compared to the value in WEPOnlyTrafficInd using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_WEPOnlyTrafficInd must be specified if op_WEPOnlyTrafficInd is specified. :type val_c_WEPOnlyTrafficInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_ifIndex: The operator to apply to the field ifIndex. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. ifIndex: The SNMP index of a local interface for the device wireless table entry. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_ifIndex: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_ifIndex: If op_ifIndex is specified, the field named in this input will be compared to the value in ifIndex using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_ifIndex must be specified if op_ifIndex is specified. :type val_f_ifIndex: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_ifIndex: If op_ifIndex is specified, this value will be compared to the value in ifIndex using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_ifIndex must be specified if op_ifIndex is specified. :type val_c_ifIndex: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceGroupID: The internal NetMRI identifier of the device groups to which to limit the results. :type DeviceGroupID: Array of Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param timestamp: The data returned will represent the device wirelesses as of this date and time. If omitted, the result will indicate the most recently collected data. :type timestamp: DateTime | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param methods: A list of device wireless methods. The listed methods will be called on each device wireless returned and included in the output. Available methods are: device, interface. :type methods: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param include: A list of associated object types to include in the output. The listed associations will be returned as outputs named according to the association name (see outputs below). Available includes are: device, interface. :type include: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 0 :param start: The record number to return in the selected page of data. It will always appear, although it may not be the first record. See the :limit for more information. :type start: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 1000 :param limit: The size of the page of data, that is, the maximum number of records returned. The limit size will be used to break the data up into pages and the first page with the start record will be returned. So if you have 100 records and use a :limit of 10 and a :start of 10, you will get records 10-19. The maximum limit is 10000. :type limit: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` DeviceWirelessID :param sort: The data field(s) to use for sorting the output. Default is DeviceWirelessID. Valid values are DeviceWirelessID, DeviceWirelessStartTime, DeviceWirelessEndTime, DeviceWirelessChangedCols, DeviceWirelessTimestamp, DataSourceID, DeviceID, ifIndex, InterfaceID, StationID, DesiredSSID, StationRole, WEPEnabledInd, WEPAllowedInd, WEPOnlyTrafficInd, WEPICVErrorCount, WEPDefaultKeyLen1, WEPDefaultKeyLen2, WEPDefaultKeyLen3, WEPDefaultKeyLen4. :type sort: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` asc :param dir: The direction(s) in which to sort the data. Default is 'asc'. Valid values are 'asc' and 'desc'. :type dir: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param select: The list of attributes to return for each DeviceWireless. Valid values are DeviceWirelessID, DeviceWirelessStartTime, DeviceWirelessEndTime, DeviceWirelessChangedCols, DeviceWirelessTimestamp, DataSourceID, DeviceID, ifIndex, InterfaceID, StationID, DesiredSSID, StationRole, WEPEnabledInd, WEPAllowedInd, WEPOnlyTrafficInd, WEPICVErrorCount, WEPDefaultKeyLen1, WEPDefaultKeyLen2, WEPDefaultKeyLen3, WEPDefaultKeyLen4. If empty or omitted, all attributes will be returned. :type select: Array | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_field: The field name for NIOS GOTO that is used for locating a row position of records. :type goto_field: String | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_value: The value of goto_field for NIOS GOTO that is used for locating a row position of records. :type goto_value: String | ``api version min:`` 2.3 | ``api version max:`` None | ``required:`` False | ``default:`` None :param xml_filter: A SetFilter XML structure to further refine the search. The SetFilter will be applied AFTER any search query or field values, but before any limit options. The limit and pagination will be enforced after the filter. Remind that this kind of filter may be costly and inefficient if not associated with a database filtering. :type xml_filter: String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return device_wirelesses: An array of the DeviceWireless objects that match the specified input criteria. :rtype device_wirelesses: Array of DeviceWireless """ return self.api_list_request(self._get_method_fullname("find"), kwargs) def data_source(self, **kwargs): """The collector NetMRI that collected this data record. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param DeviceWirelessID: The internal NetMRI identifier of the device wireless. :type DeviceWirelessID: Integer **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return : The collector NetMRI that collected this data record. :rtype : DataSource """ return self.api_request(self._get_method_fullname("data_source"), kwargs) def device(self, **kwargs): """The device from which this data was collected. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param DeviceWirelessID: The internal NetMRI identifier of the device wireless. :type DeviceWirelessID: Integer **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return : The device from which this data was collected. :rtype : Device """ return self.api_request(self._get_method_fullname("device"), kwargs) def interface(self, **kwargs): """interface **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param DeviceWirelessID: The internal NetMRI identifier of the device wireless. :type DeviceWirelessID: Integer **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return : interface :rtype : Interface """ return self.api_request(self._get_method_fullname("interface"), kwargs) def infradevice(self, **kwargs): """The device from which this data was collected. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param DeviceWirelessID: The internal NetMRI identifier of the device wireless. :type DeviceWirelessID: Integer **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return : The device from which this data was collected. :rtype : InfraDevice """ return self.api_request(self._get_method_fullname("infradevice"), kwargs)
apache-2.0
-4,136,499,881,669,812,700
52.709158
758
0.612538
false
googleapis/googleapis-gen
google/ads/googleads/v6/googleads-py/google/ads/googleads/v6/resources/types/google_ads_field.py
1
5848
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore from google.ads.googleads.v6.enums.types import google_ads_field_category from google.ads.googleads.v6.enums.types import google_ads_field_data_type __protobuf__ = proto.module( package='google.ads.googleads.v6.resources', marshal='google.ads.googleads.v6', manifest={ 'GoogleAdsField', }, ) class GoogleAdsField(proto.Message): r"""A field or resource (artifact) used by GoogleAdsService. Attributes: resource_name (str): Output only. The resource name of the artifact. Artifact resource names have the form: ``googleAdsFields/{name}`` name (str): Output only. The name of the artifact. category (google.ads.googleads.v6.enums.types.GoogleAdsFieldCategoryEnum.GoogleAdsFieldCategory): Output only. The category of the artifact. selectable (bool): Output only. Whether the artifact can be used in a SELECT clause in search queries. filterable (bool): Output only. Whether the artifact can be used in a WHERE clause in search queries. sortable (bool): Output only. Whether the artifact can be used in a ORDER BY clause in search queries. selectable_with (Sequence[str]): Output only. The names of all resources, segments, and metrics that are selectable with the described artifact. attribute_resources (Sequence[str]): Output only. The names of all resources that are selectable with the described artifact. Fields from these resources do not segment metrics when included in search queries. This field is only set for artifacts whose category is RESOURCE. metrics (Sequence[str]): Output only. At and beyond version V1 this field lists the names of all metrics that are selectable with the described artifact when it is used in the FROM clause. It is only set for artifacts whose category is RESOURCE. Before version V1 this field lists the names of all metrics that are selectable with the described artifact. It is only set for artifacts whose category is either RESOURCE or SEGMENT segments (Sequence[str]): Output only. At and beyond version V1 this field lists the names of all artifacts, whether a segment or another resource, that segment metrics when included in search queries and when the described artifact is used in the FROM clause. It is only set for artifacts whose category is RESOURCE. Before version V1 this field lists the names of all artifacts, whether a segment or another resource, that segment metrics when included in search queries. It is only set for artifacts of category RESOURCE, SEGMENT or METRIC. enum_values (Sequence[str]): Output only. Values the artifact can assume if it is a field of type ENUM. This field is only set for artifacts of category SEGMENT or ATTRIBUTE. data_type (google.ads.googleads.v6.enums.types.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType): Output only. This field determines the operators that can be used with the artifact in WHERE clauses. type_url (str): Output only. The URL of proto describing the artifact's data type. is_repeated (bool): Output only. Whether the field artifact is repeated. """ resource_name = proto.Field( proto.STRING, number=1, ) name = proto.Field( proto.STRING, number=21, optional=True, ) category = proto.Field( proto.ENUM, number=3, enum=google_ads_field_category.GoogleAdsFieldCategoryEnum.GoogleAdsFieldCategory, ) selectable = proto.Field( proto.BOOL, number=22, optional=True, ) filterable = proto.Field( proto.BOOL, number=23, optional=True, ) sortable = proto.Field( proto.BOOL, number=24, optional=True, ) selectable_with = proto.RepeatedField( proto.STRING, number=25, ) attribute_resources = proto.RepeatedField( proto.STRING, number=26, ) metrics = proto.RepeatedField( proto.STRING, number=27, ) segments = proto.RepeatedField( proto.STRING, number=28, ) enum_values = proto.RepeatedField( proto.STRING, number=29, ) data_type = proto.Field( proto.ENUM, number=12, enum=google_ads_field_data_type.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType, ) type_url = proto.Field( proto.STRING, number=30, optional=True, ) is_repeated = proto.Field( proto.BOOL, number=31, optional=True, ) __all__ = tuple(sorted(__protobuf__.manifest))
apache-2.0
-6,471,146,014,584,337,000
33.4
106
0.625342
false
kbaseapps/GenomeFileUtil
test/core/fasta_download_test.py
1
5208
import os import time import unittest import json import shutil from configparser import ConfigParser from GenomeFileUtil.GenomeFileUtilImpl import GenomeFileUtil from GenomeFileUtil.GenomeFileUtilServer import MethodContext from installed_clients.AssemblyUtilClient import AssemblyUtil from installed_clients.WorkspaceClient import Workspace as workspaceService class UtilTest(unittest.TestCase): @classmethod def setUpClass(cls): token = os.environ.get('KB_AUTH_TOKEN', None) # WARNING: don't call any logging methods on the context object, # it'll result in a NoneType error cls.ctx = MethodContext(None) cls.ctx.update({'token': token, 'provenance': [ {'service': 'GenomeFileUtil', 'method': 'please_never_use_it_in_production', 'method_params': [] }], 'authenticated': 1}) config_file = os.environ.get('KB_DEPLOYMENT_CONFIG', None) cls.cfg = {} config = ConfigParser() config.read(config_file) for nameval in config.items('GenomeFileUtil'): cls.cfg[nameval[0]] = nameval[1] cls.wsURL = cls.cfg['workspace-url'] cls.wsClient = workspaceService(cls.wsURL, token=token) cls.serviceImpl = GenomeFileUtil(cls.cfg) suffix = int(time.time() * 1000) cls.wsName = "test_GenomeFileUtil_" + str(suffix) cls.wsClient.create_workspace({'workspace': cls.wsName}) # cls.genome_ref = 'KBaseExampleData/Escherichia_coli_K-12_MG1655' cls.genome_ref, cls.assembly_ref = cls.load_genome_direct( 'data/e_coli/new_ecoli_genome.json', 'data/e_coli/e_coli_assembly.fasta', 'TestGenome') @classmethod def load_genome_direct(cls, filename, assembly_filename, obj_name): au = AssemblyUtil(os.environ['SDK_CALLBACK_URL']) assembly_path = os.path.join(cls.cfg['scratch'], os.path.basename(assembly_filename)) shutil.copy(assembly_filename, assembly_path) assembly_ref = au.save_assembly_from_fasta({ 'workspace_name': cls.wsName, 'assembly_name': obj_name + '.assembly', 'file': {'path': assembly_path} }) data = json.load(open(filename)) data['assembly_ref'] = assembly_ref save_info = { 'workspace': cls.wsName, 'objects': [{ 'data': data, 'name': obj_name + '.genome', 'type': 'KBaseGenomes.Genome', }], } info = cls.wsClient.save_objects(save_info)[0] ref = f"{info[6]}/{info[0]}/{info[4]}" print('created test genome: ' + ref + ' from file ' + filename) return ref, assembly_ref @classmethod def tearDownClass(cls): if hasattr(cls, 'wsName'): cls.wsClient.delete_workspace({'workspace': cls.wsName}) print('Test workspace was deleted') def test_genome_protein_to_fasta(self): ret = self.serviceImpl.genome_proteins_to_fasta(self.ctx, { 'genome_ref': self.genome_ref, 'include_functions': False, 'include_aliases': False, })[0] self.assertIn('file_path', ret) with open(ret['file_path']) as infile: header1 = '>b0001_CDS_1\n' self.assertEqual(infile.readline(), header1) self.assertEqual(infile.readline(), 'MKRISTTITTTITITTGNGAG\n') infile.readline() self.assertEqual(len(infile.readline()), 71) def test_genome_features_to_fasta(self): ret = self.serviceImpl.genome_features_to_fasta(self.ctx, { 'genome_ref': self.genome_ref, 'filter_ids': ['b0001', 'b0001_CDS_1'], 'feature_lists': ['features', 'cdss'] })[0] self.assertIn('file_path', ret) with open(ret['file_path']) as infile: header1 = infile.readline() self.assertIn('>b0001 functions=leader,Amino acid biosynthesis:', header1) self.assertIn('GeneID:944742', header1) self.assertIn('thrL', header1) self.assertEqual(infile.readline(), 'ATGAAACGCATTAGCACCACCATTACCACCACCATCACCATTACCACAGGTAACGGTGCGGGCTGA\n') self.assertIn('>b0001_CDS_1', infile.readline()) def test_bad_inputs(self): with self.assertRaisesRegexp(ValueError, 'required field "genome_ref"'): self.serviceImpl.genome_features_to_fasta(self.ctx, {}) with self.assertRaisesRegexp(ValueError, 'Unknown parameter'): self.serviceImpl.genome_features_to_fasta(self.ctx, { 'genome_ref': self.genome_ref, 'foo': 'bar'}) with self.assertRaisesRegexp(ValueError, 'Unknown feature_lists'): self.serviceImpl.genome_features_to_fasta(self.ctx, { 'genome_ref': self.genome_ref, 'feature_lists': ['foo']}) with self.assertRaisesRegexp(ValueError, 'Object is not a Genome'): self.serviceImpl.genome_features_to_fasta(self.ctx, { 'genome_ref': self.assembly_ref})
mit
4,013,379,416,274,280,400
43.512821
119
0.598502
false
saurabh6790/pow-app
selling/doctype/user/user.py
2
2140
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt # For license information, please see license.txt from __future__ import unicode_literals import webnotes from webnotes.utils import cint,cstr class DocType: def __init__(self, d, dl): self.doc, self.doclist = d, dl def on_update(self): # m=webnotes.conn.sql("select profile_user from `tabUser`") # webnotes.errprint(m) self.doc.account_id=self.doc.account_id.lower() self.doc.user_id=self.doc.user_id.lower() self.doc.authorized_group=self.doc.authorized_group.lower() self.doc.device_id=self.doc.device_id.lower() self.doc.name=self.doc.name.lower() a=webnotes.conn.sql("select erp from User where userID='"+cstr(self.doc.user_id)+"'") webnotes.errprint(a) if a: res= "update User set accountID='"+cstr(self.doc.account_id)+"',userID='"+cstr(self.doc.user_id)+"',password='"+cstr(self.doc.password)+"',preferredDeviceID='"+cstr(self.doc.device_id)+"',isActive='"+cstr(self.doc.active)+"',contactName='"+cstr(self.doc.contact_name)+"',contactPhone='"+cstr(self.doc.contact_phone)+"',contactEmail='"+cstr(self.doc.contact_email)+"',notifyEmail='"+cstr(self.doc.notify_email)+"',description='"+cstr(self.doc.user_description)+"' where erp='"+cstr(self.doc.name)+"'" webnotes.conn.sql(res) webnotes.errprint(res) else: qry= "insert into User (accountID,userID,password,preferredDeviceID,isActive,contactName,contactPhone,contactEmail,notifyEmail,description,erp) values('"+cstr(self.doc.account_id)+"','"+cstr(self.doc.user_id)+"','"+cstr(self.doc.password)+"','"+cstr(self.doc.device_id)+"','"+cstr(self.doc.active)+"','"+cstr(self.doc.contact_name)+"','"+cstr(self.doc.contact_phone)+"','"+cstr(self.doc.contact_email)+"','"+cstr(self.doc.notify_email)+"','"+cstr(self.doc.user_description)+"','"+cstr(self.doc.name)+"')" webnotes.conn.sql(qry) webnotes.errprint(qry) r="insert into GroupList (accountID,groupID,userID) values('"+cstr(self.doc.account_id)+"','"+cstr(self.doc.authorized_group)+"','"+cstr(self.doc.user_id)+"')" webnotes.conn.sql(r) webnotes.errprint(r)
agpl-3.0
3,038,121,087,767,596,000
56.837838
507
0.703271
false
srjoglekar246/sympy
sympy/physics/quantum/tests/test_operator.py
2
5503
from sympy import (Derivative, diff, Function, Integer, Mul, pi, sin, Symbol, symbols) from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.hilbert import HilbertSpace from sympy.physics.quantum.operator import (Operator, UnitaryOperator, HermitianOperator, OuterProduct, DifferentialOperator) from sympy.physics.quantum.state import Ket, Bra, Wavefunction from sympy.physics.quantum.qapply import qapply from sympy.core.trace import Tr from sympy.physics.quantum.spin import JzKet, JzBra class TestKet(Ket): @classmethod def default_args(self): return ("t",) class TestOp(HermitianOperator): @classmethod def default_args(self): return ("T",) t_ket = TestKet() t_op = TestOp() def test_operator(): A = Operator('A') B = Operator('B') C = Operator('C') assert isinstance(A, Operator) assert isinstance(A, QExpr) assert A.label == (Symbol('A'),) assert A.is_commutative == False assert A.hilbert_space == HilbertSpace() assert A*B != B*A assert (A*(B+C)).expand() == A*B + A*C assert ((A+B)**2).expand() == A**2 + A*B + B*A + B**2 assert t_op.label[0] == Symbol(t_op.default_args()[0]) assert Operator() == Operator("O") def test_operator_inv(): A = Operator('A') assert A*A.inv() == 1 assert A.inv()*A == 1 def test_hermitian(): H = HermitianOperator('H') assert isinstance(H, HermitianOperator) assert isinstance(H, Operator) assert Dagger(H) == H assert H.inv() != H assert H.is_commutative == False assert Dagger(H).is_commutative == False def test_unitary(): U = UnitaryOperator('U') assert isinstance(U, UnitaryOperator) assert isinstance(U, Operator) assert U.inv() == Dagger(U) assert U*Dagger(U) == 1 assert Dagger(U)*U == 1 assert U.is_commutative == False assert Dagger(U).is_commutative == False def test_outer_product(): k = Ket('k') b = Bra('b') op = OuterProduct(k, b) assert isinstance(op, OuterProduct) assert isinstance(op, Operator) assert op.ket == k assert op.bra == b assert op.label == (k, b) assert op.is_commutative == False op = k*b assert isinstance(op, OuterProduct) assert isinstance(op, Operator) assert op.ket == k assert op.bra == b assert op.label == (k, b) assert op.is_commutative == False op = 2*k*b assert op == Mul(Integer(2), k, b) op = 2*(k*b) assert op == Mul(Integer(2), OuterProduct(k, b)) assert Dagger(k*b) == OuterProduct(Dagger(b),Dagger(k)) assert Dagger(k*b).is_commutative == False #test the _eval_trace assert Tr(OuterProduct(JzKet(1,1), JzBra(1,1))).doit() == 1 def test_operator_dagger(): A = Operator('A') B = Operator('B') assert Dagger(A*B) == Dagger(B)*Dagger(A) assert Dagger(A+B) == Dagger(A) + Dagger(B) assert Dagger(A**2) == Dagger(A)**2 def test_differential_operator(): x = Symbol('x') f = Function('f') d = DifferentialOperator(Derivative(f(x), x), f(x)) g = Wavefunction(x**2, x) assert qapply(d*g) == Wavefunction(2*x, x) assert d.expr == Derivative(f(x), x) assert d.function == f(x) assert d.variables == (x,) assert diff(d, x) == DifferentialOperator(Derivative(f(x), x, 2), f(x)) d = DifferentialOperator(Derivative(f(x), x, 2), f(x)) g = Wavefunction(x**3, x) assert qapply(d*g) == Wavefunction(6*x, x) assert d.expr == Derivative(f(x), x, 2) assert d.function == f(x) assert d.variables == (x,) assert diff(d, x) == DifferentialOperator(Derivative(f(x), x, 3), f(x)) d = DifferentialOperator(1/x*Derivative(f(x), x), f(x)) assert d.expr == 1/x*Derivative(f(x), x) assert d.function == f(x) assert d.variables == (x,) assert diff(d, x) == \ DifferentialOperator(Derivative(1/x*Derivative(f(x), x), x), f(x)) assert qapply(d*g) == Wavefunction(3*x, x) # 2D cartesian Laplacian y = Symbol('y') d = DifferentialOperator(Derivative(f(x, y), x, 2) + \ Derivative(f(x, y), y, 2), f(x, y)) w = Wavefunction(x**3*y**2 + y**3*x**2, x, y) assert d.expr == Derivative(f(x, y), x, 2) + Derivative(f(x, y), y, 2) assert d.function == f(x, y) assert d.variables == (x, y) assert diff(d, x) == \ DifferentialOperator(Derivative(d.expr, x), f(x, y)) assert diff(d, y) == \ DifferentialOperator(Derivative(d.expr, y), f(x, y)) assert qapply(d*w) == Wavefunction(2*x**3 + 6*x*y**2 + 6*x**2*y + 2*y**3, \ x, y) # 2D polar Laplacian (th = theta) r, th = symbols('r th') d = DifferentialOperator(1/r*Derivative(r*Derivative(f(r, th), r) , r) + \ 1/(r**2)*Derivative(f(r, th), th, 2), f(r, th)) w = Wavefunction(r**2*sin(th), r, (th, 0, pi)) assert d.expr == \ 1/r*Derivative(r*Derivative(f(r, th), r), r) + \ 1/(r**2)*Derivative(f(r, th), th, 2) assert d.function == f(r, th) assert d.variables == (r, th) assert diff(d, r) == \ DifferentialOperator(Derivative(d.expr, r), f(r, th)) assert diff(d, th) == \ DifferentialOperator(Derivative(d.expr, th), f(r, th)) assert qapply(d*w) == Wavefunction(3*sin(th), r, (th, 0, pi))
bsd-3-clause
4,518,610,432,724,588,000
29.572222
79
0.582955
false
nathania/pysal
pysal/weights/util.py
3
31930
import pysal from pysal.common import * import pysal.weights import numpy as np from scipy import sparse, float32 import scipy.spatial import os import operator import scipy __all__ = ['lat2W', 'block_weights', 'comb', 'order', 'higher_order', 'shimbel', 'remap_ids', 'full2W', 'full', 'WSP2W', 'insert_diagonal', 'get_ids', 'get_points_array_from_shapefile', 'min_threshold_distance', 'lat2SW', 'w_local_cluster', 'higher_order_sp', 'hexLat2W', 'regime_weights'] def hexLat2W(nrows=5, ncols=5): """ Create a W object for a hexagonal lattice. Parameters ---------- nrows : int number of rows ncols : int number of columns Returns ------- w : W instance of spatial weights class W Notes ----- Observations are row ordered: first k observations are in row 0, next k in row 1, and so on. Construction is based on shifting every other column of a regular lattice down 1/2 of a cell. Examples -------- >>> import pysal as ps >>> w = ps.lat2W() >>> w.neighbors[1] [0, 6, 2] >>> w.neighbors[21] [16, 20, 22] >>> wh = ps.hexLat2W() >>> wh.neighbors[1] [0, 6, 2, 5, 7] >>> wh.neighbors[21] [16, 20, 22] >>> """ if nrows == 1 or ncols == 1: print "Hexagon lattice requires at least 2 rows and columns" print "Returning a linear contiguity structure" return lat2W(nrows, ncols) n = nrows * ncols rid = [i / ncols for i in xrange(n)] cid = [i % ncols for i in xrange(n)] r1 = nrows - 1 c1 = ncols - 1 w = lat2W(nrows, ncols).neighbors for i in xrange(n): odd = cid[i] % 2 if odd: if rid[i] < r1: # odd col index above last row # new sw neighbor if cid[i] > 0: j = i + ncols - 1 w[i] = w.get(i, []) + [j] # new se neighbor if cid[i] < c1: j = i + ncols + 1 w[i] = w.get(i, []) + [j] else: # even col # nw jnw = [i - ncols - 1] # ne jne = [i - ncols + 1] if rid[i] > 0: w[i] if cid[i] == 0: w[i] = w.get(i, []) + jne elif cid[i] == c1: w[i] = w.get(i, []) + jnw else: w[i] = w.get(i, []) + jne w[i] = w.get(i, []) + jnw return pysal.weights.W(w) def lat2W(nrows=5, ncols=5, rook=True, id_type='int'): """ Create a W object for a regular lattice. Parameters ---------- nrows : int number of rows ncols : int number of columns rook : boolean type of contiguity. Default is rook. For queen, rook =False id_type : string string defining the type of IDs to use in the final W object; options are 'int' (0, 1, 2 ...; default), 'float' (0.0, 1.0, 2.0, ...) and 'string' ('id0', 'id1', 'id2', ...) Returns ------- w : W instance of spatial weights class W Notes ----- Observations are row ordered: first k observations are in row 0, next k in row 1, and so on. Examples -------- >>> from pysal import lat2W >>> w9 = lat2W(3,3) >>> "%.3f"%w9.pct_nonzero '29.630' >>> w9[0] {1: 1.0, 3: 1.0} >>> w9[3] {0: 1.0, 4: 1.0, 6: 1.0} >>> """ n = nrows * ncols r1 = nrows - 1 c1 = ncols - 1 rid = [i / ncols for i in xrange(n)] cid = [i % ncols for i in xrange(n)] w = {} r = below = 0 for i in xrange(n - 1): if rid[i] < r1: below = rid[i] + 1 r = below * ncols + cid[i] w[i] = w.get(i, []) + [r] w[r] = w.get(r, []) + [i] if cid[i] < c1: right = cid[i] + 1 c = rid[i] * ncols + right w[i] = w.get(i, []) + [c] w[c] = w.get(c, []) + [i] if not rook: # southeast bishop if cid[i] < c1 and rid[i] < r1: r = (rid[i] + 1) * ncols + 1 + cid[i] w[i] = w.get(i, []) + [r] w[r] = w.get(r, []) + [i] # southwest bishop if cid[i] > 0 and rid[i] < r1: r = (rid[i] + 1) * ncols - 1 + cid[i] w[i] = w.get(i, []) + [r] w[r] = w.get(r, []) + [i] neighbors = {} weights = {} for key in w: weights[key] = [1.] * len(w[key]) ids = range(n) if id_type == 'string': ids = ['id' + str(i) for i in ids] elif id_type == 'float': ids = [i * 1. for i in ids] if id_type == 'string' or id_type == 'float': id_dict = dict(zip(range(n), ids)) alt_w = {} alt_weights = {} for i in w: values = [id_dict[j] for j in w[i]] key = id_dict[i] alt_w[key] = values alt_weights[key] = weights[i] w = alt_w weights = alt_weights return pysal.weights.W(w, weights, ids=ids, id_order=ids[:]) def regime_weights(regimes): """ Construct spatial weights for regime neighbors. Block contiguity structures are relevant when defining neighbor relations based on membership in a regime. For example, all counties belonging to the same state could be defined as neighbors, in an analysis of all counties in the US. Parameters ---------- regimes : array, list ids of which regime an observation belongs to Returns ------- W : spatial weights instance Examples -------- >>> from pysal import regime_weights >>> import numpy as np >>> regimes = np.ones(25) >>> regimes[range(10,20)] = 2 >>> regimes[range(21,25)] = 3 >>> regimes array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 3., 3., 3., 3.]) >>> w = regime_weights(regimes) PendingDepricationWarning: regime_weights will be renamed to block_weights in PySAL 2.0 >>> w.weights[0] [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] >>> w.neighbors[0] [1, 2, 3, 4, 5, 6, 7, 8, 9, 20] >>> regimes = ['n','n','s','s','e','e','w','w','e'] >>> n = len(regimes) >>> w = regime_weights(regimes) PendingDepricationWarning: regime_weights will be renamed to block_weights in PySAL 2.0 >>> w.neighbors {0: [1], 1: [0], 2: [3], 3: [2], 4: [5, 8], 5: [4, 8], 6: [7], 7: [6], 8: [4, 5]} Notes ----- regime_weights will be deprecated in PySAL 2.0 and renamed to block_weights. """ msg = "PendingDepricationWarning: regime_weights will be " msg += "renamed to block_weights in PySAL 2.0" print msg return block_weights(regimes) def block_weights(regimes): """ Construct spatial weights for regime neighbors. Block contiguity structures are relevant when defining neighbor relations based on membership in a regime. For example, all counties belonging to the same state could be defined as neighbors, in an analysis of all counties in the US. Parameters ---------- regimes : list, array ids of which regime an observation belongs to Returns ------- W : spatial weights instance Examples -------- >>> from pysal import block_weights >>> import numpy as np >>> regimes = np.ones(25) >>> regimes[range(10,20)] = 2 >>> regimes[range(21,25)] = 3 >>> regimes array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 3., 3., 3., 3.]) >>> w = block_weights(regimes) >>> w.weights[0] [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] >>> w.neighbors[0] [1, 2, 3, 4, 5, 6, 7, 8, 9, 20] >>> regimes = ['n','n','s','s','e','e','w','w','e'] >>> n = len(regimes) >>> w = block_weights(regimes) >>> w.neighbors {0: [1], 1: [0], 2: [3], 3: [2], 4: [5, 8], 5: [4, 8], 6: [7], 7: [6], 8: [4, 5]} """ rids = np.unique(regimes) neighbors = {} NPNZ = np.nonzero regimes = np.array(regimes) for rid in rids: members = NPNZ(regimes == rid)[0] for member in members: neighbors[member] = members[NPNZ(members != member)[0]].tolist() return pysal.weights.W(neighbors) def comb(items, n=None): """ Combinations of size n taken from items Parameters ---------- items : list items to be drawn from n : integer size of combinations to take from items Returns ------- implicit : generator combinations of size n taken from items Examples -------- >>> x = range(4) >>> for c in comb(x, 2): ... print c ... [0, 1] [0, 2] [0, 3] [1, 2] [1, 3] [2, 3] """ if n is None: n = len(items) for i in range(len(items)): v = items[i:i + 1] if n == 1: yield v else: rest = items[i + 1:] for c in comb(rest, n - 1): yield v + c def order(w, kmax=3): """ Determine the non-redundant order of contiguity up to a specific order. Parameters ---------- w : W spatial weights object kmax : int maximum order of contiguity Returns ------- info : dictionary observation id is the key, value is a list of contiguity orders with a negative 1 in the ith position Notes ----- Implements the algorithm in Anselin and Smirnov (1996) [Anselin1996b]_ Examples -------- >>> from pysal import rook_from_shapefile as rfs >>> w = rfs(pysal.examples.get_path('10740.shp')) WARNING: there is one disconnected observation (no neighbors) Island id: [163] >>> w3 = order(w, kmax = 3) >>> w3[1][0:5] [1, -1, 1, 2, 1] """ #ids = w.neighbors.keys() ids = w.id_order info = {} for id_ in ids: s = [0] * w.n s[ids.index(id_)] = -1 for j in w.neighbors[id_]: s[ids.index(j)] = 1 k = 1 while k < kmax: knext = k + 1 if s.count(k): # get neighbors of order k js = [ids[j] for j, val in enumerate(s) if val == k] # get first order neighbors for order k neighbors for j in js: next_neighbors = w.neighbors[j] for neighbor in next_neighbors: nid = ids.index(neighbor) if s[nid] == 0: s[nid] = knext k = knext info[id_] = s return info def higher_order(w, k=2): """ Contiguity weights object of order k. Parameters ---------- w : W spatial weights object k : int order of contiguity Returns ------- implicit : W spatial weights object Notes ----- Proper higher order neighbors are returned such that i and j are k-order neighbors iff the shortest path from i-j is of length k. Examples -------- >>> from pysal import lat2W, higher_order >>> w10 = lat2W(10, 10) >>> w10_2 = higher_order(w10, 2) >>> w10_2[0] {2: 1.0, 11: 1.0, 20: 1.0} >>> w5 = lat2W() >>> w5[0] {1: 1.0, 5: 1.0} >>> w5[1] {0: 1.0, 2: 1.0, 6: 1.0} >>> w5_2 = higher_order(w5,2) >>> w5_2[0] {10: 1.0, 2: 1.0, 6: 1.0} """ return higher_order_sp(w, k) def higher_order_sp(w, k=2, shortest_path=True, diagonal=False): """ Contiguity weights for either a sparse W or pysal.weights.W for order k. Parameters ---------- w : W sparse_matrix, spatial weights object or scipy.sparse.csr.csr_instance k : int Order of contiguity shortest_path : boolean True: i,j and k-order neighbors if the shortest path for i,j is k False: i,j are k-order neighbors if there is a path from i,j of length k diagonal : boolean True: keep k-order (i,j) joins when i==j False: remove k-order (i,j) joins when i==j Returns ------- wk : W WSP, type matches type of w argument Notes ----- Lower order contiguities are removed. Examples -------- >>> import pysal >>> w25 = pysal.lat2W(5,5) >>> w25.n 25 >>> w25[0] {1: 1.0, 5: 1.0} >>> w25_2 = pysal.weights.util.higher_order_sp(w25, 2) >>> w25_2[0] {10: 1.0, 2: 1.0, 6: 1.0} >>> w25_2 = pysal.weights.util.higher_order_sp(w25, 2, diagonal=True) >>> w25_2[0] {0: 1.0, 10: 1.0, 2: 1.0, 6: 1.0} >>> w25_3 = pysal.weights.util.higher_order_sp(w25, 3) >>> w25_3[0] {15: 1.0, 3: 1.0, 11: 1.0, 7: 1.0} >>> w25_3 = pysal.weights.util.higher_order_sp(w25, 3, shortest_path=False) >>> w25_3[0] {1: 1.0, 3: 1.0, 5: 1.0, 7: 1.0, 11: 1.0, 15: 1.0} """ tw = type(w) id_order = None if tw == pysal.weights.weights.W: id_order = w.id_order w = w.sparse elif tw != scipy.sparse.csr.csr_matrix: print "Unsupported sparse argument." return None wk = w**k rk, ck = wk.nonzero() sk = set(zip(rk, ck)) if shortest_path: for j in range(1, k): wj = w**j rj, cj = wj.nonzero() sj = set(zip(rj, cj)) sk.difference_update(sj) if not diagonal: sk = set([(i,j) for i,j in sk if i!=j]) if id_order: d = dict([(i,[]) for i in id_order]) for pair in sk: k, v = pair k = id_order[k] v = id_order[v] d[k].append(v) return pysal.W(neighbors=d) else: d = {} for pair in sk: k, v = pair if k in d: d[k].append(v) else: d[k] = [v] return pysal.weights.WSP(pysal.W(neighbors=d).sparse) def w_local_cluster(w): """ Local clustering coefficients for each unit as a node in a graph. [ws]_ Parameters ---------- w : W spatial weights object Returns ------- c : array (w.n,1) local clustering coefficients Notes ----- The local clustering coefficient :math:`c_i` quantifies how close the neighbors of observation :math:`i` are to being a clique: .. math:: c_i = | \{w_{j,k}\} |/ (k_i(k_i - 1)): j,k \in N_i where :math:`N_i` is the set of neighbors to :math:`i`, :math:`k_i = |N_i|` and :math:`\{w_{j,k}\}` is the set of non-zero elements of the weights between pairs in :math:`N_i`. [Watts1998]_ Examples -------- >>> w = pysal.lat2W(3,3, rook=False) >>> w_local_cluster(w) array([[ 1. ], [ 0.6 ], [ 1. ], [ 0.6 ], [ 0.42857143], [ 0.6 ], [ 1. ], [ 0.6 ], [ 1. ]]) """ c = np.zeros((w.n, 1), float) w.transformation = 'b' for i, id in enumerate(w.id_order): ki = max(w.cardinalities[id], 1) # deal with islands Ni = w.neighbors[id] wi = pysal.w_subset(w, Ni).full()[0] c[i] = wi.sum() / (ki * (ki - 1)) return c def shimbel(w): """ Find the Shimbel matrix for first order contiguity matrix. Parameters ---------- w : W spatial weights object Returns ------- info : list list of lists; one list for each observation which stores the shortest order between it and each of the the other observations. Examples -------- >>> from pysal import lat2W, shimbel >>> w5 = lat2W() >>> w5_shimbel = shimbel(w5) >>> w5_shimbel[0][24] 8 >>> w5_shimbel[0][0:4] [-1, 1, 2, 3] >>> """ info = {} ids = w.id_order for id in ids: s = [0] * w.n s[ids.index(id)] = -1 for j in w.neighbors[id]: s[ids.index(j)] = 1 k = 1 flag = s.count(0) while flag: p = -1 knext = k + 1 for j in range(s.count(k)): neighbor = s.index(k, p + 1) p = neighbor next_neighbors = w.neighbors[ids[p]] for neighbor in next_neighbors: nid = ids.index(neighbor) if s[nid] == 0: s[nid] = knext k = knext flag = s.count(0) info[id] = s return info def full(w): """ Generate a full numpy array. Parameters ---------- w : W spatial weights object Returns ------- (fullw, keys) : tuple first element being the full numpy array and second element keys being the ids associated with each row in the array. Examples -------- >>> from pysal import W, full >>> neighbors = {'first':['second'],'second':['first','third'],'third':['second']} >>> weights = {'first':[1],'second':[1,1],'third':[1]} >>> w = W(neighbors, weights) >>> wf, ids = full(w) >>> wf array([[ 0., 1., 0.], [ 1., 0., 1.], [ 0., 1., 0.]]) >>> ids ['first', 'second', 'third'] """ wfull = np.zeros([w.n, w.n], dtype=float) keys = w.neighbors.keys() if w.id_order: keys = w.id_order for i, key in enumerate(keys): n_i = w.neighbors[key] w_i = w.weights[key] for j, wij in zip(n_i, w_i): c = keys.index(j) wfull[i, c] = wij return (wfull, keys) def full2W(m, ids=None): ''' Create a PySAL W object from a full array. Parameters ---------- m : array nxn array with the full weights matrix ids : list User ids assumed to be aligned with m Returns ------- w : W PySAL weights object Examples -------- >>> import pysal as ps >>> import numpy as np Create an array of zeros >>> a = np.zeros((4, 4)) For loop to fill it with random numbers >>> for i in range(len(a)): ... for j in range(len(a[i])): ... if i!=j: ... a[i, j] = np.random.random(1) Create W object >>> w = ps.weights.util.full2W(a) >>> w.full()[0] == a array([[ True, True, True, True], [ True, True, True, True], [ True, True, True, True], [ True, True, True, True]], dtype=bool) Create list of user ids >>> ids = ['myID0', 'myID1', 'myID2', 'myID3'] >>> w = ps.weights.util.full2W(a, ids=ids) >>> w.full()[0] == a array([[ True, True, True, True], [ True, True, True, True], [ True, True, True, True], [ True, True, True, True]], dtype=bool) ''' if m.shape[0] != m.shape[1]: raise ValueError('Your array is not square') neighbors, weights = {}, {} for i in xrange(m.shape[0]): # for i, row in enumerate(m): row = m[i] if ids: i = ids[i] ngh = list(row.nonzero()[0]) weights[i] = list(row[ngh]) ngh = list(ngh) if ids: ngh = [ids[j] for j in ngh] neighbors[i] = ngh return pysal.W(neighbors, weights, id_order=ids) def WSP2W(wsp, silent_island_warning=False): """ Convert a pysal WSP object (thin weights matrix) to a pysal W object. Parameters ---------- wsp : WSP PySAL sparse weights object silent_island_warning : boolean Switch to turn off (default on) print statements for every observation with islands Returns ------- w : W PySAL weights object Examples -------- >>> import pysal Build a 10x10 scipy.sparse matrix for a rectangular 2x5 region of cells (rook contiguity), then construct a PySAL sparse weights object (wsp). >>> sp = pysal.weights.lat2SW(2, 5) >>> wsp = pysal.weights.WSP(sp) >>> wsp.n 10 >>> print wsp.sparse[0].todense() [[0 1 0 0 0 1 0 0 0 0]] Convert this sparse weights object to a standard PySAL weights object. >>> w = pysal.weights.WSP2W(wsp) >>> w.n 10 >>> print w.full()[0][0] [ 0. 1. 0. 0. 0. 1. 0. 0. 0. 0.] """ wsp.sparse indices = wsp.sparse.indices data = wsp.sparse.data indptr = wsp.sparse.indptr id_order = wsp.id_order if id_order: # replace indices with user IDs indices = [id_order[i] for i in indices] else: id_order = range(wsp.n) neighbors, weights = {}, {} start = indptr[0] for i in xrange(wsp.n): oid = id_order[i] end = indptr[i + 1] neighbors[oid] = indices[start:end] weights[oid] = data[start:end] start = end ids = copy.copy(wsp.id_order) w = pysal.W(neighbors, weights, ids, silent_island_warning=silent_island_warning) w._sparse = copy.deepcopy(wsp.sparse) w._cache['sparse'] = w._sparse return w def insert_diagonal(w, diagonal=1.0, wsp=False): """ Returns a new weights object with values inserted along the main diagonal. Parameters ---------- w : W Spatial weights object diagonal : float, int or array Defines the value(s) to which the weights matrix diagonal should be set. If a constant is passed then each element along the diagonal will get this value (default is 1.0). An array of length w.n can be passed to set explicit values to each element along the diagonal (assumed to be in the same order as w.id_order). wsp : boolean If True return a thin weights object of the type WSP, if False return the standard W object. Returns ------- w : W Spatial weights object Examples -------- >>> import pysal >>> import numpy as np Build a basic rook weights matrix, which has zeros on the diagonal, then insert ones along the diagonal. >>> w = pysal.lat2W(5, 5, id_type='string') >>> w_const = pysal.weights.insert_diagonal(w) >>> w['id0'] {'id5': 1.0, 'id1': 1.0} >>> w_const['id0'] {'id5': 1.0, 'id0': 1.0, 'id1': 1.0} Insert different values along the main diagonal. >>> diag = np.arange(100, 125) >>> w_var = pysal.weights.insert_diagonal(w, diag) >>> w_var['id0'] {'id5': 1.0, 'id0': 100.0, 'id1': 1.0} """ w_new = copy.deepcopy(w.sparse) w_new = w_new.tolil() if issubclass(type(diagonal), np.ndarray): if w.n != diagonal.shape[0]: raise Exception("shape of w and diagonal do not match") w_new.setdiag(diagonal) elif operator.isNumberType(diagonal): w_new.setdiag([diagonal] * w.n) else: raise Exception("Invalid value passed to diagonal") w_out = pysal.weights.WSP(w_new, copy.copy(w.id_order)) if wsp: return w_out else: return WSP2W(w_out) def remap_ids(w, old2new, id_order=[]): """ Remaps the IDs in a spatial weights object. Parameters ---------- w : W Spatial weights object old2new : dictionary Dictionary where the keys are the IDs in w (i.e. "old IDs") and the values are the IDs to replace them (i.e. "new IDs") id_order : list An ordered list of new IDs, which defines the order of observations when iterating over W. If not set then the id_order in w will be used. Returns ------- implicit : W Spatial weights object with new IDs Examples -------- >>> from pysal import lat2W, remap_ids >>> w = lat2W(3,2) >>> w.id_order [0, 1, 2, 3, 4, 5] >>> w.neighbors[0] [2, 1] >>> old_to_new = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'} >>> w_new = remap_ids(w, old_to_new) >>> w_new.id_order ['a', 'b', 'c', 'd', 'e', 'f'] >>> w_new.neighbors['a'] ['c', 'b'] """ if not isinstance(w, pysal.weights.W): raise Exception("w must be a spatial weights object") new_neigh = {} new_weights = {} for key, value in w.neighbors.iteritems(): new_values = [old2new[i] for i in value] new_key = old2new[key] new_neigh[new_key] = new_values new_weights[new_key] = copy.copy(w.weights[key]) if id_order: return pysal.weights.W(new_neigh, new_weights, id_order) else: if w.id_order: id_order = [old2new[i] for i in w.id_order] return pysal.weights.W(new_neigh, new_weights, id_order) else: return pysal.weights.W(new_neigh, new_weights) def get_ids(shapefile, idVariable): """ Gets the IDs from the DBF file that moves with a given shape file. Parameters ---------- shapefile : string name of a shape file including suffix idVariable : string name of a column in the shapefile's DBF to use for ids Returns ------- ids : list a list of IDs Examples -------- >>> from pysal.weights.util import get_ids >>> polyids = get_ids(pysal.examples.get_path("columbus.shp"), "POLYID") >>> polyids[:5] [1, 2, 3, 4, 5] """ try: dbname = os.path.splitext(shapefile)[0] + '.dbf' db = pysal.open(dbname) var = db.by_col[idVariable] db.close() return var except IOError: msg = 'The shapefile "%s" appears to be missing its DBF file. The DBF file "%s" could not be found.' % ( shapefile, dbname) raise IOError(msg) except AttributeError: msg = 'The variable "%s" was not found in the DBF file. The DBF contains the following variables: %s.' % ( idVariable, ','.join(db.header)) raise KeyError(msg) def get_points_array_from_shapefile(shapefile): """ Gets a data array of x and y coordinates from a given shapefile. Parameters ---------- shapefile : string name of a shape file including suffix Returns ------- points : array (n, 2) a data array of x and y coordinates Notes ----- If the given shape file includes polygons, this function returns x and y coordinates of the polygons' centroids Examples -------- Point shapefile >>> from pysal.weights.util import get_points_array_from_shapefile >>> xy = get_points_array_from_shapefile(pysal.examples.get_path('juvenile.shp')) >>> xy[:3] array([[ 94., 93.], [ 80., 95.], [ 79., 90.]]) Polygon shapefile >>> xy = get_points_array_from_shapefile(pysal.examples.get_path('columbus.shp')) >>> xy[:3] array([[ 8.82721847, 14.36907602], [ 8.33265837, 14.03162401], [ 9.01226541, 13.81971908]]) """ f = pysal.open(shapefile) if f.type.__name__ == 'Polygon': data = np.array([shape.centroid for shape in f]) elif f.type.__name__ == 'Point': data = np.array([shape for shape in f]) f.close() return data def min_threshold_distance(data, p=2): """ Get the maximum nearest neighbor distance. Parameters ---------- data : array (n,k) or KDTree where KDtree.data is array (n,k) n observations on k attributes p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance Returns ------- nnd : float maximum nearest neighbor distance between the n observations Examples -------- >>> from pysal.weights.util import min_threshold_distance >>> import numpy as np >>> x, y = np.indices((5, 5)) >>> x.shape = (25, 1) >>> y.shape = (25, 1) >>> data = np.hstack([x, y]) >>> min_threshold_distance(data) 1.0 """ if issubclass(type(data), scipy.spatial.KDTree): kd = data data = kd.data else: kd = KDTree(data) nn = kd.query(data, k=2, p=p) nnd = nn[0].max(axis=0)[1] return nnd def lat2SW(nrows=3, ncols=5, criterion="rook", row_st=False): """ Create a sparse W matrix for a regular lattice. Parameters ---------- nrows : int number of rows ncols : int number of columns rook : {"rook", "queen", "bishop"} type of contiguity. Default is rook. row_st : boolean If True, the created sparse W object is row-standardized so every row sums up to one. Defaults to False. Returns ------- w : scipy.sparse.dia_matrix instance of a scipy sparse matrix Notes ----- Observations are row ordered: first k observations are in row 0, next k in row 1, and so on. This method directly creates the W matrix using the strucuture of the contiguity type. Examples -------- >>> from pysal import weights >>> w9 = weights.lat2SW(3,3) >>> w9[0,1] 1 >>> w9[3,6] 1 >>> w9r = weights.lat2SW(3,3, row_st=True) >>> w9r[3,6] 0.33333333333333331 """ n = nrows * ncols diagonals = [] offsets = [] if criterion == "rook" or criterion == "queen": d = np.ones((1, n)) for i in range(ncols - 1, n, ncols): d[0, i] = 0 diagonals.append(d) offsets.append(-1) d = np.ones((1, n)) diagonals.append(d) offsets.append(-ncols) if criterion == "queen" or criterion == "bishop": d = np.ones((1, n)) for i in range(0, n, ncols): d[0, i] = 0 diagonals.append(d) offsets.append(-(ncols - 1)) d = np.ones((1, n)) for i in range(ncols - 1, n, ncols): d[0, i] = 0 diagonals.append(d) offsets.append(-(ncols + 1)) data = np.concatenate(diagonals) offsets = np.array(offsets) m = sparse.dia_matrix((data, offsets), shape=(n, n), dtype=np.int8) m = m + m.T if row_st: m = sparse.spdiags(1. / m.sum(1).T, 0, *m.shape) * m return m def write_gal(file, k=10): f = open(file, 'w') n = k * k f.write("0 %d" % n) for i in xrange(n): row = i / k col = i % k neighs = [i - i, i + 1, i - k, i + k] neighs = [j for j in neighs if j >= 0 and j < n] f.write("\n%d %d\n" % (i, len(neighs))) f.write(" ".join(map(str, neighs))) f.close() if __name__ == "__main__": from pysal import lat2W assert (lat2W(5, 5).sparse.todense() == lat2SW(5, 5).todense()).all() assert (lat2W(5, 3).sparse.todense() == lat2SW(5, 3).todense()).all() assert (lat2W(5, 3, rook=False).sparse.todense() == lat2SW(5, 3, 'queen').todense()).all() assert (lat2W(50, 50, rook=False).sparse.todense() == lat2SW(50, 50, 'queen').todense()).all()
bsd-3-clause
3,801,147,828,704,531,500
25.652755
114
0.496304
false
benjmarshall/hls_scratchpad
python_automation/run_hls.py
1
7359
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ A Vivado HLS Command Line Helper tool Copyright (c) 2017 Ben Marshall """ ### Imports ### import os import sys import shutil import argparse from glob import glob import contextlib ### Class definitions ### class Error(Exception): """Base class for exceptions in this module.""" pass class ConfigError(Error): """Exception raised for options not defined in config. Attributes: message -- explanation of the error """ def __init__(self, message): self.message = message ### Support Functions ### def try_delete(item): try: shutil.rmtree(item) except OSError: try: os.remove(item) except OSError: return 1 else: return 0 else: return 0 def get_vars_from_file(filename): import imp f = open(filename) config = imp.load_source('config', '', f) f.close() return config def parse_config_vars(config_loaded, config, errors): config_loaded_dict = dict((name, getattr(config_loaded, name)) for name in dir(config_loaded) if not name.startswith('__')) config_loaded_set = set(config_loaded_dict) config_set = set(config) options_defined = config_loaded_set.intersection(config_set) for name in config: if str(name) in options_defined: config[name] = config_loaded_dict[name] try: if not config[name]: raise ConfigError("Error: " + name + " is not defined in config file. No default exists, please define a value in the config file.") except ConfigError as err: errors.append(err) continue def just_loop_on(input): if isinstance(input, str): yield input else: try: for item in input: yield item except TypeError: yield input def main(): # Set up default config dictionary config = { "project_name" : "proj_" + os.path.relpath(".",".."), "top_level_function_name" : "", "src_dir_name" : "src", "tb_dir_name" : "tb", "src_files" : "", "tb_files" : "", "part_name" : "", "clock_period" : "", "language" : "vhdl", } # Parse command line arguments parser = argparse.ArgumentParser(description="Helper tool for using Vivado HLS through the command line. If no arguments are specified then a default run is executed which includes C simulation, C synthesis, Cosimulation and export for both Vivado IP Catalog and System Generator. If any of the run options are specified then only those specified are performed.") parser.add_argument("-clean", help="remove all Vivado HLS generated files", action="store_true") parser.add_argument("-keep", help="keep all previous solution and generate a new one", action="store_true") parser.add_argument("-csim", help="perform C simulation stage", action="store_true") parser.add_argument("-syn", help="perform C synthesis stage", action="store_true") cosim_group = parser.add_mutually_exclusive_group() cosim_group.add_argument("-cosim", help="perform cosimulation", action="store_true") cosim_group.add_argument("-cosim_debug", help="perform cosimulation with debug logging", action="store_true") export_ip_group = parser.add_mutually_exclusive_group() export_ip_group.add_argument("-export_ip", help="perform export for Vivado IP Catalog", action="store_true") export_ip_group.add_argument("-evaluate_ip", help="perform export for Vivado IP Catalog with build to place and route", action="store_true") export_dsp_group = parser.add_mutually_exclusive_group() export_dsp_group.add_argument("-export_dsp", help="perform export for System Generator", action="store_true") export_dsp_group.add_argument("-evaluate_dsp", help="perform export for System Generator with build to place and route", action="store_true") args = parser.parse_args() # Check for clean argument if args.clean: if len(sys.argv) > 2: print("Warning: The 'Clean' option is exclusive. All other arguments will be ignored.") if try_delete(config["project_name"]) + try_delete("run_hls.tcl") + try_delete("vivado_hls.log") == 3: print("Warning: Nothing to remove!") else: print("Cleaned up generated files.") sys.exit() # Load project specifics from local config file and add to config dict config_loaded = get_vars_from_file('hls_config.py') errors = [] parse_config_vars(config_loaded, config, errors) if len(errors) != 0: for err in errors: print(err) print("Config Errors, exiting...") sys.exit() # Write out TCL file file = open("run_hls.tcl","w") file.write("open_project " + config["project_name"] + "\n") file.write("set_top " + config["top_level_function_name"] + "\n") for src_file in config["src_files"]: file.write("add_files " + config["src_dir_name"] + "/" + src_file + "\n") for tb_file in config["tb_files"]: file.write("add_files -tb " + config["tb_dir_name"] + "/" + tb_file + "\n") if args.keep: paths = glob(config["project_name"] + "/solution*/") solution_num = len(paths) + 1 if solution_num == 1: file.write("open_solution -reset \"solution1\"" + "\n") else: file.write("open_solution -reset \"solution" + str(solution_num) + "\"" + "\n") else: file.write("open_solution \"solution1\"" + "\n") file.write("set_part \{" + config["part_name"] + "\}" + "\n") file.write("create_clock -period " + config["clock_period"] + " -name default" + "\n") if not(args.csim or args.syn or args.cosim or args.cosim_debug or args.export_ip or args.export_dsp or args.evaluate_ip or args.evaluate_dsp): file.write("csim_design -clean" + "\n") file.write("csynth_design" + "\n") file.write("cosim_design -O -rtl " + config["language"] + "\n") file.write("export_design -format ip_catalog" + "\n") file.write("export_design -format sysgen" + "\n") file.write("exit" + "\n") else: if args.csim: file.write("csim_design -clean" + "\n") if args.syn: file.write("csynth_design" + "\n") if args.cosim: for language in just_loop_on(config["language"]): file.write("cosim_design -O -rtl " + language + "\n") if args.cosim_debug: for language in just_loop_on(config["language"]): file.write("cosim_design -rtl " + language + " -trace_level all" + "\n") if args.export_dsp: file.write("export_design -format ip_catalog" + "\n") if args.export_ip: file.write("export_design -format sysgen" + "\n") if args.evaluate_dsp: for language in just_loop_on(config["language"]): file.write("export_design -format ip_catalog -evaluate " + language + "\n") if args.evaluate_ip: for language in just_loop_on(config["language"]): file.write("export_design -format sysgen -evaluate " + language + "\n") file.write("exit") file.close() # Call the Vivado HLS process os.system("vivado_hls -f run_hls.tcl") if __name__ == "__main__": main()
mit
8,336,447,695,265,548,000
39.434066
367
0.612855
false
lis-epfl/mavlink
pymavlink/mavutil.py
3
59548
#!/usr/bin/env python ''' mavlink python utility functions Copyright Andrew Tridgell 2011 Released under GNU GPL version 3 or later ''' import socket, math, struct, time, os, fnmatch, array, sys, errno import select, mavexpression # adding these extra imports allows pymavlink to be used directly with pyinstaller # without having complex spec files. To allow for installs that don't have ardupilotmega # at all we avoid throwing an exception if it isn't installed try: import json from pymavlink.dialects.v10 import ardupilotmega except Exception: pass # maximum packet length for a single receive call - use the UDP limit UDP_MAX_PACKET_LEN = 65535 # Store the MAVLink library for the currently-selected dialect # (set by set_dialect()) mavlink = None # Store the mavlink file currently being operated on # (set by mavlink_connection()) mavfile_global = None # If the caller hasn't specified a particular native/legacy version, use this default_native = False # Use a globally-set MAVLink dialect if one has been specified as an environment variable. if not 'MAVLINK_DIALECT' in os.environ: os.environ['MAVLINK_DIALECT'] = 'ardupilotmega' def mavlink10(): '''return True if using MAVLink 1.0''' return not 'MAVLINK09' in os.environ def evaluate_expression(expression, vars): '''evaluation an expression''' return mavexpression.evaluate_expression(expression, vars) def evaluate_condition(condition, vars): '''evaluation a conditional (boolean) statement''' if condition is None: return True v = evaluate_expression(condition, vars) if v is None: return False return v class location(object): '''represent a GPS coordinate''' def __init__(self, lat, lng, alt=0, heading=0): self.lat = lat self.lng = lng self.alt = alt self.heading = heading def __str__(self): return "lat=%.6f,lon=%.6f,alt=%.1f" % (self.lat, self.lng, self.alt) def set_dialect(dialect): '''set the MAVLink dialect to work with. For example, set_dialect("ardupilotmega") ''' global mavlink, current_dialect from .generator import mavparse if mavlink is None or mavlink.WIRE_PROTOCOL_VERSION == "1.0" or not 'MAVLINK09' in os.environ: wire_protocol = mavparse.PROTOCOL_1_0 modname = "pymavlink.dialects.v10." + dialect else: wire_protocol = mavparse.PROTOCOL_0_9 modname = "pymavlink.dialects.v09." + dialect try: mod = __import__(modname) except Exception: # auto-generate the dialect module from .generator.mavgen import mavgen_python_dialect mavgen_python_dialect(dialect, wire_protocol) mod = __import__(modname) components = modname.split('.') for comp in components[1:]: mod = getattr(mod, comp) current_dialect = dialect mavlink = mod # Set the default dialect. This is done here as it needs to be after the function declaration set_dialect(os.environ['MAVLINK_DIALECT']) class mavfile(object): '''a generic mavlink port''' def __init__(self, fd, address, source_system=255, notimestamps=False, input=True, use_native=default_native): global mavfile_global if input: mavfile_global = self self.fd = fd self.address = address self.messages = { 'MAV' : self } if mavlink.WIRE_PROTOCOL_VERSION == "1.0": self.messages['HOME'] = mavlink.MAVLink_gps_raw_int_message(0,0,0,0,0,0,0,0,0,0) mavlink.MAVLink_waypoint_message = mavlink.MAVLink_mission_item_message else: self.messages['HOME'] = mavlink.MAVLink_gps_raw_message(0,0,0,0,0,0,0,0,0) self.params = {} self.target_system = 0 self.target_component = 0 self.source_system = source_system self.first_byte = True self.robust_parsing = True self.mav = mavlink.MAVLink(self, srcSystem=self.source_system, use_native=use_native) self.mav.robust_parsing = self.robust_parsing self.logfile = None self.logfile_raw = None self.param_fetch_in_progress = False self.param_fetch_complete = False self.start_time = time.time() self.flightmode = "UNKNOWN" self.vehicle_type = "UNKNOWN" self.mav_type = mavlink.MAV_TYPE_FIXED_WING self.base_mode = 0 self.timestamp = 0 self.message_hooks = [] self.idle_hooks = [] self.uptime = 0.0 self.notimestamps = notimestamps self._timestamp = None self.ground_pressure = None self.ground_temperature = None self.altitude = 0 self.WIRE_PROTOCOL_VERSION = mavlink.WIRE_PROTOCOL_VERSION self.last_seq = {} self.mav_loss = 0 self.mav_count = 0 self.stop_on_EOF = False self.portdead = False def auto_mavlink_version(self, buf): '''auto-switch mavlink protocol version''' global mavlink if len(buf) == 0: return try: magic = ord(buf[0]) except: magic = buf[0] if not magic in [ 85, 254 ]: return self.first_byte = False if self.WIRE_PROTOCOL_VERSION == "0.9" and magic == 254: self.WIRE_PROTOCOL_VERSION = "1.0" set_dialect(current_dialect) elif self.WIRE_PROTOCOL_VERSION == "1.0" and magic == 85: self.WIRE_PROTOCOL_VERSION = "0.9" set_dialect(current_dialect) os.environ['MAVLINK09'] = '1' else: return # switch protocol (callback, callback_args, callback_kwargs) = (self.mav.callback, self.mav.callback_args, self.mav.callback_kwargs) self.mav = mavlink.MAVLink(self, srcSystem=self.source_system) self.mav.robust_parsing = self.robust_parsing self.WIRE_PROTOCOL_VERSION = mavlink.WIRE_PROTOCOL_VERSION (self.mav.callback, self.mav.callback_args, self.mav.callback_kwargs) = (callback, callback_args, callback_kwargs) def recv(self, n=None): '''default recv method''' raise RuntimeError('no recv() method supplied') def close(self, n=None): '''default close method''' raise RuntimeError('no close() method supplied') def write(self, buf): '''default write method''' raise RuntimeError('no write() method supplied') def select(self, timeout): '''wait for up to timeout seconds for more data''' if self.fd is None: time.sleep(min(timeout,0.5)) return True try: (rin, win, xin) = select.select([self.fd], [], [], timeout) except select.error: return False return len(rin) == 1 def pre_message(self): '''default pre message call''' return def set_rtscts(self, enable): '''enable/disable RTS/CTS if applicable''' return def post_message(self, msg): '''default post message call''' if '_posted' in msg.__dict__: return msg._posted = True msg._timestamp = time.time() type = msg.get_type() if type != 'HEARTBEAT' or (msg.type != mavlink.MAV_TYPE_GCS and msg.type != mavlink.MAV_TYPE_GIMBAL): self.messages[type] = msg if 'usec' in msg.__dict__: self.uptime = msg.usec * 1.0e-6 if 'time_boot_ms' in msg.__dict__: self.uptime = msg.time_boot_ms * 1.0e-3 if self._timestamp is not None: if self.notimestamps: msg._timestamp = self.uptime else: msg._timestamp = self._timestamp src_system = msg.get_srcSystem() src_component = msg.get_srcComponent() src_tuple = (src_system, src_component) radio_tuple = (ord('3'), ord('D')) if not (src_tuple == radio_tuple or msg.get_type() == 'BAD_DATA'): if not src_tuple in self.last_seq: last_seq = -1 else: last_seq = self.last_seq[src_tuple] seq = (last_seq+1) % 256 seq2 = msg.get_seq() if seq != seq2 and last_seq != -1: diff = (seq2 - seq) % 256 self.mav_loss += diff #print("lost %u seq=%u seq2=%u last_seq=%u src_system=%u %s" % (diff, seq, seq2, last_seq, src_system, msg.get_type())) self.last_seq[src_tuple] = seq2 self.mav_count += 1 self.timestamp = msg._timestamp if type == 'HEARTBEAT' and msg.get_srcComponent() != mavlink.MAV_COMP_ID_GIMBAL: self.target_system = msg.get_srcSystem() self.target_component = msg.get_srcComponent() if mavlink.WIRE_PROTOCOL_VERSION == '1.0' and msg.type != mavlink.MAV_TYPE_GCS: self.flightmode = mode_string_v10(msg) self.mav_type = msg.type self.base_mode = msg.base_mode elif type == 'PARAM_VALUE': s = str(msg.param_id) self.params[str(msg.param_id)] = msg.param_value if msg.param_index+1 == msg.param_count: self.param_fetch_in_progress = False self.param_fetch_complete = True elif type == 'SYS_STATUS' and mavlink.WIRE_PROTOCOL_VERSION == '0.9': self.flightmode = mode_string_v09(msg) elif type == 'GPS_RAW': if self.messages['HOME'].fix_type < 2: self.messages['HOME'] = msg elif type == 'GPS_RAW_INT': if self.messages['HOME'].fix_type < 3: self.messages['HOME'] = msg for hook in self.message_hooks: hook(self, msg) def packet_loss(self): '''packet loss as a percentage''' if self.mav_count == 0: return 0 return (100.0*self.mav_loss)/(self.mav_count+self.mav_loss) def recv_msg(self): '''message receive routine''' self.pre_message() while True: n = self.mav.bytes_needed() s = self.recv(n) numnew = len(s) if numnew != 0: if self.logfile_raw: self.logfile_raw.write(str(s)) if self.first_byte: self.auto_mavlink_version(s) # We always call parse_char even if the new string is empty, because the existing message buf might already have some valid packet # we can extract msg = self.mav.parse_char(s) if msg: if self.logfile and msg.get_type() != 'BAD_DATA' : usec = int(time.time() * 1.0e6) & ~3 self.logfile.write(str(struct.pack('>Q', usec) + msg.get_msgbuf())) self.post_message(msg) return msg else: # if we failed to parse any messages _and_ no new bytes arrived, return immediately so the client has the option to # timeout if numnew == 0: return None def recv_match(self, condition=None, type=None, blocking=False, timeout=None): '''recv the next MAVLink message that matches the given condition type can be a string or a list of strings''' if type is not None and not isinstance(type, list): type = [type] start_time = time.time() while True: if timeout is not None: now = time.time() if now < start_time: start_time = now # If an external process rolls back system time, we should not spin forever. if start_time + timeout < time.time(): return None m = self.recv_msg() if m is None: if blocking: for hook in self.idle_hooks: hook(self) if timeout is None: self.select(0.05) else: self.select(timeout/2) continue return None if type is not None and not m.get_type() in type: continue if not evaluate_condition(condition, self.messages): continue return m def check_condition(self, condition): '''check if a condition is true''' return evaluate_condition(condition, self.messages) def mavlink10(self): '''return True if using MAVLink 1.0''' return self.WIRE_PROTOCOL_VERSION == "1.0" def setup_logfile(self, logfile, mode='w'): '''start logging to the given logfile, with timestamps''' self.logfile = open(logfile, mode=mode) def setup_logfile_raw(self, logfile, mode='w'): '''start logging raw bytes to the given logfile, without timestamps''' self.logfile_raw = open(logfile, mode=mode) def wait_heartbeat(self, blocking=True): '''wait for a heartbeat so we know the target system IDs''' return self.recv_match(type='HEARTBEAT', blocking=blocking) def param_fetch_all(self): '''initiate fetch of all parameters''' if time.time() - getattr(self, 'param_fetch_start', 0) < 2.0: # don't fetch too often return self.param_fetch_start = time.time() self.param_fetch_in_progress = True self.mav.param_request_list_send(self.target_system, self.target_component) def param_fetch_one(self, name): '''initiate fetch of one parameter''' try: idx = int(name) self.mav.param_request_read_send(self.target_system, self.target_component, "", idx) except Exception: self.mav.param_request_read_send(self.target_system, self.target_component, name, -1) def time_since(self, mtype): '''return the time since the last message of type mtype was received''' if not mtype in self.messages: return time.time() - self.start_time return time.time() - self.messages[mtype]._timestamp def param_set_send(self, parm_name, parm_value, parm_type=None): '''wrapper for parameter set''' if self.mavlink10(): if parm_type == None: parm_type = mavlink.MAVLINK_TYPE_FLOAT self.mav.param_set_send(self.target_system, self.target_component, parm_name, parm_value, parm_type) else: self.mav.param_set_send(self.target_system, self.target_component, parm_name, parm_value) def waypoint_request_list_send(self): '''wrapper for waypoint_request_list_send''' if self.mavlink10(): self.mav.mission_request_list_send(self.target_system, self.target_component) else: self.mav.waypoint_request_list_send(self.target_system, self.target_component) def waypoint_clear_all_send(self): '''wrapper for waypoint_clear_all_send''' if self.mavlink10(): self.mav.mission_clear_all_send(self.target_system, self.target_component) else: self.mav.waypoint_clear_all_send(self.target_system, self.target_component) def waypoint_request_send(self, seq): '''wrapper for waypoint_request_send''' if self.mavlink10(): self.mav.mission_request_send(self.target_system, self.target_component, seq) else: self.mav.waypoint_request_send(self.target_system, self.target_component, seq) def waypoint_set_current_send(self, seq): '''wrapper for waypoint_set_current_send''' if self.mavlink10(): self.mav.mission_set_current_send(self.target_system, self.target_component, seq) else: self.mav.waypoint_set_current_send(self.target_system, self.target_component, seq) def waypoint_current(self): '''return current waypoint''' if self.mavlink10(): m = self.recv_match(type='MISSION_CURRENT', blocking=True) else: m = self.recv_match(type='WAYPOINT_CURRENT', blocking=True) return m.seq def waypoint_count_send(self, seq): '''wrapper for waypoint_count_send''' if self.mavlink10(): self.mav.mission_count_send(self.target_system, self.target_component, seq) else: self.mav.waypoint_count_send(self.target_system, self.target_component, seq) def set_mode_flag(self, flag, enable): ''' Enables/ disables MAV_MODE_FLAG @param flag The mode flag, see MAV_MODE_FLAG enum @param enable Enable the flag, (True/False) ''' if self.mavlink10(): mode = self.base_mode if (enable == True): mode = mode | flag elif (enable == False): mode = mode & ~flag self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_DO_SET_MODE, 0, mode, 0, 0, 0, 0, 0, 0) else: print("Set mode flag not supported") def set_mode_auto(self): '''enter auto mode''' if self.mavlink10(): self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_MISSION_START, 0, 0, 0, 0, 0, 0, 0, 0) else: MAV_ACTION_SET_AUTO = 13 self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_SET_AUTO) def mode_mapping(self): '''return dictionary mapping mode names to numbers, or None if unknown''' mav_type = self.field('HEARTBEAT', 'type', self.mav_type) if mav_type is None: return None map = None if mav_type in [mavlink.MAV_TYPE_QUADROTOR, mavlink.MAV_TYPE_HELICOPTER, mavlink.MAV_TYPE_HEXAROTOR, mavlink.MAV_TYPE_OCTOROTOR, mavlink.MAV_TYPE_TRICOPTER]: map = mode_mapping_acm if mav_type == mavlink.MAV_TYPE_FIXED_WING: map = mode_mapping_apm if mav_type == mavlink.MAV_TYPE_GROUND_ROVER: map = mode_mapping_rover if mav_type == mavlink.MAV_TYPE_ANTENNA_TRACKER: map = mode_mapping_tracker if map is None: return None inv_map = dict((a, b) for (b, a) in list(map.items())) return inv_map def set_mode(self, mode): '''enter arbitrary mode''' if isinstance(mode, str): map = self.mode_mapping() if map is None or mode not in map: print("Unknown mode '%s'" % mode) return mode = map[mode] self.mav.set_mode_send(self.target_system, mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED, mode) def set_mode_rtl(self): '''enter RTL mode''' if self.mavlink10(): self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 0, 0, 0, 0, 0, 0, 0, 0) else: MAV_ACTION_RETURN = 3 self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_RETURN) def set_mode_manual(self): '''enter MANUAL mode''' if self.mavlink10(): self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_DO_SET_MODE, 0, mavlink.MAV_MODE_MANUAL_ARMED, 0, 0, 0, 0, 0, 0) else: MAV_ACTION_SET_MANUAL = 12 self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_SET_MANUAL) def set_mode_fbwa(self): '''enter FBWA mode''' if self.mavlink10(): self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_DO_SET_MODE, 0, mavlink.MAV_MODE_STABILIZE_ARMED, 0, 0, 0, 0, 0, 0) else: print("Forcing FBWA not supported") def set_mode_loiter(self): '''enter LOITER mode''' if self.mavlink10(): self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_NAV_LOITER_UNLIM, 0, 0, 0, 0, 0, 0, 0, 0) else: MAV_ACTION_LOITER = 27 self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_LOITER) def set_servo(self, channel, pwm): '''set a servo value''' self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_DO_SET_SERVO, 0, channel, pwm, 0, 0, 0, 0, 0) def set_relay(self, relay_pin=0, state=True): '''Set relay_pin to value of state''' if self.mavlink10(): self.mav.command_long_send( self.target_system, # target_system self.target_component, # target_component mavlink.MAV_CMD_DO_SET_RELAY, # command 0, # Confirmation relay_pin, # Relay Number int(state), # state (1 to indicate arm) 0, # param3 (all other params meaningless) 0, # param4 0, # param5 0, # param6 0) # param7 else: print("Setting relays not supported.") def calibrate_level(self): '''calibrate accels (1D version)''' self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0, 1, 1, 0, 0, 0, 0, 0) def calibrate_pressure(self): '''calibrate pressure''' if self.mavlink10(): self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0, 0, 0, 1, 0, 0, 0, 0) else: MAV_ACTION_CALIBRATE_PRESSURE = 20 self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_CALIBRATE_PRESSURE) def reboot_autopilot(self, hold_in_bootloader=False): '''reboot the autopilot''' if self.mavlink10(): if hold_in_bootloader: param1 = 3 else: param1 = 1 self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0, param1, 0, 0, 0, 0, 0, 0) # send an old style reboot immediately afterwards in case it is an older firmware # that doesn't understand the new convention self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0, 1, 0, 0, 0, 0, 0, 0) def wait_gps_fix(self): self.recv_match(type='VFR_HUD', blocking=True) if self.mavlink10(): self.recv_match(type='GPS_RAW_INT', blocking=True, condition='GPS_RAW_INT.fix_type==3 and GPS_RAW_INT.lat != 0 and GPS_RAW_INT.alt != 0') else: self.recv_match(type='GPS_RAW', blocking=True, condition='GPS_RAW.fix_type==2 and GPS_RAW.lat != 0 and GPS_RAW.alt != 0') def location(self, relative_alt=False): '''return current location''' self.wait_gps_fix() # wait for another VFR_HUD, to ensure we have correct altitude self.recv_match(type='VFR_HUD', blocking=True) self.recv_match(type='GLOBAL_POSITION_INT', blocking=True) if relative_alt: alt = self.messages['GLOBAL_POSITION_INT'].relative_alt*0.001 else: alt = self.messages['VFR_HUD'].alt return location(self.messages['GPS_RAW_INT'].lat*1.0e-7, self.messages['GPS_RAW_INT'].lon*1.0e-7, alt, self.messages['VFR_HUD'].heading) def arducopter_arm(self): '''arm motors (arducopter only)''' if self.mavlink10(): self.mav.command_long_send( self.target_system, # target_system self.target_component, mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command 0, # confirmation 1, # param1 (1 to indicate arm) 0, # param2 (all other params meaningless) 0, # param3 0, # param4 0, # param5 0, # param6 0) # param7 def arducopter_disarm(self): '''calibrate pressure''' if self.mavlink10(): self.mav.command_long_send( self.target_system, # target_system self.target_component, mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command 0, # confirmation 0, # param1 (0 to indicate disarm) 0, # param2 (all other params meaningless) 0, # param3 0, # param4 0, # param5 0, # param6 0) # param7 def motors_armed(self): '''return true if motors armed''' if not 'HEARTBEAT' in self.messages: return False m = self.messages['HEARTBEAT'] return (m.base_mode & mavlink.MAV_MODE_FLAG_SAFETY_ARMED) != 0 def motors_armed_wait(self): '''wait for motors to be armed''' while True: m = self.wait_heartbeat() if self.motors_armed(): return def motors_disarmed_wait(self): '''wait for motors to be disarmed''' while True: m = self.wait_heartbeat() if not self.motors_armed(): return def field(self, type, field, default=None): '''convenient function for returning an arbitrary MAVLink field with a default''' if not type in self.messages: return default return getattr(self.messages[type], field, default) def param(self, name, default=None): '''convenient function for returning an arbitrary MAVLink parameter with a default''' if not name in self.params: return default return self.params[name] def set_close_on_exec(fd): '''set the clone on exec flag on a file descriptor. Ignore exceptions''' try: import fcntl flags = fcntl.fcntl(fd, fcntl.F_GETFD) flags |= fcntl.FD_CLOEXEC fcntl.fcntl(fd, fcntl.F_SETFD, flags) except Exception: pass class mavserial(mavfile): '''a serial mavlink port''' def __init__(self, device, baud=115200, autoreconnect=False, source_system=255, use_native=default_native): import serial if ',' in device and not os.path.exists(device): device, baud = device.split(',') self.baud = baud self.device = device self.autoreconnect = autoreconnect # we rather strangely set the baudrate initially to 1200, then change to the desired # baudrate. This works around a kernel bug on some Linux kernels where the baudrate # is not set correctly self.port = serial.Serial(self.device, 1200, timeout=0, dsrdtr=False, rtscts=False, xonxoff=False) try: fd = self.port.fileno() set_close_on_exec(fd) except Exception: fd = None self.set_baudrate(self.baud) mavfile.__init__(self, fd, device, source_system=source_system, use_native=use_native) self.rtscts = False def set_rtscts(self, enable): '''enable/disable RTS/CTS if applicable''' self.port.setRtsCts(enable) self.rtscts = enable def set_baudrate(self, baudrate): '''set baudrate''' try: self.port.setBaudrate(baudrate) except Exception: # for pySerial 3.0, which doesn't have setBaudrate() self.port.baudrate = baudrate def close(self): self.port.close() def recv(self,n=None): if n is None: n = self.mav.bytes_needed() if self.fd is None: waiting = self.port.inWaiting() if waiting < n: n = waiting ret = self.port.read(n) return ret def write(self, buf): try: if not isinstance(buf, str): buf = str(buf) return self.port.write(buf) except Exception: if not self.portdead: print("Device %s is dead" % self.device) self.portdead = True if self.autoreconnect: self.reset() return -1 def reset(self): import serial try: newport = serial.Serial(self.device, self.baud, timeout=0, dsrdtr=False, rtscts=False, xonxoff=False) self.port.close() self.port = newport print("Device %s reopened OK" % self.device) self.portdead = False try: self.fd = self.port.fileno() except Exception: self.fd = None if self.rtscts: self.set_rtscts(self.rtscts) return True except Exception: return False class mavudp(mavfile): '''a UDP mavlink socket''' def __init__(self, device, input=True, broadcast=False, source_system=255, use_native=default_native): a = device.split(':') if len(a) != 2: print("UDP ports must be specified as host:port") sys.exit(1) self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp_server = input self.broadcast = False if input: self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.port.bind((a[0], int(a[1]))) else: self.destination_addr = (a[0], int(a[1])) if broadcast: self.port.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.broadcast = True set_close_on_exec(self.port.fileno()) self.port.setblocking(0) self.last_address = None mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, input=input, use_native=use_native) def close(self): self.port.close() def recv(self,n=None): try: data, new_addr = self.port.recvfrom(UDP_MAX_PACKET_LEN) except socket.error as e: if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK, errno.ECONNREFUSED ]: return "" raise if self.udp_server or self.broadcast: self.last_address = new_addr return data def write(self, buf): try: if self.udp_server: if self.last_address: self.port.sendto(buf, self.last_address) else: if self.last_address and self.broadcast: self.destination_addr = self.last_address self.broadcast = False self.port.connect(self.destination_addr) self.port.sendto(buf, self.destination_addr) except socket.error: pass def recv_msg(self): '''message receive routine for UDP link''' self.pre_message() s = self.recv() if len(s) > 0: if self.first_byte: self.auto_mavlink_version(s) m = self.mav.parse_char(s) if m is not None: self.post_message(m) return m class mavtcp(mavfile): '''a TCP mavlink socket''' def __init__(self, device, source_system=255, retries=3, use_native=default_native): a = device.split(':') if len(a) != 2: print("TCP ports must be specified as host:port") sys.exit(1) self.port = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.destination_addr = (a[0], int(a[1])) while retries >= 0: retries -= 1 if retries <= 0: self.port.connect(self.destination_addr) else: try: self.port.connect(self.destination_addr) break except Exception as e: if retries > 0: print(e, "sleeping") time.sleep(1) continue self.port.setblocking(0) set_close_on_exec(self.port.fileno()) self.port.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) mavfile.__init__(self, self.port.fileno(), "tcp:" + device, source_system=source_system, use_native=use_native) def close(self): self.port.close() def recv(self,n=None): if n is None: n = self.mav.bytes_needed() try: data = self.port.recv(n) except socket.error as e: if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]: return "" raise return data def write(self, buf): try: self.port.send(buf) except socket.error: pass class mavtcpin(mavfile): '''a TCP input mavlink socket''' def __init__(self, device, source_system=255, retries=3, use_native=default_native): a = device.split(':') if len(a) != 2: print("TCP ports must be specified as host:port") sys.exit(1) self.listen = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_addr = (a[0], int(a[1])) self.listen.bind(self.listen_addr) self.listen.listen(1) self.listen.setblocking(0) set_close_on_exec(self.listen.fileno()) self.listen.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) mavfile.__init__(self, self.listen.fileno(), "tcpin:" + device, source_system=source_system, use_native=use_native) self.port = None def close(self): self.listen.close() def recv(self,n=None): if not self.port: try: (self.port, addr) = self.listen.accept() except Exception: return '' self.port.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) self.port.setblocking(0) set_close_on_exec(self.port.fileno()) self.fd = self.port.fileno() if n is None: n = self.mav.bytes_needed() try: data = self.port.recv(n) except socket.error as e: if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]: return "" self.port.close() self.port = None self.fd = self.listen.fileno() return '' return data def write(self, buf): if self.port is None: return try: self.port.send(buf) except socket.error as e: if e.errno in [ errno.EPIPE ]: self.port.close() self.port = None self.fd = self.listen.fileno() pass class mavlogfile(mavfile): '''a MAVLink logfile reader/writer''' def __init__(self, filename, planner_format=None, write=False, append=False, robust_parsing=True, notimestamps=False, source_system=255, use_native=default_native): self.filename = filename self.writeable = write self.robust_parsing = robust_parsing self.planner_format = planner_format self._two64 = math.pow(2.0, 63) mode = 'rb' if self.writeable: if append: mode = 'ab' else: mode = 'wb' self.f = open(filename, mode) self.filesize = os.path.getsize(filename) self.percent = 0 mavfile.__init__(self, None, filename, source_system=source_system, notimestamps=notimestamps, use_native=use_native) if self.notimestamps: self._timestamp = 0 else: self._timestamp = time.time() self.stop_on_EOF = True self._last_message = None self._last_timestamp = None def close(self): self.f.close() def recv(self,n=None): if n is None: n = self.mav.bytes_needed() return self.f.read(n) def write(self, buf): self.f.write(buf) def scan_timestamp(self, tbuf): '''scan forward looking in a tlog for a timestamp in a reasonable range''' while True: (tusec,) = struct.unpack('>Q', tbuf) t = tusec * 1.0e-6 if abs(t - self._last_timestamp) <= 3*24*60*60: break c = self.f.read(1) if len(c) != 1: break tbuf = tbuf[1:] + c return t def pre_message(self): '''read timestamp if needed''' # read the timestamp if self.filesize != 0: self.percent = (100.0 * self.f.tell()) / self.filesize if self.notimestamps: return if self.planner_format: tbuf = self.f.read(21) if len(tbuf) != 21 or tbuf[0] != '-' or tbuf[20] != ':': raise RuntimeError('bad planner timestamp %s' % tbuf) hnsec = self._two64 + float(tbuf[0:20]) t = hnsec * 1.0e-7 # convert to seconds t -= 719163 * 24 * 60 * 60 # convert to 1970 base self._link = 0 else: tbuf = self.f.read(8) if len(tbuf) != 8: return (tusec,) = struct.unpack('>Q', tbuf) t = tusec * 1.0e-6 if (self._last_timestamp is not None and self._last_message.get_type() == "BAD_DATA" and abs(t - self._last_timestamp) > 3*24*60*60): t = self.scan_timestamp(tbuf) self._link = tusec & 0x3 self._timestamp = t def post_message(self, msg): '''add timestamp to message''' # read the timestamp super(mavlogfile, self).post_message(msg) if self.planner_format: self.f.read(1) # trailing newline self.timestamp = msg._timestamp self._last_message = msg if msg.get_type() != "BAD_DATA": self._last_timestamp = msg._timestamp class mavmemlog(mavfile): '''a MAVLink log in memory. This allows loading a log into memory to make it easier to do multiple sweeps over a log''' def __init__(self, mav): mavfile.__init__(self, None, 'memlog') self._msgs = [] self._index = 0 self._count = 0 self.messages = {} while True: m = mav.recv_msg() if m is None: break self._msgs.append(m) self._count = len(self._msgs) def recv_msg(self): '''message receive routine''' if self._index >= self._count: return None m = self._msgs[self._index] self._index += 1 self.percent = (100.0 * self._index) / self._count self.messages[m.get_type()] = m return m def rewind(self): '''rewind to start''' self._index = 0 self.percent = 0 self.messages = {} class mavchildexec(mavfile): '''a MAVLink child processes reader/writer''' def __init__(self, filename, source_system=255, use_native=default_native): from subprocess import Popen, PIPE import fcntl self.filename = filename self.child = Popen(filename, shell=False, stdout=PIPE, stdin=PIPE, bufsize=0) self.fd = self.child.stdout.fileno() fl = fcntl.fcntl(self.fd, fcntl.F_GETFL) fcntl.fcntl(self.fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) fl = fcntl.fcntl(self.child.stdout.fileno(), fcntl.F_GETFL) fcntl.fcntl(self.child.stdout.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK) mavfile.__init__(self, self.fd, filename, source_system=source_system, use_native=use_native) def close(self): self.child.close() def recv(self,n=None): try: x = self.child.stdout.read(1) except Exception: return '' return x def write(self, buf): self.child.stdin.write(buf) def mavlink_connection(device, baud=115200, source_system=255, planner_format=None, write=False, append=False, robust_parsing=True, notimestamps=False, input=True, dialect=None, autoreconnect=False, zero_time_base=False, retries=3, use_native=default_native): '''open a serial, UDP, TCP or file mavlink connection''' global mavfile_global if dialect is not None: set_dialect(dialect) if device.startswith('tcp:'): return mavtcp(device[4:], source_system=source_system, retries=retries, use_native=use_native) if device.startswith('tcpin:'): return mavtcpin(device[6:], source_system=source_system, retries=retries, use_native=use_native) if device.startswith('udpin:'): return mavudp(device[6:], input=True, source_system=source_system, use_native=use_native) if device.startswith('udpout:'): return mavudp(device[7:], input=False, source_system=source_system, use_native=use_native) if device.startswith('udpbcast:'): return mavudp(device[9:], input=False, source_system=source_system, use_native=use_native, broadcast=True) # For legacy purposes we accept the following syntax and let the caller to specify direction if device.startswith('udp:'): return mavudp(device[4:], input=input, source_system=source_system, use_native=use_native) if device.lower().endswith('.bin') or device.lower().endswith('.px4log'): # support dataflash logs from pymavlink import DFReader m = DFReader.DFReader_binary(device, zero_time_base=zero_time_base) mavfile_global = m return m if device.endswith('.log'): # support dataflash text logs from pymavlink import DFReader if DFReader.DFReader_is_text_log(device): m = DFReader.DFReader_text(device, zero_time_base=zero_time_base) mavfile_global = m return m # list of suffixes to prevent setting DOS paths as UDP sockets logsuffixes = ['mavlink', 'log', 'raw', 'tlog' ] suffix = device.split('.')[-1].lower() if device.find(':') != -1 and not suffix in logsuffixes: return mavudp(device, source_system=source_system, input=input, use_native=use_native) if os.path.isfile(device): if device.endswith(".elf") or device.find("/bin/") != -1: print("executing '%s'" % device) return mavchildexec(device, source_system=source_system, use_native=use_native) else: return mavlogfile(device, planner_format=planner_format, write=write, append=append, robust_parsing=robust_parsing, notimestamps=notimestamps, source_system=source_system, use_native=use_native) return mavserial(device, baud=baud, source_system=source_system, autoreconnect=autoreconnect, use_native=use_native) class periodic_event(object): '''a class for fixed frequency events''' def __init__(self, frequency): self.frequency = float(frequency) self.last_time = time.time() def force(self): '''force immediate triggering''' self.last_time = 0 def trigger(self): '''return True if we should trigger now''' tnow = time.time() if tnow < self.last_time: print("Warning, time moved backwards. Restarting timer.") self.last_time = tnow if self.last_time + (1.0/self.frequency) <= tnow: self.last_time = tnow return True return False try: from curses import ascii have_ascii = True except: have_ascii = False def is_printable(c): '''see if a character is printable''' global have_ascii if have_ascii: return ascii.isprint(c) if isinstance(c, int): ic = c else: ic = ord(c) return ic >= 32 and ic <= 126 def all_printable(buf): '''see if a string is all printable''' for c in buf: if not is_printable(c) and not c in ['\r', '\n', '\t']: return False return True class SerialPort(object): '''auto-detected serial port''' def __init__(self, device, description=None, hwid=None): self.device = device self.description = description self.hwid = hwid def __str__(self): ret = self.device if self.description is not None: ret += " : " + self.description if self.hwid is not None: ret += " : " + self.hwid return ret def auto_detect_serial_win32(preferred_list=['*']): '''try to auto-detect serial ports on win32''' try: from serial.tools.list_ports_windows import comports list = sorted(comports()) except: return [] ret = [] others = [] for port, description, hwid in list: matches = False p = SerialPort(port, description=description, hwid=hwid) for preferred in preferred_list: if fnmatch.fnmatch(description, preferred) or fnmatch.fnmatch(hwid, preferred): matches = True if matches: ret.append(p) else: others.append(p) if len(ret) > 0: return ret # now the rest ret.extend(others) return ret def auto_detect_serial_unix(preferred_list=['*']): '''try to auto-detect serial ports on unix''' import glob glist = glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') + glob.glob('/dev/serial/by-id/*') ret = [] others = [] # try preferred ones first for d in glist: matches = False for preferred in preferred_list: if fnmatch.fnmatch(d, preferred): matches = True if matches: ret.append(SerialPort(d)) else: others.append(SerialPort(d)) if len(ret) > 0: return ret ret.extend(others) return ret def auto_detect_serial(preferred_list=['*']): '''try to auto-detect serial port''' # see if if os.name == 'nt': return auto_detect_serial_win32(preferred_list=preferred_list) return auto_detect_serial_unix(preferred_list=preferred_list) def mode_string_v09(msg): '''mode string for 0.9 protocol''' mode = msg.mode nav_mode = msg.nav_mode MAV_MODE_UNINIT = 0 MAV_MODE_MANUAL = 2 MAV_MODE_GUIDED = 3 MAV_MODE_AUTO = 4 MAV_MODE_TEST1 = 5 MAV_MODE_TEST2 = 6 MAV_MODE_TEST3 = 7 MAV_NAV_GROUNDED = 0 MAV_NAV_LIFTOFF = 1 MAV_NAV_HOLD = 2 MAV_NAV_WAYPOINT = 3 MAV_NAV_VECTOR = 4 MAV_NAV_RETURNING = 5 MAV_NAV_LANDING = 6 MAV_NAV_LOST = 7 MAV_NAV_LOITER = 8 cmode = (mode, nav_mode) mapping = { (MAV_MODE_UNINIT, MAV_NAV_GROUNDED) : "INITIALISING", (MAV_MODE_MANUAL, MAV_NAV_VECTOR) : "MANUAL", (MAV_MODE_TEST3, MAV_NAV_VECTOR) : "CIRCLE", (MAV_MODE_GUIDED, MAV_NAV_VECTOR) : "GUIDED", (MAV_MODE_TEST1, MAV_NAV_VECTOR) : "STABILIZE", (MAV_MODE_TEST2, MAV_NAV_LIFTOFF) : "FBWA", (MAV_MODE_AUTO, MAV_NAV_WAYPOINT) : "AUTO", (MAV_MODE_AUTO, MAV_NAV_RETURNING) : "RTL", (MAV_MODE_AUTO, MAV_NAV_LOITER) : "LOITER", (MAV_MODE_AUTO, MAV_NAV_LIFTOFF) : "TAKEOFF", (MAV_MODE_AUTO, MAV_NAV_LANDING) : "LANDING", (MAV_MODE_AUTO, MAV_NAV_HOLD) : "LOITER", (MAV_MODE_GUIDED, MAV_NAV_VECTOR) : "GUIDED", (MAV_MODE_GUIDED, MAV_NAV_WAYPOINT) : "GUIDED", (100, MAV_NAV_VECTOR) : "STABILIZE", (101, MAV_NAV_VECTOR) : "ACRO", (102, MAV_NAV_VECTOR) : "ALT_HOLD", (107, MAV_NAV_VECTOR) : "CIRCLE", (109, MAV_NAV_VECTOR) : "LAND", } if cmode in mapping: return mapping[cmode] return "Mode(%s,%s)" % cmode mode_mapping_apm = { 0 : 'MANUAL', 1 : 'CIRCLE', 2 : 'STABILIZE', 3 : 'TRAINING', 4 : 'ACRO', 5 : 'FBWA', 6 : 'FBWB', 7 : 'CRUISE', 8 : 'AUTOTUNE', 10 : 'AUTO', 11 : 'RTL', 12 : 'LOITER', 14 : 'LAND', 15 : 'GUIDED', 16 : 'INITIALISING', 17 : 'QSTABILIZE', 18 : 'QHOVER', 19 : 'QLOITER', 20 : 'QLAND', } mode_mapping_acm = { 0 : 'STABILIZE', 1 : 'ACRO', 2 : 'ALT_HOLD', 3 : 'AUTO', 4 : 'GUIDED', 5 : 'LOITER', 6 : 'RTL', 7 : 'CIRCLE', 8 : 'POSITION', 9 : 'LAND', 10 : 'OF_LOITER', 11 : 'DRIFT', 13 : 'SPORT', 14 : 'FLIP', 15 : 'AUTOTUNE', 16 : 'POSHOLD' } mode_mapping_rover = { 0 : 'MANUAL', 2 : 'LEARNING', 3 : 'STEERING', 4 : 'HOLD', 10 : 'AUTO', 11 : 'RTL', 15 : 'GUIDED', 16 : 'INITIALISING' } mode_mapping_tracker = { 0 : 'MANUAL', 1 : 'STOP', 2 : 'SCAN', 10 : 'AUTO', 16 : 'INITIALISING' } mode_mapping_px4 = { 0 : 'MANUAL', 1 : 'ATTITUDE', 2 : 'EASY', 3 : 'AUTO' } def mode_mapping_byname(mav_type): '''return dictionary mapping mode names to numbers, or None if unknown''' map = None if mav_type in [mavlink.MAV_TYPE_QUADROTOR, mavlink.MAV_TYPE_HELICOPTER, mavlink.MAV_TYPE_HEXAROTOR, mavlink.MAV_TYPE_OCTOROTOR, mavlink.MAV_TYPE_TRICOPTER]: map = mode_mapping_acm if mav_type == mavlink.MAV_TYPE_FIXED_WING: map = mode_mapping_apm if mav_type == mavlink.MAV_TYPE_GROUND_ROVER: map = mode_mapping_rover if mav_type == mavlink.MAV_TYPE_ANTENNA_TRACKER: map = mode_mapping_tracker if map is None: return None inv_map = dict((a, b) for (b, a) in map.items()) return inv_map def mode_mapping_bynumber(mav_type): '''return dictionary mapping mode numbers to name, or None if unknown''' map = None if mav_type in [mavlink.MAV_TYPE_QUADROTOR, mavlink.MAV_TYPE_HELICOPTER, mavlink.MAV_TYPE_HEXAROTOR, mavlink.MAV_TYPE_OCTOROTOR, mavlink.MAV_TYPE_TRICOPTER]: map = mode_mapping_acm if mav_type == mavlink.MAV_TYPE_FIXED_WING: map = mode_mapping_apm if mav_type == mavlink.MAV_TYPE_GROUND_ROVER: map = mode_mapping_rover if mav_type == mavlink.MAV_TYPE_ANTENNA_TRACKER: map = mode_mapping_tracker if map is None: return None return map def mode_string_v10(msg): '''mode string for 1.0 protocol, from heartbeat''' if not msg.base_mode & mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED: return "Mode(0x%08x)" % msg.base_mode if msg.type in [ mavlink.MAV_TYPE_QUADROTOR, mavlink.MAV_TYPE_HEXAROTOR, mavlink.MAV_TYPE_OCTOROTOR, mavlink.MAV_TYPE_TRICOPTER, mavlink.MAV_TYPE_COAXIAL, mavlink.MAV_TYPE_HELICOPTER ]: if msg.custom_mode in mode_mapping_acm: return mode_mapping_acm[msg.custom_mode] if msg.type == mavlink.MAV_TYPE_FIXED_WING: if msg.custom_mode in mode_mapping_apm: return mode_mapping_apm[msg.custom_mode] if msg.type == mavlink.MAV_TYPE_GROUND_ROVER: if msg.custom_mode in mode_mapping_rover: return mode_mapping_rover[msg.custom_mode] if msg.type == mavlink.MAV_TYPE_ANTENNA_TRACKER: if msg.custom_mode in mode_mapping_tracker: return mode_mapping_tracker[msg.custom_mode] return "Mode(%u)" % msg.custom_mode def mode_string_apm(mode_number): '''return mode string for APM:Plane''' if mode_number in mode_mapping_apm: return mode_mapping_apm[mode_number] return "Mode(%u)" % mode_number def mode_string_acm(mode_number): '''return mode string for APM:Copter''' if mode_number in mode_mapping_acm: return mode_mapping_acm[mode_number] return "Mode(%u)" % mode_number def mode_string_px4(mode_number): '''return mode string for PX4 flight stack''' if mode_number in mode_mapping_px4: return mode_mapping_px4[mode_number] return "Mode(%u)" % mode_number class x25crc(object): '''x25 CRC - based on checksum.h from mavlink library''' def __init__(self, buf=''): self.crc = 0xffff self.accumulate(buf) def accumulate(self, buf): '''add in some more bytes''' bytes = array.array('B') if isinstance(buf, array.array): bytes.extend(buf) else: bytes.fromstring(buf) accum = self.crc for b in bytes: tmp = b ^ (accum & 0xff) tmp = (tmp ^ (tmp<<4)) & 0xFF accum = (accum>>8) ^ (tmp<<8) ^ (tmp<<3) ^ (tmp>>4) accum = accum & 0xFFFF self.crc = accum class MavlinkSerialPort(): '''an object that looks like a serial port, but transmits using mavlink SERIAL_CONTROL packets''' def __init__(self, portname, baudrate, devnum=0, devbaud=0, timeout=3, debug=0): from . import mavutil self.baudrate = 0 self.timeout = timeout self._debug = debug self.buf = '' self.port = devnum self.debug("Connecting with MAVLink to %s ..." % portname) self.mav = mavutil.mavlink_connection(portname, autoreconnect=True, baud=baudrate) self.mav.wait_heartbeat() self.debug("HEARTBEAT OK\n") if devbaud != 0: self.setBaudrate(devbaud) self.debug("Locked serial device\n") def debug(self, s, level=1): '''write some debug text''' if self._debug >= level: print(s) def write(self, b): '''write some bytes''' from . import mavutil self.debug("sending '%s' (0x%02x) of len %u\n" % (b, ord(b[0]), len(b)), 2) while len(b) > 0: n = len(b) if n > 70: n = 70 buf = [ord(x) for x in b[:n]] buf.extend([0]*(70-len(buf))) self.mav.mav.serial_control_send(self.port, mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE | mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND, 0, 0, n, buf) b = b[n:] def _recv(self): '''read some bytes into self.buf''' from . import mavutil start_time = time.time() while time.time() < start_time + self.timeout: m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0', type='SERIAL_CONTROL', blocking=False, timeout=0) if m is not None and m.count != 0: break self.mav.mav.serial_control_send(self.port, mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE | mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND, 0, 0, 0, [0]*70) m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0', type='SERIAL_CONTROL', blocking=True, timeout=0.01) if m is not None and m.count != 0: break if m is not None: if self._debug > 2: print(m) data = m.data[:m.count] self.buf += ''.join(str(chr(x)) for x in data) def read(self, n): '''read some bytes''' if len(self.buf) == 0: self._recv() if len(self.buf) > 0: if n > len(self.buf): n = len(self.buf) ret = self.buf[:n] self.buf = self.buf[n:] if self._debug >= 2: for b in ret: self.debug("read 0x%x" % ord(b), 2) return ret return '' def flushInput(self): '''flush any pending input''' self.buf = '' saved_timeout = self.timeout self.timeout = 0.5 self._recv() self.timeout = saved_timeout self.buf = '' self.debug("flushInput") def setBaudrate(self, baudrate): '''set baudrate''' from . import mavutil if self.baudrate == baudrate: return self.baudrate = baudrate self.mav.mav.serial_control_send(self.port, mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE, 0, self.baudrate, 0, [0]*70) self.flushInput() self.debug("Changed baudrate %u" % self.baudrate) if __name__ == '__main__': serial_list = auto_detect_serial(preferred_list=['*FTDI*',"*Arduino_Mega_2560*", "*3D_Robotics*", "*USB_to_UART*", '*PX4*', '*FMU*']) for port in serial_list: print("%s" % port)
lgpl-3.0
-1,812,975,357,580,576,300
36.078456
142
0.536878
false
bgalehouse/grr
client/client_utils_linux.py
9
7736
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- # Copyright 2011 Google Inc. All Rights Reserved. """Linux specific utils.""" import locale import os import subprocess import sys import threading import time from google.protobuf import message import logging from grr.lib import config_lib from grr.lib import rdfvalue from grr.lib import utils # TODO(user): Find a reliable way to do this for Linux. def LinFindProxies(): return [] MOUNTPOINT_CACHE = [0, None] def GetMountpoints(data=None): """List all the filesystems mounted on the system.""" expiry = 60 # 1 min insert_time = MOUNTPOINT_CACHE[0] if insert_time + expiry > time.time(): return MOUNTPOINT_CACHE[1] devices = {} # Check all the mounted filesystems. if data is None: data = "\n".join([open(x).read() for x in ["/proc/mounts", "/etc/mtab"]]) for line in data.splitlines(): try: device, mnt_point, fs_type, _ = line.split(" ", 3) mnt_point = os.path.normpath(mnt_point) # What if several devices are mounted on the same mount point? devices[mnt_point] = (device, fs_type) except ValueError: pass MOUNTPOINT_CACHE[0] = time.time() MOUNTPOINT_CACHE[1] = devices return devices def LinGetRawDevice(path): """Resolve the raw device that contains the path.""" device_map = GetMountpoints() path = utils.SmartUnicode(path) mount_point = path = utils.NormalizePath(path, "/") result = rdfvalue.PathSpec(pathtype=rdfvalue.PathSpec.PathType.OS) # Assign the most specific mount point to the result while mount_point: try: result.path, fs_type = device_map[mount_point] if fs_type in ["ext2", "ext3", "ext4", "vfat", "ntfs"]: # These are read filesystems result.pathtype = rdfvalue.PathSpec.PathType.OS else: result.pathtype = rdfvalue.PathSpec.PathType.UNSET # Drop the mount point path = utils.NormalizePath(path[len(mount_point):]) result.mount_point = mount_point return result, path except KeyError: mount_point = os.path.dirname(mount_point) def CanonicalPathToLocalPath(path): """Linux uses a normal path. If sys.getfilesystemencoding() returns None normally any call to a system function will try to encode the string to ASCII. A modern version of Linux will use UTF-8 as (narrow) string encoding. locale.getpreferredencoding() seems to return ASCII at this point. So for older versions of Linux we'll need to rely on locale.getdefaultlocale()[1]. If everything fails we fallback to UTF-8. Args: path: the canonical path as an Unicode string Returns: a unicode string or an encoded (narrow) string dependent on system settings """ canonical_path = utils.NormalizePath(path) if sys.getfilesystemencoding(): return canonical_path encoding = locale.getdefaultlocale()[1] or "UTF-8" return canonical_path.encode(encoding) def LocalPathToCanonicalPath(path): """Linux uses a normal path.""" return utils.NormalizePath(path) class NannyThread(threading.Thread): """This is the thread which watches the nanny running.""" def __init__(self, unresponsive_kill_period): """Constructor. Args: unresponsive_kill_period: The time in seconds which we wait for a heartbeat. """ super(NannyThread, self).__init__(name="Nanny") self.last_heart_beat_time = time.time() self.unresponsive_kill_period = unresponsive_kill_period self.running = True self.daemon = True def run(self): self.WriteNannyStatus("Nanny starting.") while self.running: now = time.time() # When should we check the next heartbeat? check_time = self.last_heart_beat_time + self.unresponsive_kill_period # Missed the deadline, we need to die. if check_time < now: msg = "Suicide by nanny thread." logging.error(msg) self.WriteNannyStatus(msg) # Die hard here to prevent hangs due to non daemonized threads. os._exit(-1) # pylint: disable=protected-access else: # Sleep until the next heartbeat is due. time.sleep(check_time - now) def Stop(self): """Exits the main thread.""" self.running = False self.WriteNannyStatus("Nanny stopping.") def Heartbeat(self): self.last_heart_beat_time = time.time() def WriteNannyStatus(self, status): try: with open(config_lib.CONFIG["Nanny.statusfile"], "w") as fd: fd.write(status) except (IOError, OSError): pass class NannyController(object): """Controls communication with the nanny.""" # Nanny should be a global singleton thread. nanny = None max_log_size = 100000000 def StartNanny(self, unresponsive_kill_period=None, nanny_logfile=None): # The nanny thread is a singleton. if NannyController.nanny is None: if unresponsive_kill_period is None: unresponsive_kill_period = config_lib.CONFIG[ "Nanny.unresponsive_kill_period"] NannyController.nanny_logfile = (nanny_logfile or config_lib.CONFIG["Nanny.logfile"]) NannyController.nanny = NannyThread(unresponsive_kill_period) NannyController.nanny.start() def StopNanny(self): if NannyController.nanny: NannyController.nanny.Stop() NannyController.nanny = None def Heartbeat(self): """Notifies the nanny of a heartbeat.""" if self.nanny: self.nanny.Heartbeat() def WriteTransactionLog(self, grr_message): """Write the message into the transaction log.""" try: grr_message = grr_message.SerializeToString() except AttributeError: grr_message = str(grr_message) try: with open(self.nanny_logfile, "w") as fd: fd.write(grr_message) except (IOError, OSError): pass def SyncTransactionLog(self): # Not implemented on Linux. pass def CleanTransactionLog(self): """Wipes the transaction log.""" try: with open(self.nanny_logfile, "w") as fd: fd.write("") except (IOError, OSError): pass def GetTransactionLog(self): """Return a GrrMessage instance from the transaction log or None.""" try: with open(self.nanny_logfile, "r") as fd: data = fd.read(self.max_log_size) except (IOError, OSError): return try: if data: return rdfvalue.GrrMessage(data) except (message.Error, rdfvalue.Error): return def GetNannyMessage(self): # Not implemented on Linux. return None def ClearNannyMessage(self): # Not implemented on Linux. pass def GetNannyStatus(self): try: with open(config_lib.CONFIG["Nanny.statusfile"], "r") as fd: return fd.read(self.max_log_size) except (IOError, OSError): return None def InstallDriver(driver_path): """Loads a driver and starts it.""" cmd = ["/sbin/insmod", driver_path] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() exit_status = p.returncode logging.info("Loading driver finished, status: %d.", exit_status) if exit_status != 0: raise OSError("Failed to load driver, may already be installed.") def UninstallDriver(driver_name): """Unloads the driver. Args: driver_name: Name of the driver. Raises: OSError: On failure to uninstall. """ cmd = ["/sbin/rmmod", driver_name] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() exit_status = p.returncode logging.info("Unloading driver finished, status: %d.", exit_status) if exit_status != 0: raise OSError("Failed to unload driver.") def KeepAlive(): # Not yet supported for Linux. pass
apache-2.0
7,020,517,690,146,524,000
25.675862
77
0.670889
false
MarsRobotics/Experiments
UI/RobotData.py
1
3418
__author__ = 'Matt' class RobotData: def __init__(self): self.frontLeftWheel = wheel(0, 0.5, 0) self.frontRightWheel = wheel(0, 0.5, 0) self.midLeftWheel = wheel(0, 0.5, 0) self.midRightWheel = wheel(0, 0.5, 0) self.rearLeftWheel = wheel(0, 0.5, 0) self.rearRightWheel = wheel(0, 0.5, 0) self.leftArm = rockerBogieArm(0, 0) self.rightArm = rockerBogieArm(0, 0) self.currentLocation = location(0, 0, 0) ## # This class defines the position of an individual wheel on the transport. The # # Variables: # - theta: the radian rotation of wheels relative to body. 0 is forward for the robot. # - speed: the speed the wheels are being told to drive at (TODO: speed/time) # - current: the current draw of the wheel motors (TODO: units) # ## class wheel: MAX_CURRENT = 5 def __init__(self, theta, speed, current): self.theta = theta # Speed wheels are being told to drive self.speed = speed self.current = current ## # # Variables: # - rockerTheta: the rotation of the rocker. (TODO: what does this mean) # - bogeTheta: the rotation of the boge. (also... # class rockerBogieArm: def __init__(self, rockerTheta, bogieTheta): self.rockerTheta = rockerTheta self.bogieTheta = bogieTheta return ## # This class is for holding all the data that will be sent to the robot and consists of one discrete command # # Variables: # - xx_articulation_angle # The angle of each articulation joint, in degrees. 0 is 0 on the unit circle # - xx_drive_speed # the speed we need to drive each of the motors at (UNDEFINED) TODO: Define units # - drive_duration: How long, in seconds, that we drive the motors ## class ManualControlData: def __init__(self): self.fl_articulation_angle = 0 self.fr_articulation_angle = 180 self.ml_articulation_angle = 0 self.mr_articulation_angle = 180 self.rl_articulation_angle = 0 self.rr_articulation_angle = 180 self.fl_drive_speed = 0 self.fr_drive_speed = 0 self.ml_drive_speed = 0 self.mr_drive_speed = 0 self.rl_drive_speed = 0 self.rr_drive_speed = 0 self.drive_duration = 0 self.e_stop = False return ## # This class defines the position of the robot. The arena is 3.78m by 7.38m. the expanded # robot is 1.2x1.5 # # 3.78 meters (x) pi / 2 rads # +-----+-----+ | # | | | N # | | | pi rads - W + E - 0 rads # | | | S # | | | | # | | | 3 pi / 2 rads # | | | # | | | 7.38 meters (y) # +-----+-----+ # (0,0) # # The origin is located at the exact center of the arena. Relative north is # facing the end of the arena (as shown above). # # Variables: # x - denotes the x position of the center of the robot (meters). -1.89 <= x <= +1.89 # y - denotes the y position of the center of the robot (meters). 0 <= y <= 7.38 # theta - the number of radians turned from E(ast); as the unit circle # # TODO: use verification to make sure that the robot does not hit the edges/go outside the arena. # TODO: functions about travel. ## class location: def __init__(self, x, y, theta): self.x = x self.y = y self.theta = theta
bsd-3-clause
-8,114,020,577,965,434,000
26.572581
108
0.588941
false
Vagab0nd/SiCKRAGE
lib3/guessit/rules/common/formatters.py
5
3637
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Formatters """ from rebulk.formatters import formatters from rebulk.remodule import re from . import seps _excluded_clean_chars = ',:;-/\\' clean_chars = "" for sep in seps: if sep not in _excluded_clean_chars: clean_chars += sep def _potential_before(i, input_string): """ Check if the character at position i can be a potential single char separator considering what's before it. :param i: :type i: int :param input_string: :type input_string: str :return: :rtype: bool """ return i - 1 >= 0 and input_string[i] in seps and input_string[i - 2] in seps and input_string[i - 1] not in seps def _potential_after(i, input_string): """ Check if the character at position i can be a potential single char separator considering what's after it. :param i: :type i: int :param input_string: :type input_string: str :return: :rtype: bool """ return i + 2 >= len(input_string) or \ input_string[i + 2] == input_string[i] and input_string[i + 1] not in seps def cleanup(input_string): """ Removes and strip separators from input_string (but keep ',;' characters) It also keep separators for single characters (Mavels Agents of S.H.I.E.L.D.) :param input_string: :type input_string: str :return: :rtype: """ clean_string = input_string for char in clean_chars: clean_string = clean_string.replace(char, ' ') # Restore input separator if they separate single characters. # Useful for Mavels Agents of S.H.I.E.L.D. # https://github.com/guessit-io/guessit/issues/278 indices = [i for i, letter in enumerate(clean_string) if letter in seps] dots = set() if indices: clean_list = list(clean_string) potential_indices = [] for i in indices: if _potential_before(i, input_string) and _potential_after(i, input_string): potential_indices.append(i) replace_indices = [] for potential_index in potential_indices: if potential_index - 2 in potential_indices or potential_index + 2 in potential_indices: replace_indices.append(potential_index) if replace_indices: for replace_index in replace_indices: dots.add(input_string[replace_index]) clean_list[replace_index] = input_string[replace_index] clean_string = ''.join(clean_list) clean_string = strip(clean_string, ''.join([c for c in seps if c not in dots])) clean_string = re.sub(' +', ' ', clean_string) return clean_string def strip(input_string, chars=seps): """ Strip separators from input_string :param input_string: :param chars: :type input_string: :return: :rtype: """ return input_string.strip(chars) def raw_cleanup(raw): """ Cleanup a raw value to perform raw comparison :param raw: :type raw: :return: :rtype: """ return formatters(cleanup, strip)(raw.lower()) def reorder_title(title, articles=('the',), separators=(',', ', ')): """ Reorder the title :param title: :type title: :param articles: :type articles: :param separators: :type separators: :return: :rtype: """ ltitle = title.lower() for article in articles: for separator in separators: suffix = separator + article if ltitle[-len(suffix):] == suffix: return title[-len(suffix) + len(separator):] + ' ' + title[:-len(suffix)] return title
gpl-3.0
-3,686,810,875,147,249,000
25.742647
117
0.613968
false
VaysseB/PySimpleMazeGenerator
maze/ortho/ortho_maze.py
1
1613
# -*- coding: utf-8 -*- import numpy as np from .ortho_point import OrthoPoint from .ortho_maze_cell import OrthoMazeCellStatus, OrthoMazeCell __all__ = ("OrthoMaze",) class OrthoMaze: """A simplified class builder for orthogonal based maze.""" def __init__(self, width, height): """Build an empty maze.""" self.resize(width + 1, height + 1) def resize(self, width, height): """Resize the maze to the new coordinates.""" self.width = width self.height = height self.matrix = self.createMatrix(width, height) def clear(self): """Clear all cells with the initial state.""" self.matrix.fill(OrthoMazeCellStatus.states.NorthWall | OrthoMazeCellStatus.states.EastWall) @staticmethod def createMatrix(width, height): """Create an empty matrix with the given parameters.""" mx = np.matrix([[0]], dtype=OrthoMazeCellStatus.__numpy_type__).copy() mx.resize((width, height)) return mx #-------------------------------------- # User cells interactions def cell(self, pos): """Return the cell at the position.""" return OrthoMazeCell(pos, self) #-------------------------------------- # Cells interactions def get_cell_value(self, pos): """Return the cell at the position.""" pos = OrthoPoint(pos) value = self.matrix[pos.x, pos.y] return value def set_cell_value(self, pos, value): """Change the value at the position.""" pos = OrthoPoint(pos) self.matrix[pos.x, pos.y] = int(value)
mit
1,127,908,839,063,675,100
28.888889
78
0.584005
false
MusculoskeletalAtlasProject/mapclient
src/mapclient/view/managers/plugins/ui/ui_pluginmanagerdialog.py
2
5644
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'qt/pluginmanagerdialog.ui' # # Created: Wed Jan 28 16:54:28 2015 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_PluginManagerDialog(object): def setupUi(self, PluginManagerDialog): PluginManagerDialog.setObjectName("PluginManagerDialog") PluginManagerDialog.resize(567, 496) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/mapclient/images/icon-app.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) PluginManagerDialog.setWindowIcon(icon) self.verticalLayout = QtGui.QVBoxLayout(PluginManagerDialog) self.verticalLayout.setObjectName("verticalLayout") self.groupBox = QtGui.QGroupBox(PluginManagerDialog) self.groupBox.setAlignment(QtCore.Qt.AlignCenter) self.groupBox.setFlat(False) self.groupBox.setObjectName("groupBox") self.verticalLayout_4 = QtGui.QVBoxLayout(self.groupBox) self.verticalLayout_4.setObjectName("verticalLayout_4") self.label = QtGui.QLabel(self.groupBox) self.label.setObjectName("label") self.verticalLayout_4.addWidget(self.label) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.verticalLayout_3 = QtGui.QVBoxLayout() self.verticalLayout_3.setObjectName("verticalLayout_3") self.directoryListing = QtGui.QListWidget(self.groupBox) self.directoryListing.setObjectName("directoryListing") self.verticalLayout_3.addWidget(self.directoryListing) self.defaultPluginCheckBox = QtGui.QCheckBox(self.groupBox) self.defaultPluginCheckBox.setChecked(True) self.defaultPluginCheckBox.setObjectName("defaultPluginCheckBox") self.verticalLayout_3.addWidget(self.defaultPluginCheckBox) self.horizontalLayout.addLayout(self.verticalLayout_3) self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.addButton = QtGui.QPushButton(self.groupBox) self.addButton.setObjectName("addButton") self.verticalLayout_2.addWidget(self.addButton) self.removeButton = QtGui.QPushButton(self.groupBox) self.removeButton.setObjectName("removeButton") self.verticalLayout_2.addWidget(self.removeButton) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem) self.reloadButton = QtGui.QPushButton(self.groupBox) self.reloadButton.setObjectName("reloadButton") self.verticalLayout_2.addWidget(self.reloadButton) self.horizontalLayout.addLayout(self.verticalLayout_2) self.verticalLayout_4.addLayout(self.horizontalLayout) self.verticalLayout.addWidget(self.groupBox) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.advancedButton = QtGui.QPushButton(PluginManagerDialog) self.advancedButton.setMinimumSize(QtCore.QSize(90, 0)) self.advancedButton.setObjectName("advancedButton") self.horizontalLayout_2.addWidget(self.advancedButton) spacerItem1 = QtGui.QSpacerItem(80, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem1) self.buttonBox = QtGui.QDialogButtonBox(PluginManagerDialog) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.horizontalLayout_2.addWidget(self.buttonBox) self.verticalLayout.addLayout(self.horizontalLayout_2) self.retranslateUi(PluginManagerDialog) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), PluginManagerDialog.accept) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), PluginManagerDialog.reject) QtCore.QMetaObject.connectSlotsByName(PluginManagerDialog) def retranslateUi(self, PluginManagerDialog): PluginManagerDialog.setWindowTitle(QtGui.QApplication.translate("PluginManagerDialog", "Plugin Manager", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox.setTitle(QtGui.QApplication.translate("PluginManagerDialog", "Plugin Manager", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("PluginManagerDialog", "Plugin directories:", None, QtGui.QApplication.UnicodeUTF8)) self.defaultPluginCheckBox.setText(QtGui.QApplication.translate("PluginManagerDialog", "Use default plugin directory", None, QtGui.QApplication.UnicodeUTF8)) self.addButton.setText(QtGui.QApplication.translate("PluginManagerDialog", "Add Directory", None, QtGui.QApplication.UnicodeUTF8)) self.removeButton.setText(QtGui.QApplication.translate("PluginManagerDialog", "Remove Directory", None, QtGui.QApplication.UnicodeUTF8)) self.reloadButton.setToolTip(QtGui.QApplication.translate("PluginManagerDialog", "Reload the plugins from the current plugin directories", None, QtGui.QApplication.UnicodeUTF8)) self.reloadButton.setText(QtGui.QApplication.translate("PluginManagerDialog", "Reload", None, QtGui.QApplication.UnicodeUTF8)) self.advancedButton.setText(QtGui.QApplication.translate("PluginManagerDialog", "Advanced...", None, QtGui.QApplication.UnicodeUTF8))
gpl-3.0
4,194,251,262,441,179,600
63.136364
185
0.750354
false
bootphon/zerospeech2017
track2/baseline/baseline_mandarin/scripts/build_graph.py
6
3446
#!/usr/bin/python # # Copyright 2011-2012 Johns Hopkins University (Author: Aren Jansen) # from __future__ import division import sys import os import re import string from optparse import OptionParser parser = OptionParser() parser.add_option("--input", help="matches input file", dest="infile") parser.add_option("--probthr", help="match probability threshold", dest="probthr", default="0.5") parser.add_option("--olapthr", help="overlap threshold", dest="olapthr", default="0.95") parser.add_option("--output", help="graph output base", dest="outfile") parser.add_option("--list", help="file basename list", dest="filelist", default="") (options, args) = parser.parse_args() inFilename = options.infile outFilebase = options.outfile probthr = float(options.probthr) olapthr = float(options.olapthr) filelist = options.filelist vout = open(outFilebase + ".nodes","w") eout = open(outFilebase + ".edges","w") print "Building the file set" if len(filelist) == 0: fileset = set() for line in open(inFilename): if len(line.strip().split()) == 2: [f1,f2] = line.strip().split() fileset.add(f1); fileset.add(f2); fileset = list(fileset) fileset.sort() else: fileset = [] for line in open(filelist): f1 = line.strip().split() fileset.append(f1[0]); fileset.sort() fileind = {} for f in fileset: ind = fileset.index(f) fileind[f] = ind+1 vcount = 0; ecount = 0; print "Generating Nodes and Type 1 Edges" savefAB = [] cnt = 0 for line in open(inFilename): if len(line.strip().split()) == 2: [f1,f2] = line.strip().split() continue [xA,xB,yA,yB,prob,rho] = line.strip().split() if float(prob) < probthr: continue # if float(prob) > 0.95: # continue i1 = fileind[f1] i2 = fileind[f2] if int(xB) > int(xA): vcount = vcount + 1 vout.write(f1+"\t"+xA+"\t"+xB+"\t"+prob+"\t"+rho+"\t"+str(i1)+"\n") savefAB.append((vcount,f1,int(xA),int(xB))) if int(yB) > int(yA): vcount = vcount + 1 vout.write(f2+"\t"+yA+"\t"+yB+"\t"+prob+"\t"+rho+"\t"+str(i2)+"\n") savefAB.append((vcount,f2,int(yA),int(yB))) ecount = ecount + 1 eout.write(str(vcount-1)+"\t"+str(vcount)+"\t"+str(int(float(prob)*1000))+"\n") cnt += 1 if cnt % 100000 == 0: print "Finished ingesting",cnt print "Original Nodes: ", vcount print "Original Edges: ", ecount # Add overlap edges print "Adding Overlap Edges" savefAB.sort(key=lambda x: (x[1],x[2])) pos1 = 1 while pos1 < len(savefAB): pos2 = pos1 + 1 while pos2 < len(savefAB) and savefAB[pos2][1] == savefAB[pos1][1]: pos2 = pos2 + 1 print "Processing",str(pos1)+":"+str(pos2),"of",len(savefAB) for n in range(pos1,pos2-1): for m in range(n+1,pos2-1): if savefAB[m][2] > savefAB[n][3]: break num = savefAB[n][3]-savefAB[n][2] + savefAB[m][3]-savefAB[m][2] den = max(savefAB[n][3],savefAB[m][3]) - min(savefAB[n][2],savefAB[m][2]) olap = max(0,num/den-1) if olap >= olapthr: ecount = ecount + 1 eout.write(str(savefAB[n][0])+"\t"+str(savefAB[m][0])+"\t"+str(int(float(olap)*1000))+"\n") #print savefAB[n], savefAB[m],olap pos1 = pos2 print "Total Edges: ", ecount vout.close() eout.close()
gpl-3.0
6,627,459,577,708,773,000
25.305344
108
0.584736
false
anryko/ansible
lib/ansible/modules/cloud/google/gcp_kms_crypto_key.py
13
14214
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_kms_crypto_key description: - A `CryptoKey` represents a logical key that can be used for cryptographic operations. short_description: Creates a GCP CryptoKey version_added: '2.9' author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: state: description: - Whether the given object should exist in GCP choices: - present - absent default: present type: str name: description: - The resource name for the CryptoKey. required: true type: str labels: description: - Labels with user-defined metadata to apply to this resource. required: false type: dict purpose: description: - Immutable purpose of CryptoKey. See U(https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys#CryptoKeyPurpose) for inputs. - 'Some valid choices include: "ENCRYPT_DECRYPT", "ASYMMETRIC_SIGN", "ASYMMETRIC_DECRYPT"' required: false default: ENCRYPT_DECRYPT type: str rotation_period: description: - Every time this period passes, generate a new CryptoKeyVersion and set it as the primary. - The first rotation will take place after the specified period. The rotation period has the format of a decimal number with up to 9 fractional digits, followed by the letter `s` (seconds). It must be greater than a day (ie, 86400). required: false type: str version_template: description: - A template describing settings for new crypto key versions. required: false type: dict suboptions: algorithm: description: - The algorithm to use when creating a version based on this template. - See the [algorithm reference](U(https://cloud.google.com/kms/docs/reference/rest/v1/CryptoKeyVersionAlgorithm)) for possible inputs. required: true type: str protection_level: description: - The protection level to use when creating a version based on this template. - 'Some valid choices include: "SOFTWARE", "HSM"' required: false type: str key_ring: description: - The KeyRing that this key belongs to. - 'Format: `''projects/{{project}}/locations/{{location}}/keyRings/{{keyRing}}''`.' required: true type: str project: description: - The Google Cloud Platform project to use. type: str auth_kind: description: - The type of credential used. type: str required: true choices: - application - machineaccount - serviceaccount service_account_contents: description: - The contents of a Service Account JSON file, either in a dictionary or as a JSON string that represents it. type: jsonarg service_account_file: description: - The path of a Service Account JSON file if serviceaccount is selected as type. type: path service_account_email: description: - An optional service account email address if machineaccount is selected and the user does not wish to use the default email. type: str scopes: description: - Array of scopes to be used type: list env_type: description: - Specifies which Ansible environment you're running this module within. - This should not be set unless you know what you're doing. - This only alters the User Agent string for any API requests. type: str notes: - 'API Reference: U(https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys)' - 'Creating a key: U(https://cloud.google.com/kms/docs/creating-keys#create_a_key)' - for authentication, you can set service_account_file using the C(gcp_service_account_file) env variable. - for authentication, you can set service_account_contents using the C(GCP_SERVICE_ACCOUNT_CONTENTS) env variable. - For authentication, you can set service_account_email using the C(GCP_SERVICE_ACCOUNT_EMAIL) env variable. - For authentication, you can set auth_kind using the C(GCP_AUTH_KIND) env variable. - For authentication, you can set scopes using the C(GCP_SCOPES) env variable. - Environment variables values will only be used if the playbook values are not set. - The I(service_account_email) and I(service_account_file) options are mutually exclusive. ''' EXAMPLES = ''' - name: create a key ring gcp_kms_key_ring: name: key-key-ring location: us-central1 project: "{{ gcp_project }}" auth_kind: "{{ gcp_cred_kind }}" service_account_file: "{{ gcp_cred_file }}" state: present register: keyring - name: create a crypto key gcp_kms_crypto_key: name: test_object key_ring: projects/{{ gcp_project }}/locations/us-central1/keyRings/key-key-ring project: test_project auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" state: present ''' RETURN = ''' name: description: - The resource name for the CryptoKey. returned: success type: str creationTime: description: - The time that this resource was created on the server. - This is in RFC3339 text format. returned: success type: str labels: description: - Labels with user-defined metadata to apply to this resource. returned: success type: dict purpose: description: - Immutable purpose of CryptoKey. See U(https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys#CryptoKeyPurpose) for inputs. returned: success type: str rotationPeriod: description: - Every time this period passes, generate a new CryptoKeyVersion and set it as the primary. - The first rotation will take place after the specified period. The rotation period has the format of a decimal number with up to 9 fractional digits, followed by the letter `s` (seconds). It must be greater than a day (ie, 86400). returned: success type: str versionTemplate: description: - A template describing settings for new crypto key versions. returned: success type: complex contains: algorithm: description: - The algorithm to use when creating a version based on this template. - See the [algorithm reference](U(https://cloud.google.com/kms/docs/reference/rest/v1/CryptoKeyVersionAlgorithm)) for possible inputs. returned: success type: str protectionLevel: description: - The protection level to use when creating a version based on this template. returned: success type: str keyRing: description: - The KeyRing that this key belongs to. - 'Format: `''projects/{{project}}/locations/{{location}}/keyRings/{{keyRing}}''`.' returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, remove_nones_from_dict, replace_resource_dict import json ################################################################################ # Main ################################################################################ def main(): """Main function""" module = GcpModule( argument_spec=dict( state=dict(default='present', choices=['present', 'absent'], type='str'), name=dict(required=True, type='str'), labels=dict(type='dict'), purpose=dict(default='ENCRYPT_DECRYPT', type='str'), rotation_period=dict(type='str'), version_template=dict(type='dict', options=dict(algorithm=dict(required=True, type='str'), protection_level=dict(type='str'))), key_ring=dict(required=True, type='str'), ) ) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/cloudkms'] state = module.params['state'] fetch = fetch_resource(module, self_link(module)) changed = False if fetch: if state == 'present': if is_different(module, fetch): update(module, self_link(module), fetch) fetch = fetch_resource(module, self_link(module)) changed = True else: delete(module, self_link(module)) fetch = {} changed = True else: if state == 'present': fetch = create(module, create_link(module)) changed = True else: fetch = {} fetch.update({'changed': changed}) module.exit_json(**fetch) def create(module, link): auth = GcpSession(module, 'kms') return return_if_object(module, auth.post(link, resource_to_request(module))) def update(module, link, fetch): auth = GcpSession(module, 'kms') params = {'updateMask': updateMask(resource_to_request(module), response_to_hash(module, fetch))} request = resource_to_request(module) return return_if_object(module, auth.patch(link, request, params=params)) def updateMask(request, response): update_mask = [] if request.get('labels') != response.get('labels'): update_mask.append('labels') if request.get('rotationPeriod') != response.get('rotationPeriod'): update_mask.append('rotationPeriod') if request.get('versionTemplate') != response.get('versionTemplate'): update_mask.append('versionTemplate') return ','.join(update_mask) def delete(module, link): module.fail_json(msg="KeyRings cannot be deleted") def resource_to_request(module): request = { u'labels': module.params.get('labels'), u'purpose': module.params.get('purpose'), u'rotationPeriod': module.params.get('rotation_period'), u'versionTemplate': CryptoKeyVersiontemplate(module.params.get('version_template', {}), module).to_request(), } return_vals = {} for k, v in request.items(): if v or v is False: return_vals[k] = v return return_vals def fetch_resource(module, link, allow_not_found=True): auth = GcpSession(module, 'kms') return return_if_object(module, auth.get(link), allow_not_found) def self_link(module): return "https://cloudkms.googleapis.com/v1/{key_ring}/cryptoKeys/{name}".format(**module.params) def collection(module): return "https://cloudkms.googleapis.com/v1/{key_ring}/cryptoKeys".format(**module.params) def create_link(module): return "https://cloudkms.googleapis.com/v1/{key_ring}/cryptoKeys?cryptoKeyId={name}".format(**module.params) def return_if_object(module, response, allow_not_found=False): # If not found, return nothing. if allow_not_found and response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError): module.fail_json(msg="Invalid JSON response with error: %s" % response.text) result = decode_response(result, module) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result def is_different(module, response): request = resource_to_request(module) response = response_to_hash(module, response) request = decode_response(request, module) # Remove all output-only from response. response_vals = {} for k, v in response.items(): if k in request: response_vals[k] = v request_vals = {} for k, v in request.items(): if k in response: request_vals[k] = v return GcpRequest(request_vals) != GcpRequest(response_vals) # Remove unnecessary properties from the response. # This is for doing comparisons with Ansible's current parameters. def response_to_hash(module, response): return { u'name': module.params.get('name'), u'creationTime': response.get(u'creationTime'), u'labels': response.get(u'labels'), u'purpose': module.params.get('purpose'), u'rotationPeriod': response.get(u'rotationPeriod'), u'versionTemplate': CryptoKeyVersiontemplate(response.get(u'versionTemplate', {}), module).from_response(), } def decode_response(response, module): if 'name' in response: response['name'] = response['name'].split('/')[-1] return response class CryptoKeyVersiontemplate(object): def __init__(self, request, module): self.module = module if request: self.request = request else: self.request = {} def to_request(self): return remove_nones_from_dict({u'algorithm': self.request.get('algorithm'), u'protectionLevel': self.request.get('protection_level')}) def from_response(self): return remove_nones_from_dict({u'algorithm': self.request.get(u'algorithm'), u'protectionLevel': self.module.params.get('protection_level')}) if __name__ == '__main__': main()
gpl-3.0
-7,609,309,285,686,532,000
32.288056
152
0.63747
false
jj4jj/awolmsg
pydemo/server.py
1
3088
import redis import json class MsgSvr(): def __init__(self): self.r=redis.Redis(host='localhost',port=6379, db=0) self.peers=[] #connect to redis server def set(self, actor, type, qid, msg): #hset hset=self.mergekey(actor, type) if self.r.hlen(hset) > 100: return None return self.r.hset(hset, qid, msg) def alive(self, actor): pass def mergekey(self, actor, type): return 'u1$msg$%i$%i$%i' % (actor.type, actor.id, type) def list(self, actor, type): key=self.mergekey(actor, type) #print key return self.r.hvals(key) def rm(self, actor, type, id): return self.r.hdel(self.mergekey(actor, type), id) def length(self, actor, type): return self.r.hlen(self.mergekey(actor,type)) def on_actor_msg_add(): pass def register(self, peer): self.peers.append(peer) class MsgMgr(): def __init__(self, svr, selfinfo): self.msgsvr=MsgSvr() def init(self, options, processors): self.processors=[] self.processors.extend(processors) #send(register_msg) self.msgsvr.register(self) def update(self): #listall > pass import datetime import time class MsgProcessor(): def __init__(self, type, msgsvr): self.type=type self.msgsvr=msgsvr self.starttime=time.time() self.seq=0 def msg(self, type, expire, data): return dict(type=type, id=self.nextid(), time=time.time(), expire=expire, data=data) def nextid(self): self.seq+=1 return self.starttime*(1<<31)+self.seq def sendm(self, toers, type, data, expire=-1): [self.send(actor, type, data, expire) for actor in toers] def send(self, actor, type, data, expire=-1): msg=self.msg(type, expire, data) if self.msgsvr.set(actor, self.type, msg['id'], msg) is None: print "full" else: print "send msg success" class MailProcessor(MsgProcessor): def update(self, actor, id, op): pass def list(self, actor): return self.msgsvr.list(actor, self.type) def remove(self, actor, id): pass @staticmethod def mail(sender, title, content, attachements=None): return json.dumps(dict(sender=sender.id, title=title, content=content, attachments=attachements)) def send(self, toers, mail): if isinstance(toers, list): MsgProcessor.sendm(self, toers, 1 , mail) else: MsgProcessor.send(self, toers, 1 , mail) pass def onNotify(self, actor, mail): print 'actor receive mail' pass class Actor(): def __init__(self): self.id=0 self.type=0 self. def main(): msgsvr=MsgSvr() actor=Actor() actor.type=1 actor.id=23556 mail=MailProcessor(1, msgsvr) mail.send(actor, MailProcessor.mail(actor, 'echo', 'hello,world from myself')) print 'list:'+str(mail.list(actor)) if __name__ == '__main__': main()
mit
-1,263,875,015,260,058,000
24.105691
105
0.588407
false
chinakr/jiaxiao
jiaxiao/jiaxiao/wsgi.py
1
1422
""" WSGI config for jiaxiao project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "jiaxiao.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jiaxiao.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
gpl-2.0
-1,596,401,843,799,118,000
43.4375
79
0.793249
false
virtuNat/hemopicker
hemopicker.py
1
3420
#!/usr/bin/env python import pygame as pg from colorset import ColorSet from boilerplate import load_image from boilerplate import AppExit, AppState, FreeSprite from boilerplate import Appli, Window class Gamzee(FreeSprite): """Gamzee Makara's display sprite. Does nothing.""" def __init__(self, **kwargs): super().__init__( image=load_image('gamzee.png', colorkey=0x00FF00), **kwargs, ) class ColorMenu(AppState): """docstring""" def __init__(self): self.bg = pg.Surface(self.window.rect.size) self.panel = load_image('panel.png', colorkey=0xFF00FF) self.gamzee = Gamzee(topright=(self.window.rect.topright)) self.colorset = ColorSet() def eval_events(self): """Handles all event logic.""" for event in pg.event.get(): if event.type == pg.QUIT: raise AppExit elif event.type == pg.MOUSEBUTTONDOWN: if event.button == 1: pos = event.pos if self.colorset.isclicked('genbutton', pos): self.colorset.generate() elif self.colorset.isclicked('genallbutton', pos): self.colorset.generate_all() elif self.colorset.isclicked('mutantbutton', pos): self.colorset.toggle_mutant() elif self.colorset.isclicked('randombutton', pos): self.colorset.toggle_random() else: # Turn cursor position into a rect to take advantage of Rect.collidelist rpos = pg.Rect(pos, (1, 1)) idx = rpos.collidelist(self.colorset.castebuttons) if idx >= 0: # Switch caste hue if self.colorset.castebuttons[idx].active: self.colorset.castebuttons[idx].pressed = True continue self.colorset.set_caste(idx) continue idx = rpos.collidelist(self.colorset.oldcolors) if idx >= 0: # Look at previous colors self.colorset.swap_color(idx) continue idx = rpos.collidelist(self.colorset.copybuttons) if idx >= 0: self.colorset.clip_color(idx) continue elif event.type == pg.MOUSEBUTTONUP: if event.button == 1: self.colorset.unpress() def eval_logic(self): """Handles logic not requiring event handling.""" self.colorset.update() def display(self): """Handles the display.""" drawsurf = self.window.surf drawsurf.blit(self.bg, (0, 0)) self.colorset.draw(drawsurf) drawsurf.blit(self.panel, (0, 0)) self.gamzee.draw(drawsurf) pg.display.flip() app = Appli( window=Window( name='Fantroll Hemopicker', size=(800, 600), flags=pg.HWSURFACE, ), state='picker' ) app.set_states(picker=ColorMenu) app.run()
gpl-3.0
-8,802,998,533,534,245,000
35.173913
96
0.494444
false
frankvdp/django
django/db/models/functions/text.py
8
8244
from django.db.models import Func, IntegerField, Transform, Value, fields from django.db.models.functions import Coalesce class BytesToCharFieldConversionMixin: """ Convert CharField results from bytes to str. MySQL returns long data types (bytes) instead of chars when it can't determine the length of the result string. For example: LPAD(column1, CHAR_LENGTH(column2), ' ') returns the LONGTEXT (bytes) instead of VARCHAR. """ def convert_value(self, value, expression, connection): if connection.features.db_functions_convert_bytes_to_str: if self.output_field.get_internal_type() == 'CharField' and isinstance(value, bytes): return value.decode() return super().convert_value(value, expression, connection) class Chr(Transform): function = 'CHR' lookup_name = 'chr' def as_mysql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, function='CHAR', template='%(function)s(%(expressions)s USING utf16)', **extra_context ) def as_oracle(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template='%(function)s(%(expressions)s USING NCHAR_CS)', **extra_context ) def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function='CHAR', **extra_context) class ConcatPair(Func): """ Concatenate two arguments together. This is used by `Concat` because not all backend databases support more than two arguments. """ function = 'CONCAT' def as_sqlite(self, compiler, connection, **extra_context): coalesced = self.coalesce() return super(ConcatPair, coalesced).as_sql( compiler, connection, template='%(expressions)s', arg_joiner=' || ', **extra_context ) def as_mysql(self, compiler, connection, **extra_context): # Use CONCAT_WS with an empty separator so that NULLs are ignored. return super().as_sql( compiler, connection, function='CONCAT_WS', template="%(function)s('', %(expressions)s)", **extra_context ) def coalesce(self): # null on either side results in null for expression, wrap with coalesce c = self.copy() expressions = [ Coalesce(expression, Value('')) for expression in c.get_source_expressions() ] c.set_source_expressions(expressions) return c class Concat(Func): """ Concatenate text fields together. Backends that result in an entire null expression when any arguments are null will wrap each argument in coalesce functions to ensure a non-null result. """ function = None template = "%(expressions)s" def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError('Concat must take at least two expressions') paired = self._paired(expressions) super().__init__(paired, **extra) def _paired(self, expressions): # wrap pairs of expressions in successive concat functions # exp = [a, b, c, d] # -> ConcatPair(a, ConcatPair(b, ConcatPair(c, d)))) if len(expressions) == 2: return ConcatPair(*expressions) return ConcatPair(expressions[0], self._paired(expressions[1:])) class Left(Func): function = 'LEFT' arity = 2 def __init__(self, expression, length, **extra): """ expression: the name of a field, or an expression returning a string length: the number of characters to return from the start of the string """ if not hasattr(length, 'resolve_expression'): if length < 1: raise ValueError("'length' must be greater than 0.") super().__init__(expression, length, **extra) def get_substr(self): return Substr(self.source_expressions[0], Value(1), self.source_expressions[1]) def use_substr(self, compiler, connection, **extra_context): return self.get_substr().as_oracle(compiler, connection, **extra_context) as_oracle = use_substr as_sqlite = use_substr class Length(Transform): """Return the number of characters in the expression.""" function = 'LENGTH' lookup_name = 'length' output_field = fields.IntegerField() def as_mysql(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function='CHAR_LENGTH', **extra_context) class Lower(Transform): function = 'LOWER' lookup_name = 'lower' class LPad(BytesToCharFieldConversionMixin, Func): function = 'LPAD' def __init__(self, expression, length, fill_text=Value(' '), **extra): if not hasattr(length, 'resolve_expression') and length is not None and length < 0: raise ValueError("'length' must be greater or equal to 0.") super().__init__(expression, length, fill_text, **extra) class LTrim(Transform): function = 'LTRIM' lookup_name = 'ltrim' class Ord(Transform): function = 'ASCII' lookup_name = 'ord' output_field = IntegerField() def as_mysql(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function='ORD', **extra_context) def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function='UNICODE', **extra_context) class Repeat(BytesToCharFieldConversionMixin, Func): function = 'REPEAT' def __init__(self, expression, number, **extra): if not hasattr(number, 'resolve_expression') and number is not None and number < 0: raise ValueError("'number' must be greater or equal to 0.") super().__init__(expression, number, **extra) def as_oracle(self, compiler, connection, **extra_context): expression, number = self.source_expressions length = None if number is None else Length(expression) * number rpad = RPad(expression, length, expression) return rpad.as_sql(compiler, connection, **extra_context) class Replace(Func): function = 'REPLACE' def __init__(self, expression, text, replacement=Value(''), **extra): super().__init__(expression, text, replacement, **extra) class Right(Left): function = 'RIGHT' def get_substr(self): return Substr(self.source_expressions[0], self.source_expressions[1] * Value(-1)) class RPad(LPad): function = 'RPAD' class RTrim(Transform): function = 'RTRIM' lookup_name = 'rtrim' class StrIndex(Func): """ Return a positive integer corresponding to the 1-indexed position of the first occurrence of a substring inside another string, or 0 if the substring is not found. """ function = 'INSTR' arity = 2 output_field = fields.IntegerField() def as_postgresql(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function='STRPOS', **extra_context) class Substr(Func): function = 'SUBSTRING' def __init__(self, expression, pos, length=None, **extra): """ expression: the name of a field, or an expression returning a string pos: an integer > 0, or an expression returning an integer length: an optional number of characters to return """ if not hasattr(pos, 'resolve_expression'): if pos < 1: raise ValueError("'pos' must be greater than 0") expressions = [expression, pos] if length is not None: expressions.append(length) super().__init__(*expressions, **extra) def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function='SUBSTR', **extra_context) def as_oracle(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function='SUBSTR', **extra_context) class Trim(Transform): function = 'TRIM' lookup_name = 'trim' class Upper(Transform): function = 'UPPER' lookup_name = 'upper'
bsd-3-clause
2,305,287,747,617,468,700
32.376518
97
0.639131
false
bbiiggppiigg/PokemonGo-Bot
pokemongo_bot/test/plugin_loader_test.py
19
6875
import imp import sys import pkgutil import importlib import unittest import os import shutil import mock from datetime import timedelta, datetime from mock import patch, MagicMock from pokemongo_bot.plugin_loader import PluginLoader, GithubPlugin from pokemongo_bot.test.resources.plugin_fixture import FakeTask PLUGIN_PATH = os.path.realpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'plugins')) class PluginLoaderTest(unittest.TestCase): def setUp(self): self.plugin_loader = PluginLoader() def test_load_namespace_class(self): package_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'resources', 'plugin_fixture') self.plugin_loader.load_plugin(package_path) loaded_class = self.plugin_loader.get_class('plugin_fixture.FakeTask') self.assertEqual(loaded_class({}, {}).work(), 'FakeTask') self.plugin_loader.remove_path(package_path) def test_load_zip(self): package_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'resources', 'plugin_fixture_test.zip') self.plugin_loader.load_plugin(package_path) loaded_class = self.plugin_loader.get_class('plugin_fixture_test.FakeTask') self.assertEqual(loaded_class({}, {}).work(), 'FakeTaskZip') self.plugin_loader.remove_path(package_path) def copy_plugin(self): package_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'resources', 'plugin_fixture') dest_path = os.path.join(PLUGIN_PATH, 'org_repo', 'plugin_fixture_tests') shutil.copytree(package_path, os.path.join(dest_path)) with open(os.path.join(os.path.dirname(dest_path), '.sha'), 'w') as file: file.write('testsha') return dest_path def test_load_github_already_downloaded(self): dest_path = self.copy_plugin() self.plugin_loader.load_plugin('org/repo#testsha') loaded_class = self.plugin_loader.get_class('plugin_fixture_tests.FakeTask') self.assertEqual(loaded_class({}, {}).work(), 'FakeTask') self.plugin_loader.remove_path(dest_path) shutil.rmtree(os.path.dirname(dest_path)) def copy_zip(self): zip_name = 'test-pgo-plugin-2d54eddde33061be9b329efae0cfb9bd58842655.zip' fixture_zip = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'resources', zip_name) zip_dest = os.path.join(PLUGIN_PATH, 'org_test-pgo-plugin_2d54eddde33061be9b329efae0cfb9bd58842655.zip') shutil.copyfile(fixture_zip, zip_dest) @mock.patch.object(GithubPlugin, 'download', copy_zip) def test_load_github_not_downloaded(self): self.plugin_loader.load_plugin('org/test-pgo-plugin#2d54eddde33061be9b329efae0cfb9bd58842655') loaded_class = self.plugin_loader.get_class('test-pgo-plugin.PrintText') self.assertEqual(loaded_class({}, {}).work(), 'PrintText') dest_path = os.path.join(PLUGIN_PATH, 'org_test-pgo-plugin') self.plugin_loader.remove_path(os.path.join(dest_path, 'test-pgo-plugin')) shutil.rmtree(dest_path) class GithubPluginTest(unittest.TestCase): def test_get_github_parts_for_valid_github(self): github_plugin = GithubPlugin('org/repo#sha') self.assertTrue(github_plugin.is_valid_plugin()) self.assertEqual(github_plugin.plugin_parts['user'], 'org') self.assertEqual(github_plugin.plugin_parts['repo'], 'repo') self.assertEqual(github_plugin.plugin_parts['sha'], 'sha') def test_get_github_parts_for_invalid_github(self): self.assertFalse(GithubPlugin('org/repo').is_valid_plugin()) self.assertFalse(GithubPlugin('foo').is_valid_plugin()) self.assertFalse(GithubPlugin('/Users/foo/bar.zip').is_valid_plugin()) def test_get_installed_version(self): github_plugin = GithubPlugin('org/repo#my-version') src_fixture = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'resources', 'plugin_sha') dest = github_plugin.get_plugin_folder() shutil.copytree(src_fixture, dest) actual = github_plugin.get_installed_version() shutil.rmtree(dest) self.assertEqual('my-version', actual) def test_get_plugin_folder(self): github_plugin = GithubPlugin('org/repo#sha') expected = os.path.join(PLUGIN_PATH, 'org_repo') actual = github_plugin.get_plugin_folder() self.assertEqual(actual, expected) def test_get_local_destination(self): github_plugin = GithubPlugin('org/repo#sha') path = github_plugin.get_local_destination() expected = os.path.join(PLUGIN_PATH, 'org_repo_sha.zip') self.assertEqual(path, expected) def test_get_github_download_url(self): github_plugin = GithubPlugin('org/repo#sha') url = github_plugin.get_github_download_url() expected = 'https://github.com/org/repo/archive/sha.zip' self.assertEqual(url, expected) def test_is_already_installed_not_installed(self): github_plugin = GithubPlugin('org/repo#sha') self.assertFalse(github_plugin.is_already_installed()) def test_is_already_installed_version_mismatch(self): github_plugin = GithubPlugin('org/repo#sha') plugin_folder = github_plugin.get_plugin_folder() os.mkdir(plugin_folder) with open(os.path.join(plugin_folder, '.sha'), 'w') as file: file.write('sha2') actual = github_plugin.is_already_installed() shutil.rmtree(plugin_folder) self.assertFalse(actual) def test_is_already_installed_installed(self): github_plugin = GithubPlugin('org/repo#sha') plugin_folder = github_plugin.get_plugin_folder() os.mkdir(plugin_folder) with open(os.path.join(plugin_folder, '.sha'), 'w') as file: file.write('sha') actual = github_plugin.is_already_installed() shutil.rmtree(plugin_folder) self.assertTrue(actual) def test_extract(self): github_plugin = GithubPlugin('org/test-pgo-plugin#2d54eddde33061be9b329efae0cfb9bd58842655') src = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'resources', 'test-pgo-plugin-2d54eddde33061be9b329efae0cfb9bd58842655.zip') zip_dest = github_plugin.get_local_destination() shutil.copyfile(src, zip_dest) github_plugin.extract() plugin_folder = github_plugin.get_plugin_folder() os.path.isdir(plugin_folder) sub_folder = os.path.join(plugin_folder, 'test-pgo-plugin') os.path.isdir(sub_folder) sha_file = os.path.join(github_plugin.get_plugin_folder(), '.sha') os.path.isfile(sha_file) with open(sha_file) as file: content = file.read().strip() self.assertEqual(content, '2d54eddde33061be9b329efae0cfb9bd58842655') shutil.rmtree(plugin_folder)
mit
-2,005,949,108,382,772,000
45.452703
147
0.672436
false
boland1992/SeisSuite
bin/xcorr_multiplot.py
2
4620
# -*- coding: utf-8 -*- """ Created on Mon Mar 28 12:28:15 2016 @author: boland """ # -*- coding: utf-8 -*- """ Created on Mon Mar 28 08:35:56 2016 @author: boland """ # -*- coding: utf-8 -*- """ Created on Fri Oct 16 23:34:00 2015 @author: boland """ from seissuite.ant import (pscrosscorr) import matplotlib.pyplot as plt import glob import os import pickle import numpy as np from obspy.core import UTCDateTime as utc import datetime as dt from matplotlib.colors import LogNorm from matplotlib import colors #PICKLE_PATH = '/storage/ANT/PROGRAMS/ANT_OUTPUT/OUTPUT/CROSS/06.05.2015-15:53:28/XCORR-STACK_01.01.2014-31.12.2014_datalesspaz.pickle' #PICKLE_PATH = '/home/boland/Desktop/XCORR-STACK_01.08.1999-10.06.2000_datalesspaz.part.pickle' # import CONFIG class initalised in ./configs/tmp_config.pickle config_pickle = 'configs/tmp_config.pickle' f = open(name=config_pickle, mode='rb') CONFIG = pickle.load(f) f.close() # import variables from initialised CONFIG class. # import variables from initialised CONFIG class. MSEED_DIR = CONFIG.MSEED_DIR DATABASE_DIR = CONFIG.DATABASE_DIR DATALESS_DIR = CONFIG.DATALESS_DIR STATIONXML_DIR = CONFIG.STATIONXML_DIR CROSSCORR_DIR = CONFIG.CROSSCORR_DIR USE_DATALESSPAZ = CONFIG.USE_DATALESSPAZ USE_STATIONXML = CONFIG.USE_STATIONXML CROSSCORR_STATIONS_SUBSET = CONFIG.CROSSCORR_STATIONS_SUBSET CROSSCORR_SKIPLOCS = CONFIG.CROSSCORR_SKIPLOCS FIRSTDAY = CONFIG.FIRSTDAY LASTDAY = CONFIG.LASTDAY MINFILL = CONFIG.MINFILL FREQMIN = CONFIG.FREQMIN FREQMAX = CONFIG.FREQMAX CORNERS = CONFIG.CORNERS ZEROPHASE = CONFIG.ZEROPHASE PERIOD_RESAMPLE = CONFIG.PERIOD_RESAMPLE ONEBIT_NORM = CONFIG.ONEBIT_NORM FREQMIN_EARTHQUAKE = CONFIG.FREQMIN_EARTHQUAKE FREQMAX_EARTHQUAKE = CONFIG.FREQMAX_EARTHQUAKE WINDOW_TIME = CONFIG.WINDOW_TIME WINDOW_FREQ = CONFIG.WINDOW_FREQ XCORR_INTERVAL = CONFIG.XCORR_INTERVAL CROSSCORR_TMAX = CONFIG.CROSSCORR_TMAX PLOT_CLASSIC = CONFIG.PLOT_CLASSIC PLOT_DISTANCE = CONFIG.PLOT_DISTANCE MAX_DISTANCE = CONFIG.MAX_DISTANCE pickle_list = [] folder_list = sorted(glob.glob(os.path.join(CROSSCORR_DIR, '*'))) print MSEED_DIR print CROSSCORR_TMAX # station list to plot SNR for # can only plot one station combination per plot! stat_list = [['AUBSH', 'AUTOO'], ['AUBSH', 'AUWSH'], ['AUDHS', 'AUKAT'], ['AUMOU', 'AUNRC'], ['AUMOU', 'AUTOO'], ['AUNRC', 'AUTOO'], ['AUTOO', 'AUWSH']] for folder in folder_list: #check to see if there are any pickle files in the xcorr time folder if len(glob.glob(os.path.join(folder, '*.pickle'))) < 1: #print("There are no .pickle files in this folder. Skipping ...") continue else: for file_ in glob.glob(os.path.join(folder, '*.pickle')): if 'metadata' not in file_ and '.part' not in file_: pickle_list.append(file_) start_plot = dt.datetime(2014, 1, 1, 00, 00) end_plot = dt.datetime(2014, 2, 1, 00, 00) dpi = 300 counter = 0 total_time = [] total_SNR = [] for pair in stat_list: s1, s2 = pair fig = plt.figure(figsize=(21.0, 12.0)) for PICKLE_PATH in pickle_list: OUTFILESPATH = PICKLE_PATH[:-7] out_basename = os.path.basename(OUTFILESPATH) OUTPATH = os.path.dirname(OUTFILESPATH) OUT_SNR = os.path.join(OUTPATH, 'SNR_PLOTS') print OUTPATH # re-initialising .part.pickle collection of cross-correlations xc = pscrosscorr.load_pickled_xcorr(PICKLE_PATH) dataarray = np.asarray(xc[s1][s2].dataarray) timearray = np.asarray(xc[s1][s2].timearray) dataarray = dataarray / np.max(dataarray) if len(dataarray) > 0 and len(dataarray) == len(timearray): x, y = timearray, dataarray s = '{s1}-{s2}: Plot of 100 randomly stacked combination cross-correlations.' title = s.format(s1=s1, s2=s2) #plt.xlim([start_plot, end_plot]) plt.title(title) plt.ylabel('Amplitude') plt.xlabel('Time (UTC)') plt.plot(x, y, alpha=0.05, c='k') file_name = 'Random_Combination_waveform{}-{}-SNR.png'.format(s1, s2) print '{s1}-{s2}'.format(s1=s1, s2=s2) #plt.show() fig.savefig(file_name) plt.clf() #fig.savefig(outfile_individual, dpi=dpi) #fig.clf()
gpl-3.0
4,845,144,260,295,143,000
30.650685
135
0.62619
false
atagar/ReviewBoard
reviewboard/hostingsvcs/service.py
1
8490
import base64 import logging import mimetools import urllib2 from pkg_resources import iter_entry_points from django.utils import simplejson from django.utils.translation import ugettext_lazy as _ class HostingService(object): """An interface to a hosting service for repositories and bug trackers. HostingService subclasses are used to more easily configure repositories and to make use of third party APIs to perform special operations not otherwise usable by generic repositories. A HostingService can specify forms for repository and bug tracker configuration. It can also provide a list of repository "plans" (such as public repositories, private repositories, or other types available to the hosting service), along with configuration specific to the plan. These plans will be available when configuring the repository. """ name = None plans = None supports_bug_trackers = False supports_repositories = False # These values are defaults that can be overridden in repository_plans # above. needs_authorization = False supported_scmtools = [] form = None fields = [] repository_fields = {} bug_tracker_field = None def __init__(self, account): assert account self.account = account def is_authorized(self): """Returns whether or not the account is currently authorized. An account may no longer be authorized if the hosting service switches to a new API that doesn't match the current authorization records. This function will determine whether the account is still considered authorized. """ return False def authorize(self, username, password, local_site_name=None, *args, **kwargs): raise NotImplementedError def get_file(self, repository, path, revision, *args, **kwargs): if not self.supports_repositories: raise NotImplementedError return repository.get_scmtool().get_file(path, revision) def get_file_exists(self, repository, path, revision, *args, **kwargs): if not self.supports_repositories: raise NotImplementedError return repository.get_scmtool().file_exists(path, revision) @classmethod def get_repository_fields(cls, username, plan, tool_name, field_vars): if not cls.supports_repositories: raise NotImplementedError # Grab the list of fields for population below. We have to do this # differently depending on whether or not this hosting service has # different repository plans. fields = cls._get_field(plan, 'repository_fields') new_vars = field_vars.copy() new_vars['hosting_account_username'] = username results = {} for field, value in fields[tool_name].iteritems(): try: results[field] = value % new_vars except KeyError, e: logging.error('Failed to generate %s field for hosting ' 'service %s using %s and %r: Missing key %s' % (field, unicode(cls.name), value, new_vars, e), exc_info=1) raise KeyError( _('Internal error when generating %(field)s field ' '(Missing key "%(key)s"). Please report this.') % { 'field': field, 'key': e, }) return results @classmethod def get_bug_tracker_requires_username(cls, plan=None): if not cls.supports_bug_trackers: raise NotImplementedError return ('%(hosting_account_username)s' in cls._get_field(plan, 'bug_tracker_field', '')) @classmethod def get_bug_tracker_field(cls, plan, field_vars): if not cls.supports_bug_trackers: raise NotImplementedError bug_tracker_field = cls._get_field(plan, 'bug_tracker_field') if not bug_tracker_field: return '' try: return bug_tracker_field % field_vars except KeyError, e: logging.error('Failed to generate %s field for hosting ' 'service %s using %r: Missing key %s' % (bug_tracker_field, unicode(cls.name), field_vars, e), exc_info=1) raise KeyError( _('Internal error when generating %(field)s field ' '(Missing key "%(key)s"). Please report this.') % { 'field': bug_tracker_field, 'key': e, }) @classmethod def _get_field(cls, plan, name, default=None): if cls.plans: assert plan for plan_name, info in cls.plans: if plan_name == plan and name in info: return info[name] return getattr(cls, name, default) # # HTTP utility methods # def _json_get(self, *args, **kwargs): data, headers = self._http_get(*args, **kwargs) return simplejson.loads(data), headers def _json_post(self, *args, **kwargs): data, headers = self._http_post(*args, **kwargs) return simplejson.loads(data), headers def _http_get(self, url, *args, **kwargs): r = self._build_request(url, *args, **kwargs) u = urllib2.urlopen(r) return u.read(), u.headers def _http_post(self, url, body=None, fields={}, files={}, content_type=None, headers={}, *args, **kwargs): headers = headers.copy() if body is None: if fields is not None: body, content_type = self._build_form_data(fields, files) else: body = '' if content_type: headers['Content-Type'] = content_type headers['Content-Length'] = str(len(body)) r = self._build_request(url, body, headers, **kwargs) u = urllib2.urlopen(r) return u.read(), u.headers def _build_request(self, url, body=None, headers={}, username=None, password=None): r = urllib2.Request(url, body, headers) if username is not None and password is not None: r.add_header(urllib2.HTTPBasicAuthHandler.auth_header, 'Basic %s' % base64.b64encode(username + ':' + password)) return r def _build_form_data(self, fields, files): """Encodes data for use in an HTTP POST.""" BOUNDARY = mimetools.choose_boundary() content = "" for key in fields: content += "--" + BOUNDARY + "\r\n" content += "Content-Disposition: form-data; name=\"%s\"\r\n" % key content += "\r\n" content += str(fields[key]) + "\r\n" for key in files: filename = files[key]['filename'] value = files[key]['content'] content += "--" + BOUNDARY + "\r\n" content += "Content-Disposition: form-data; name=\"%s\"; " % key content += "filename=\"%s\"\r\n" % filename content += "\r\n" content += value + "\r\n" content += "--" + BOUNDARY + "--\r\n" content += "\r\n" content_type = "multipart/form-data; boundary=%s" % BOUNDARY return content_type, content def get_hosting_services(): """Gets the list of hosting services. This will return an iterator for iterating over each hosting service. """ for entry in iter_entry_points('reviewboard.hosting_services'): try: cls = entry.load() except Exception, e: logging.error('Unable to load repository hosting service %s: %s' % (entry, e)) continue yield (entry.name, cls) def get_hosting_service(name): """Retrieves the hosting service with the given name. If the hosting service is not found, None will be returned. """ entries = list(iter_entry_points('reviewboard.hosting_services', name)) if entries: entry = entries[0] try: return entry.load() except Exception, e: logging.error('Unable to load repository hosting service %s: %s' % (entry, e)) return None
mit
-7,944,290,956,411,547,000
32.557312
79
0.571143
false
arpho/mmasgis5
mmasgis/sessionClasses.py
1
27075
#!/usr/bin/python # -*- coding: latin-1 -*- import re from constants import * from mmasgisDb_sqlalchemy import * from sqlalchemy import func class Relations(): """ esprime le relazioni n:m esistenti tra utenti e funzioni, utenti e dbs utenti e UTB trasformando la base dati offerta da Qsettings in una base dati relazionale """ def __init__(self): self.header="" self.qName="" self.category="" #per default non puo' fare nulla self.relations={} def __repr__(self): return "relazione: {0},{1} elementi".format(self.category,len(self.relations)) def getCategory(self): """ ritorna la categoria di Relations e' il riferimento al tipo di oggetti che vengono relazionati con gli utenti nella istanza di Relations @return: string<'user'><'db'><'function'><'utb'> """ return self.category def setCategory(self, c): """ setta la categoria di Relations e' il riferimento al tipo di oggetti che vengono relazionati con gli utenti nella istanza di Relations @param: string<'user'><'db'><'function'><'utb'> """ self.category=c def getRelations(self,k): """ritorna le relazioni definite per l'utente di cui e' passato il qName @return: <int><[string]>::<[Object.Qname]> """ if self.relations.has_key(k): return self.relations[k] else: return [] def updateRelations(self, k,l): """ aggiunge le relazioni di un utente al dict degli utenti con la lista degli oggetti a lui disponibili il formato della struttura dati e' il seguente: {string:<[string]>int}::{user.qName:[Object.qName]} se al posto della lista c'e' un intero significa che l'utente ha accesso a tutti gli oggetti di quella categoria @param string: chiave del dict User.Qname @param <int><[Object.Qname]>:se int l'utente ha accesso a tutti gli oggetti della categoria descritta da Relations """ self.relations[k]=l def setQName(self,q): """setta la chiave di Qsettings @param string: """ self.qName=q def getQName(self): """ ritorna la chiave per QSettings @return: string """ return self.qName class Function(): """descrive le funzionalita' di mmasgis, cosi' che possano essere assegnate ad un utente per definirne il profilo """ def __init__(self,header,Id): self.Id=Id self.header=header self.category="" self.qName="" def setId(self,Id): self.Id=Id def getId(self): return self.Id def __repr__(self): return "Function: {0}, {1} qname:{2}".format(self.category,self.header,self.qName) def setHeader(self,h): self.header=h def getHeader(self): return self.header def setCategory(self,c): self.category=c def getCategory(self): return self.category def getQname(self): """ ritorna la chiave di Qsettings della funzione @return: string """ return self.qName def setQname(self,q): """ setta la chiave di Qsettings per l'istanza di Function @param string: """ self.qName=q class UTB(): """e' un alias di Node per memorizzare le zone agente con QSettings senza salvare tutto l'oggetto Node, ma solo i parametri sufficienti per identificare lo UTB negli shapefiles """ def __init__(self,cat,head,Id): """ @param string: catregoria dello shapefile:<comune>,<provincia>,<cap>,<regione> il valore reale dipende dal nome usato negli shapefiles @param string: etichetta dello UTB @param int: featureId """ self.category=cat self.header=head self.Id=Id def setCategory(self,c): self.category=c def setHeader(self,h): self.header=h def setId(self,i): self.Id=i def getCategory(self): return self.category def getHeader(self): return self.header def getId(self): return self.Id def __repr__(self): return "UTB: {0} {1} Id: {2}".format(self.category,self.header,self.Id) class Zone(): """definisce l'insieme di UTB disponibili per l'utente """ def __init__(self,area={}): """ per default nessuna funzione e' resa disponibile per l'utente @param opzionale :<int>,<{string:Function}::{cod identificativo funzione:Function}>, se int significa che l'utente puo' fare tutto, se viene passata una lista di funzioni, queste saranno le uniche disponibili per l'utente, che di default non puo' fare nulla """ self.area=area def __repr__(self): l=lambda x: "profilo amministratore" if type(x)==type(1) else "profilo standard: {0}".format(x) return l(self.area) def getZone(self): """ ritorna il set di aree registrate @return: <it>,<{string:Nodo}::{cod identificativo funzione:Nodo}>, se int significa che l'utente ha accesso a tutte le aree """ return self.area def setZone(self,a): """setta le aree di competenza del profilo @param <-1>,<{string:Nodo}::{cod identificativo funzione:Nodo}> se int significa che l'utente puo' fare tutto, """ self.area=a def isAvailable(self,cod): """ verifica se la funzione il cui codice e' passato come argomento e' permessa all'utente @param bool: """ administrator=lambda k,d: True ordinaryUser=lambda k,d:d.has_key(k) users={} users[type(1)]= administrator users[type({})]=ordinaryUser return users[type(self.area)](cod,self.area) class Profile(): """definisce l'insieme di funzioni disponibili per l'utente """ def __repr__(self): l=lambda x: "profilo amministratore" if type(x)==type(1) else "profilostandard: {0}".format(x) return l(self.profile) def __init__(self,role={}): """ per default nessuna funzione e' resa disponibile per l'utente @param opzionale :<int>,<{id:Function}::{funzione_id:Function}>, se int significa che l'utente puo' fare tutto, se viene passata una lista di funzioni, queste saranno le uniche disponibili per l'utente, che di default non puo' fare nulla """ self.profile=role def getProfile(self): """ ritorna il set di funzioni registrate con il profilo @return: <it>,<{string:Function}::{cod identificativo funzione:Function}>, se int significa che l'utente puo' fare tutto """ return self.profile def setProfile(self,p): """setta le funzioni registrate per il profilo @param <-1>,<{string:Function}::{cod identificativo funzione:Function}> se int significa che l'utente puo' fare tutto. """ self.profile=p def isPermitted(self,cod): """ verifica se la funzione il cui codice e' passato come argomento e' permessa all'utente @param id: function_id """ administrator=lambda k,d: True ordinaryUser=lambda k,d:d.has_key(k) users={} users[type(1)]= administrator users[type({})]=ordinaryUser return users[type(self.profile)](cod,self.profile) class User(): """ implementa il concetto di utente loggato con i db ad esso registrati e il logo aziendale da usare nell'esprtazione in pdf """ def __init__(self,uname,Id): self.name=uname self.Id=Id self.amministratore=0 self.ruolo=-1 self.qName="" self.company_id=-1 self.loggingTime="" self.logo=None self.registeredDbs=[]# questa resta per compatibilita' verso il basso io holaversione nuova di User gli altri no self.dbs=DbSet({}) self.logged=False self.area=Zone({}) self.profile=Profile({}) self.zone=Zone({}) #dummy Db self.activeDb= Db('dbName','descrizione','user_name','pwd','host','rdbms','Id') self.pwd="" def setAmministratore(self,a): self.amministratore=a def getAmministratore(self): return self.amministratore def setCompany(self,c): self.company_id=c def getCompany(self): return self.company_id def setRuolo(self,r): self.ruolo=r def getRuolo(self): return self.ruolo def setLoggingTime(self,t): """ setta il loggingtime per l'utente @param datetime.datetime: tempo attuale come ottenuto da datetime.datetime.now() """ self.loggingTime=t def getLoggingTime(self): """ ritorna il loggingTime @return: datetime.datetime """ return self.loggingTime def setDbset(self,dbs): """ setta i dbs registrati con l'utente @param DbSet """ self.dbs=dbs def getDbset(self): """ritorna il dict dei dbsregistrati con l'utente @return dbSet """ #creo una lambda f che ritorna il db relativo alla chiave di self.dbs return self.dbs def setProfile(self,p): """setta il profilo utente, cioe' l'insieme di funzioni disponibili per l'utente @param Profile::{codice identificativo della funzione:oggetto funzione} """ self.profile=p def getProfile(self): """ riorna il profilo utente, cioe' l'insieme di funzioni disponibili per l'utente @return: Profile """ return self.profile def setZone(self,p): """setta la zona utente, cioe' l'insieme di aree di competenza dell'utente @param {string:Nodo}::{codice identificativo dell'area geografica:Nodo} """ self.zone=p def getZones(self): """ riorna la zona utente, cioe' l'insieme di aree di competenza dell'utente @return: {string:None}::{Nodo.signature:None} """ z={} if type(self.zone)==type(1): #se super-user self.zone e' un intero z=self.zone else: for k in self.zone.itervalues(): z[k.getSignature()]=None return z def resetProfile(self): """resetta il dict dei profili @note: i profili utente sono registrati con Qsettings in un oggetto relations con chiave profiles """ self.profile={} def resetDbs(self): """resetta il dict dei dbs @note: i dbs utente sono registrati con Qsettings in un ggetto relations con chiave dbs """ self.dbs={} def resetZones(self): """resetta il dict delle zone @note: le zone utente sono registrate con Qsettings in un oggetto relations con chiave zones """ self.zone={} def getLogo(self): return self.logo def setLogo(self,l): self.logo=l def setName(self,n): self.name=n def getQName(self): """ ritorna la chiave di Qsetting per User @return: string """ return self.qName def setQname(self,q): """setta la chiave di QSettings per User """ self.qName=q def setPassword(self,p): self.pwd=p def getPassword(self): return self.pwd def isLogged(self): """ritorna lo stato dell'utente se loggato e' True @return: bool """ return self.logged def setLogged(self,b): """setta il parametro logged @param bool: """ self.logged=b def getName(self): """ritorna lo user name @return: string """ return self.name def setId(self,Id): self.Id=Id def getId(self): """ritorna lo id utente @return: int """ return self.Id def getRegisteredDb(self): """converte il dict dei db registrati per l'utente in una lista @return: [Db] """ dbs=[] for db in self.registeredDbs.iterValues(): dbs.append(db) return dbs def setRegisteredDb(self,l): """ setta la lista dei db registrati @param [DB]: """ self.registeredDbs=l def getActiveDb(self): """ritorna il db attivo dell'utente @return: DB """ db=None """ for i in self.registeredDbs: if i.isActive(): db=i """ return self.activeDb def setActiveDb(self,db): """setta il db attivo @param Db: """ """ #disattivo tutti i dbs for i in self.registeredDbs: i.setActive(False) # setto attivo il db il cui id corrisponde a quello passato for i in self.registeredDbs: if i.getId()==Id: i.setActive(True) self.activeDb=i """ self.activeDb=db def __repr__(self): l=lambda x: "autenticato"if x else "non autenticato" txt="User: {0}, Id:{1}, {2}, profilo: {3},dbs: {4}, zone: {5}".format(self.name,self.Id,l(self.logged),self.profile,self.dbs,self.zone) for i in self.registeredDbs: txt+="\d {0}".format(i) return txt class DbSet(): """ definisce l'insieme di db cui l'utente e' autorizzato """ def __repr__(self): l=lambda x:"amministratore censimenti" if type(x)==type(1) else "utente ordinario" return "Dbset: {0}".format(l(self.profile)) def __init__(self,dbSet={}): """ per default nessun db e' accessibile per l'utente @param opzionale :<int>,<{id:Db}::{db_id:Db}>, se int significa che l'utente ha accesso a tutti i db del sistema mmasgis, se viene passata una lista di db, questi saranno gli unici disponibili per l'utente, che di default non puo' fare nulla """ self.profile=dbSet def getProfile(self): """ ritorna il set di funzioni registrate con il profilo @return: <it>,<{string:Function}::{cod identificativo funzione:Function}>, se int significa che l'utente puo' fare tutto """ return self.profile def setProfile(self,p): """setta le funzioni registrate per il profilo @param <-1>,<{string:Function}::{cod identificativo funzione:Function}> se int significa che l'utente puo' fare tutto. """ self.profile=p def isPermitted(self,cod): """ verifica se il db il cui id e' passato come argomento e' permessa all'utente @param int:db_id """ administrator=lambda k,d: True ordinaryUser=lambda k,d:d.has_key(k) users={} users[type(1)]= administrator users[type({})]=ordinaryUser return users[type(self.profile)](cod,self.profile) class extendedUser(User): def __repr__(self): l=lambda x: "autenticato"if x else "non autenticato" txt="User: {0}, Id:{1} {2} {3}".format(self.name,self.Id,l(self.logged),self.loggingTime) for i in self.registeredDbs: txt+="\d {0}".format(i) return txt def __init__(self,uname,Id): self.name=uname self.Id=Id self.logo=None self.logged=False self.loggingTime="" self.qsettingsName="" self.profile={} self.zone={} self.pwd="" self.registeredDbs=[] def setProfile(self,p): """setta il profilo utente, cioe' l'insieme di funzioni disponibili per l'utente @param {string:Function}::{codice identificativo della funzione:oggetto funzione} """ self.profile=p def getProfile(self): """ riorna il profilo utente, cioe' l'insieme di funzioni disponibili per l'utente @return: {string:Function}::{codice identificativo della funzione:oggetto funzione} """ return self.profile def setZone(self,p): """setta la zona utente, cioe' l'insieme di aree di competenza dell'utente @param {string:Nodo}::{codice identificativo dell'area geografica:Nodo} """ self.zone=p def getZone(self): """ riorna la zona utente, cioe' l'insieme di aree di competenza dell'utente @return: {string:Nodo}::{codice identificativo della funzione:Nodo} """ return self.zone def getLogo(self): return self.logo def setLogo(self,l): self.logo=l def getPassword(self): return self.pwd def setPassword(self,p): self.pwd=p def getRegisteredDb(self): return self.registeredDbs def setRegisteredDb(self,l): self.registeredDbs=l def isLogged(self): return self.logged def setLogged(self,b): self.logged=b def getSettingsName(self): """ ritorna il nome con cui viene identificato da Datasource nel sistema @return: string """ return self.qsettingsName def setSettingsName(self,n): """ setta il nome che identifica l'utente in DataSource @param string: """ self.qsettingsName=n def setLoggingTime(self,t): """ setta il loggingtime per l'utente @param datetime.datetime: tempo attuale come ottenuto da datetime.datetime.now() """ self.loggingTime=t def getLoggingTime(self): """ ritorna il loggingTime @return: datetime.datetime """ return self.loggingTime class USER(): """ implementa il concetto di utente loggato con i db ad esso registrati e il logo aziendale da usare nell'esprtazione in pdf """ def __init__(self,uname,Id): self.name=uname self.Id=Id self.logo=None self.logged=False self.loggingTime="" self.qsettingsName="" self.profile=Profile({}) self.zone=Zone({}) self.dbs=DbSet({}) self.pwd="" self.activeDb=None self.registeredDbs=[] def getDbs(self,object=False): """ ritorna il dict dei db registrati @param bool: facoltativo se True ritorna le istanze deidbs registrati @return: <{string:None}::{Db.qName:None}><{string:Db}::{Db.qName:Db} """ l=lambda k,b:self.dbs[k] if b==True else None db={} if type(self.dbs)==type(1): #utente root db=self.dbs else: for k in self.dbs.iterkeys(): db[k]=l(k,object) return db def setName(self,n): self.name=n def setPassword(self,p): self.pwd=p def getPassword(self): return self.pwd def setProfile(self,p): """setta il profilo utente, cioe' l'insieme di funzioni disponibili per l'utente @param {string:Function}::{codice identificativo della funzione:oggetto funzione} """ self.profile=p def getProfile(self): """ riorna il profilo utente, cioe' l'insieme di funzioni disponibili per l'utente @return: {string:Function}::{codice identificativo della funzione:oggetto funzione} """ return self.profile def setZone(self,p): """setta la zona utente, cioe' l'insieme di aree di competenza dell'utente @param {string:Nodo}::{codice identificativo dell'area geografica:Nodo} """ self.zone=p def getZone(self): """ riorna la zona utente, cioe' l'insieme di aree di competenza dell'utente @return: {string:Nodo}::{codice identificativo della funzione:Nodo} """ return self.zone def getLogo(self): return self.logo def setLogo(self,l): self.logo=l def getSettingsName(self): """ ritorna il nome con cui viene identificato da Datasource nel sistema @return: string """ return self.qsettingsName def setSettingsName(self,n): """ setta il nome che identifica l'utente in DataSource @param string: """ self.qsettingsName=n def setLoggingTime(self,t): """ setta il loggingtime per l'utente @param datetime.datetime: tempo attuale come ottenuto da datetime.datetime.now() """ self.loggingTime=t def getLoggingTime(self): """ ritorna il loggingTime @return: datetime.datetime """ return self.loggingTime def isLogged(self): """ritorna lo stato dell'utente se loggato e' True @return: bool """ return self.logged def setLogged(self,b): """setta il parametro logged @param bool: """ self.logged=b def getName(self): """ritorna lo user name @return: string """ return self.name def getId(self): """ritorna lo id utente @return: int """ return self.Id def getRegisteredDb(self): """ritorna la lista dei db registrati per l'utente @return: [Db] """ return self.registeredDbs def setRegisteredDb(self,l): """ setta la lista dei db registrati @param [DB]: """ self.registeredDbs=l def getActiveDb(self): """ritorna il db attivo dell'utente @return: DB """ return self.activeDb def setActiveDb(self,db): """setta il db attivo,solo un db alla volta puo' essere attivo @param Db: db attivo """ self.activeDb=Db def __repr__(self): l=lambda x: "autenticato"if x else "non autenticato" txt="User: {0}, Id:{1} {2}".format(self.name,self.Id,l(self.logged)) for i in self.registeredDbs: txt+="\d {0}".format(i) return txt class Db(): def getSettingsName(self): """ ritorna il nome con cui viene identificato da Datasource nel sistema @return: string """ return self.qsettingsName def setSettingsName(self,n): """ setta il nome che identifica l'utente in DataSource @param string: """ self.qsettingsName=n def getConnectionString(self): """ritorna la stringa di connessione per sqlalchemy il formato dela stringa e' user:pwd@host/db @return: string """ "root:vilu7240@localhost/parafarmacie" str="{0}:{1}@{2}:{3}/{4}".format(self.user_name,self.password,self.host,self.port,self.censimento) return str def getConnectionStringMMasgisDB(self): """ritorna la stringa di connessione per sqlalchemy il formato dela stringa e' user:pwd@host/db @return: string """ "root:vilu7240@localhost/parafarmacie" str="{0}:{1}@{2}:{3}/{4}".format(self.user_name,self.password,self.host,self.port,"mmasgisDB") return str def mysqlConnect(self): return self.cons.dbDrivers[str(self.getRDBMS())].connect(host=self.getHost(), user=self.getUserName(), passwd=self.getPassword(),db=self.getNameDb(),charset="utf8",use_unicode=True) def mysqlConnect2Metmi(self): return self.cons.dbDrivers[str(self.getRDBMS())].connect(host=self.getHost(), user="metmi", passwd='metmi',db='mmasgisDB',charset="utf8",use_unicode=True) def pgConnect(self): #print "pg connection string","host='{0}' user='{1}' password='{2}' dbname='{3}'".format(self.getHost(),self.getUserName(),self.getPassword(),self.getNameDb()) conn= self.cons.dbDrivers[str(self.getRDBMS())].connect("host='{0}' user='{1}' password='{2}' dbname='{3}'".format(self.getHost(),self.getUserName(),self.getPassword(),self.getNameDb())) return conn def pgConnect2Metmi(self): #print "pg connection string","host='{0}' user='{1}' password='{2}' dbname='{3}'".format(self.getHost(),self.getUserName(),self.getPassword(),self.getNameDb()) conn= self.cons.dbDrivers[str(self.getRDBMS())].connect("host='{0}' user='{1}' password='{2}' dbname='{3}'".format(self.getHost(),'metmi','metmi','mmasgisDB')) return conn def parser(self,txt,pattern): #print "text in parser",txt match=re.compile(pattern) return match.findall(txt) def __init__(self,dbName,Id,descrizione="",user_name="",pwd="",host="",rdbms=""): """" @param string: nome del db @param string:descrizione opzionale @param string:user name opzionale @param string: passwordopzionale @param string: host opzionale @param string: famiglia db<mysql><postgres> ... opzionale """ self.certificato=-1 self.pv_mt=-1 self.cons=cons() self.qName="" self.category="db" self.name=dbName self.port=-1 self.descrizione=descrizione self.user_name=user_name self.host=host self.company=-1 self.password=pwd self.rdbms=rdbms self.censimento="" self.versione="" self.ins_data="" self.mod_data="" self.ins_utente="" self.mod_utente="" self.azienda_id="" #print "id da parser",lId[0][0] self.Id=Id self.active=False def getCertificato(self): return self.certificato def setCertificato(self,c): """ @param int: """ self.certificato=c def setPv_mt(self,p): """ @param int: """ self.pv_mt=p def getPv_mt(self): """ ritorna il parametro pv_mt, che indica se occorre fare query su anagrafiche certificate """ return self.pv_mt def setPort(self,p): self.port=p def getPort(self): return self.port def setCompany(self,c): self.company=c def getCompany(self): return self.company def setCensimento(self,c): self.censimento=c def getCategory(self): """ ritorna lacategoria della classe, @note: questometodo e' dummy e' inserito per rendere la classe Db consistente con Function per CheckFactory in settings.py @return: string "db" """ return self.category def getCensimento(self): return self.censimento def setVersione(self,v): self.versione=v def getVersione(self): return self.versione def setIns_data(self,i): self.ins_data=i def getIns_data(self): return self.ins_data def setMod_data(self,m): self.mod_data=m def getMod_data(self): return self.mod_data def setIns_utente(self,i): self.ins_utente=i def getIns_utente(self): return self.ins_utente def getMod_utente(self): return self.mod_utente def setMod_utente(self,m): self.mod_utente=m def getQname(self): return self.qName def setQname(self,q): self.qName=q def getConnection(self): connectFunctions={} connectFunctions['mysql']=self.mysqlConnect connectFunctions['postgresql']=self.pgConnect return connectFunctions[self.rdbms]() def getConnectionMMASGISDB(self): connectFunctions={} connectFunctions['mysql']=self.mysqlConnect2Metmi connectFunctions['postgresql']=self.pgConnect2Metmi #print "rdbms in sessionClasses:",self.rdbms return connectFunctions[str(self.rdbms)]() def getConnection2Metmi(self): connectFunctions={} connectFunctions['mysql']=self.mysqlConnect2Metmi connectFunctions['postgres']=self.pgConnect2Metmi #print "rdbms in sessionClasses:",self.rdbms return connectFunctions[str(self.rdbms)]() def getUserName(self): """ritorna lo user_name del db da usare nella connectionString @return: string """ return self.user_name def getPassword(self): """ritorna la password di accesso al db @return: string """ return self.password def isActive(self): """getter per self.active @return: bool """ return self.active def setHost(self,h): self.host=h def getHeader(self): return self.name def getNameDb(self): return self.name def setRDBMS(self,r): self.rdbms=r def getRDBMS(self): return self.rdbms def setNameDb(self,db): self.name=db def setUserName(self,u): self.user_name=u def setPassword(self,p): self.password=p def getHost(self): return self.host def setDescrizione(self,d): self.descrizione=d def getSDescrizione(self): return self.descrizione def setId(self,Id): self.Id=Id def setActive(self,b): """setter per self.active @param bool: """ self.active=b def getDescription(self): """ ritorna la descizione che accompagna il db nella finestra di log-censimento @return: string """ return self.descrizione def getId(self): """ritorna lo id del db @return: int """ return self.Id def __repr__(self): l=lambda x: "active" if x else 'not active' return "DB "+l(self.active)+" : rdbms:{0}, nome:{1}, descrizione:{2}, host:{3},id:{4}, port: {5}".format(self.rdbms,self.name,self.descrizione,self.host,self.Id,self.port) class Profile_standard(Profile): def __init__(self,role={}): Profile.__init__(self, role) self.name="" self.company=None self.Id=-1 def setCompany(self,c): self.company=c def getCompany(self): return self.company def isAdministrator(self): return type(self.profile)==type(1) def getMapper(self,session): """produce gli oggetti sqlalchemy da essere salvati sul db @param sqlalchemy.session: sessione attiva col db @return: (sqlachemy.profilo_std,[sqlalchemy.rel_profilo_funzioni]) """ p=profilo_std() p.amministratore=self.isAdministrator() p.nome_profilo=self.name p.azienda_id=self.company session.add(p) session.flush() session.refresh(p) l=lambda x:0 if x is None else x Id=l(session.query(func.max(profilo_std.profilo_id)).first()[0])+1 fList=[] if not p.amministratore:#il profilo e' un dict for i in self.profile.iterkeys(): r=rel_profilo_funzioni() r.profilo_id=Id r.funzione_id=i fList.append(r) return (p,fList) def addElement(self,k,v): """aggiunge una funzione abilitata al profilo @param object:id della funzione @param object: in genere Function """ if type(self.profile)==type(4): pass#e' un profilo amministratore non ha bisogno di nulla else: self.profile[k]=v def getName(self): return self.name def setName(self,n): self.name=n def getId(self): return self.Id def setId(self,i): self.Id=i
mit
-2,327,181,510,416,719,400
23.748629
188
0.682622
false
alanjw/GreenOpenERP-Win-X86
python/Lib/distutils/tests/test_archive_util.py
3
11399
# -*- coding: utf-8 -*- """Tests for distutils.archive_util.""" __revision__ = "$Id$" import unittest import os import sys import tarfile from os.path import splitdrive import warnings from distutils.archive_util import (check_archive_formats, make_tarball, make_zipfile, make_archive, ARCHIVE_FORMATS) from distutils.spawn import find_executable, spawn from distutils.tests import support from test.test_support import check_warnings, run_unittest try: import grp import pwd UID_GID_SUPPORT = True except ImportError: UID_GID_SUPPORT = False try: import zipfile ZIP_SUPPORT = True except ImportError: ZIP_SUPPORT = find_executable('zip') # some tests will fail if zlib is not available try: import zlib except ImportError: zlib = None def can_fs_encode(filename): """ Return True if the filename can be saved in the file system. """ if os.path.supports_unicode_filenames: return True try: filename.encode(sys.getfilesystemencoding()) except UnicodeEncodeError: return False return True class ArchiveUtilTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): @unittest.skipUnless(zlib, "requires zlib") def test_make_tarball(self): self._make_tarball('archive') def _make_tarball(self, target_name): # creating something to tar tmpdir = self.mkdtemp() self.write_file([tmpdir, 'file1'], 'xxx') self.write_file([tmpdir, 'file2'], 'xxx') os.mkdir(os.path.join(tmpdir, 'sub')) self.write_file([tmpdir, 'sub', 'file3'], 'xxx') tmpdir2 = self.mkdtemp() unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0], "source and target should be on same drive") base_name = os.path.join(tmpdir2, target_name) # working with relative paths to avoid tar warnings old_dir = os.getcwd() os.chdir(tmpdir) try: make_tarball(splitdrive(base_name)[1], '.') finally: os.chdir(old_dir) # check if the compressed tarball was created tarball = base_name + '.tar.gz' self.assertTrue(os.path.exists(tarball)) # trying an uncompressed one base_name = os.path.join(tmpdir2, target_name) old_dir = os.getcwd() os.chdir(tmpdir) try: make_tarball(splitdrive(base_name)[1], '.', compress=None) finally: os.chdir(old_dir) tarball = base_name + '.tar' self.assertTrue(os.path.exists(tarball)) def _tarinfo(self, path): tar = tarfile.open(path) try: names = tar.getnames() names.sort() return tuple(names) finally: tar.close() def _create_files(self): # creating something to tar tmpdir = self.mkdtemp() dist = os.path.join(tmpdir, 'dist') os.mkdir(dist) self.write_file([dist, 'file1'], 'xxx') self.write_file([dist, 'file2'], 'xxx') os.mkdir(os.path.join(dist, 'sub')) self.write_file([dist, 'sub', 'file3'], 'xxx') os.mkdir(os.path.join(dist, 'sub2')) tmpdir2 = self.mkdtemp() base_name = os.path.join(tmpdir2, 'archive') return tmpdir, tmpdir2, base_name @unittest.skipUnless(zlib, "Requires zlib") @unittest.skipUnless(find_executable('tar') and find_executable('gzip'), 'Need the tar command to run') def test_tarfile_vs_tar(self): tmpdir, tmpdir2, base_name = self._create_files() old_dir = os.getcwd() os.chdir(tmpdir) try: make_tarball(base_name, 'dist') finally: os.chdir(old_dir) # check if the compressed tarball was created tarball = base_name + '.tar.gz' self.assertTrue(os.path.exists(tarball)) # now create another tarball using `tar` tarball2 = os.path.join(tmpdir, 'archive2.tar.gz') tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist'] gzip_cmd = ['gzip', '-f9', 'archive2.tar'] old_dir = os.getcwd() os.chdir(tmpdir) try: spawn(tar_cmd) spawn(gzip_cmd) finally: os.chdir(old_dir) self.assertTrue(os.path.exists(tarball2)) # let's compare both tarballs self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2)) # trying an uncompressed one base_name = os.path.join(tmpdir2, 'archive') old_dir = os.getcwd() os.chdir(tmpdir) try: make_tarball(base_name, 'dist', compress=None) finally: os.chdir(old_dir) tarball = base_name + '.tar' self.assertTrue(os.path.exists(tarball)) # now for a dry_run base_name = os.path.join(tmpdir2, 'archive') old_dir = os.getcwd() os.chdir(tmpdir) try: make_tarball(base_name, 'dist', compress=None, dry_run=True) finally: os.chdir(old_dir) tarball = base_name + '.tar' self.assertTrue(os.path.exists(tarball)) @unittest.skipUnless(find_executable('compress'), 'The compress program is required') def test_compress_deprecated(self): tmpdir, tmpdir2, base_name = self._create_files() # using compress and testing the PendingDeprecationWarning old_dir = os.getcwd() os.chdir(tmpdir) try: with check_warnings() as w: warnings.simplefilter("always") make_tarball(base_name, 'dist', compress='compress') finally: os.chdir(old_dir) tarball = base_name + '.tar.Z' self.assertTrue(os.path.exists(tarball)) self.assertEqual(len(w.warnings), 1) # same test with dry_run os.remove(tarball) old_dir = os.getcwd() os.chdir(tmpdir) try: with check_warnings() as w: warnings.simplefilter("always") make_tarball(base_name, 'dist', compress='compress', dry_run=True) finally: os.chdir(old_dir) self.assertTrue(not os.path.exists(tarball)) self.assertEqual(len(w.warnings), 1) @unittest.skipUnless(zlib, "Requires zlib") @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run') def test_make_zipfile(self): # creating something to tar tmpdir = self.mkdtemp() self.write_file([tmpdir, 'file1'], 'xxx') self.write_file([tmpdir, 'file2'], 'xxx') tmpdir2 = self.mkdtemp() base_name = os.path.join(tmpdir2, 'archive') make_zipfile(base_name, tmpdir) # check if the compressed tarball was created tarball = base_name + '.zip' def test_check_archive_formats(self): self.assertEqual(check_archive_formats(['gztar', 'xxx', 'zip']), 'xxx') self.assertEqual(check_archive_formats(['gztar', 'zip']), None) def test_make_archive(self): tmpdir = self.mkdtemp() base_name = os.path.join(tmpdir, 'archive') self.assertRaises(ValueError, make_archive, base_name, 'xxx') @unittest.skipUnless(zlib, "Requires zlib") def test_make_archive_owner_group(self): # testing make_archive with owner and group, with various combinations # this works even if there's not gid/uid support if UID_GID_SUPPORT: group = grp.getgrgid(0)[0] owner = pwd.getpwuid(0)[0] else: group = owner = 'root' base_dir, root_dir, base_name = self._create_files() base_name = os.path.join(self.mkdtemp() , 'archive') res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner, group=group) self.assertTrue(os.path.exists(res)) res = make_archive(base_name, 'zip', root_dir, base_dir) self.assertTrue(os.path.exists(res)) res = make_archive(base_name, 'tar', root_dir, base_dir, owner=owner, group=group) self.assertTrue(os.path.exists(res)) res = make_archive(base_name, 'tar', root_dir, base_dir, owner='kjhkjhkjg', group='oihohoh') self.assertTrue(os.path.exists(res)) @unittest.skipUnless(zlib, "Requires zlib") @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support") def test_tarfile_root_owner(self): tmpdir, tmpdir2, base_name = self._create_files() old_dir = os.getcwd() os.chdir(tmpdir) group = grp.getgrgid(0)[0] owner = pwd.getpwuid(0)[0] try: archive_name = make_tarball(base_name, 'dist', compress=None, owner=owner, group=group) finally: os.chdir(old_dir) # check if the compressed tarball was created self.assertTrue(os.path.exists(archive_name)) # now checks the rights archive = tarfile.open(archive_name) try: for member in archive.getmembers(): self.assertEqual(member.uid, 0) self.assertEqual(member.gid, 0) finally: archive.close() def test_make_archive_cwd(self): current_dir = os.getcwd() def _breaks(*args, **kw): raise RuntimeError() ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file') try: try: make_archive('xxx', 'xxx', root_dir=self.mkdtemp()) except: pass self.assertEqual(os.getcwd(), current_dir) finally: del ARCHIVE_FORMATS['xxx'] @unittest.skipUnless(zlib, "requires zlib") def test_make_tarball_unicode(self): """ Mirror test_make_tarball, except filename is unicode. """ self._make_tarball(u'archive') @unittest.skipUnless(zlib, "requires zlib") @unittest.skipUnless(can_fs_encode(u'årchiv'), 'File system cannot handle this filename') def test_make_tarball_unicode_latin1(self): """ Mirror test_make_tarball, except filename is unicode and contains latin characters. """ self._make_tarball(u'årchiv') # note this isn't a real word @unittest.skipUnless(zlib, "requires zlib") @unittest.skipUnless(can_fs_encode(u'のアーカイブ'), 'File system cannot handle this filename') def test_make_tarball_unicode_extended(self): """ Mirror test_make_tarball, except filename is unicode and contains characters outside the latin charset. """ self._make_tarball(u'のアーカイブ') # japanese for archive def test_suite(): return unittest.makeSuite(ArchiveUtilTestCase) if __name__ == "__main__": run_unittest(test_suite())
agpl-3.0
-7,016,192,764,976,045,000
32.67378
78
0.562209
false
drawks/ansible
lib/ansible/plugins/lookup/_redis_kv.py
31
3050
# (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ lookup: redis_kv author: Jan-Piet Mens <jpmens(at)gmail.com> version_added: "0.9" short_description: fetch data from Redis deprecated: why: This lookup uses options intermingled with terms which blurs the interface between settings and data version: '2.9' alternative: new 'redis' lookup description: - this lookup returns a list of items given to it, if any of the top level items is also a list it will flatten it, but it will not recurse requirements: - redis (python library https://github.com/andymccurdy/redis-py/) options: _terms: description: Two element comma separated strings composed of url of the Redis server and key to query options: _url: description: location of redis host in url format default: 'redis://localhost:6379' _key: description: key to query required: True """ EXAMPLES = """ - name: query redis for somekey debug: msg="{{ lookup('redis_kv', 'redis://localhost:6379,somekey') }} is value in Redis for somekey" """ RETURN = """ _raw: description: values stored in Redis """ import os import re HAVE_REDIS = False try: import redis HAVE_REDIS = True except ImportError: pass from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase # ============================================================== # REDISGET: Obtain value from a GET on a Redis key. Terms # expected: 0 = URL, 1 = Key # URL may be empty, in which case redis://localhost:6379 assumed # -------------------------------------------------------------- class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): if not HAVE_REDIS: raise AnsibleError("Can't LOOKUP(redis_kv): module redis is not installed") ret = [] for term in terms: (url, key) = term.split(',') if url == "": url = 'redis://localhost:6379' # urlsplit on Python 2.6.1 is broken. Hmm. Probably also the reason # Redis' from_url() doesn't work here. p = '(?P<scheme>[^:]+)://?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' try: m = re.search(p, url) host = m.group('host') port = int(m.group('port')) except AttributeError: raise AnsibleError("Bad URI in redis lookup") try: conn = redis.Redis(host=host, port=port) res = conn.get(key) if res is None: res = "" ret.append(res) except Exception: ret.append("") # connection failed or key not found return ret
gpl-3.0
-7,896,204,507,531,317,000
31.795699
145
0.568525
false
sunny-wyb/xen-4.1.2
tools/python/build/lib.linux-x86_64-2.7/xen/xend/XendOptions.py
19
21030
#============================================================================ # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #============================================================================ # Copyright (C) 2004, 2005 Mike Wray <[email protected]> # Copyright (C) 2005 XenSource Ltd #============================================================================ """Xend root class. Creates the servers and handles configuration. Other classes get config variables by importing this module, using instance() to get a XendOptions instance, and then the config functions (e.g. get_xend_port()) to get configured values. """ import os import os.path import string import sys from xen.xend import sxp, osdep, XendLogging from xen.xend.XendError import XendError from xen.util import auxbin if os.uname()[0] == 'SunOS': from xen.lowlevel import scf class XendOptions: """Configuration options.""" """Where network control scripts live.""" network_script_dir = auxbin.scripts_dir() """Where block control scripts live.""" block_script_dir = auxbin.scripts_dir() """Default path to the log file. """ logfile_default = "/var/log/xen/xend.log" """Default level of information to be logged.""" loglevel_default = 'DEBUG' """Default Xen-API server configuration. """ xen_api_server_default = [['unix']] """Default for the flag indicating whether xend should run an http server (deprecated).""" xend_http_server_default = 'no' xend_tcp_xmlrpc_server_default = 'no' xend_tcp_xmlrpc_server_address_default = 'localhost' xend_tcp_xmlrpc_server_port_default = 8006 xend_unix_xmlrpc_server_default = 'yes' """Default interface address xend listens at. """ xend_address_default = '' """Default for the flag indicating whether xend should run a relocation server.""" xend_relocation_server_default = 'no' """Default for the flag indicating whether xend should run a ssl relocation server.""" xend_relocation_ssl_server_default = 'no' """Default for the flag indicating whether xend should run a udev event server.""" xend_udev_event_server_default = 'no' """Default interface address the xend relocation server listens at. """ xend_relocation_address_default = '' """Default port xend serves HTTP at. """ xend_port_default = 8000 """Default port xend serves relocation at. """ xend_relocation_port_default = 8002 """Default port xend serves ssl relocation at. """ xend_relocation_ssl_port_default = 8003 xend_relocation_hosts_allow_default = '' """Default for the flag indicating whether xend should run a unix-domain server (deprecated).""" xend_unix_server_default = 'no' """Default external migration tool """ external_migration_tool_default = '' """Default path the unix-domain server listens at.""" xend_unix_path_default = '/var/lib/xend/xend-socket' dom0_min_mem_default = 0 reserved_memory_default = 0 dom0_vcpus_default = 0 vncpasswd_default = None """Default interface to listen for VNC connections on""" xend_vnc_listen_default = '127.0.0.1' """Use of TLS mode in QEMU VNC server""" xend_vnc_tls = 0 """x509 certificate directory for QEMU VNC server""" xend_vnc_x509_cert_dir = auxbin.xen_configdir() + "/vnc" """Verify incoming client x509 certs""" xend_vnc_x509_verify = 0 """Default session storage path.""" xend_domains_path_default = '/var/lib/xend/domains' """Default xend management state storage.""" xend_state_path_default = '/var/lib/xend/state' """Default xend QCoW storage repository location.""" xend_storage_path_default = '/var/lib/xend/storage' """Default xend security state storage path.""" xend_security_path_default = '/var/lib/xend/security' """Default script to configure a backend network interface""" vif_script = osdep.vif_script """Default Xen Security Module""" xsm_module_default = 'dummy' """Default rotation count of qemu-dm log file.""" qemu_dm_logrotate_count = 10 """Default timeout for device creation.""" device_create_timeout_default = 100 """Default timeout for device destruction.""" device_destroy_timeout_default = 100 """By default, we use the strict check for HVM guest. (For PV guest, we use loose check automatically if necessary.""" pci_dev_assign_strict_check_default = True def __init__(self): self.configure() def _logError(self, fmt, *args): """Logging function to log to stderr. We use this for XendOptions log messages because they may be logged before the logger has been configured. Other components can safely use the logger. """ print >>sys.stderr, "xend [ERROR]", fmt % args """Default mask for pscsi device scan.""" xend_pscsi_device_mask = ['*'] def configure(self): self.set_config() XendLogging.init(self.get_config_string("logfile", self.logfile_default), self.get_config_string("loglevel", self.loglevel_default)) def set_config(self): raise NotImplementedError() def get_config_bool(self, name, val=None): raise NotImplementedError() def get_config_int(self, name, val=None): raise NotImplementedError() def get_config_string(self, name, val=None): raise NotImplementedError() def get_xen_api_server(self): raise NotImplementedError() def get_xend_http_server(self): """Get the flag indicating whether xend should run an http server. """ return self.get_config_bool("xend-http-server", self.xend_http_server_default) def get_xend_tcp_xmlrpc_server(self): return self.get_config_bool("xend-tcp-xmlrpc-server", self.xend_tcp_xmlrpc_server_default) def get_xend_tcp_xmlrpc_server_port(self): return self.get_config_int("xend-tcp-xmlrpc-server-port", self.xend_tcp_xmlrpc_server_port_default) def get_xend_tcp_xmlrpc_server_address(self): return self.get_config_string("xend-tcp-xmlrpc-server-address", self.xend_tcp_xmlrpc_server_address_default) def get_xend_tcp_xmlrpc_server_ssl_key_file(self): name = 'xend-tcp-xmlrpc-server-ssl-key-file' file = self.get_config_string(name) if file and os.path.dirname(file) == "": file = auxbin.xen_configdir() + '/' + file; if file and not os.path.exists(file): raise XendError("invalid xend config %s: directory '%s' does not exist" % (name, file)) return file def get_xend_tcp_xmlrpc_server_ssl_cert_file(self): name = 'xend-tcp-xmlrpc-server-ssl-cert-file' file = self.get_config_string(name) if file and os.path.dirname(file) == "": file = auxbin.xen_configdir() + '/' + file; if file and not os.path.exists(file): raise XendError("invalid xend config %s: directory '%s' does not exist" % (name, file)) return file def get_xend_unix_xmlrpc_server(self): return self.get_config_bool("xend-unix-xmlrpc-server", self.xend_unix_xmlrpc_server_default) def get_xend_relocation_server(self): """Get the flag indicating whether xend should run a relocation server. """ return self.get_config_bool("xend-relocation-server", self.xend_relocation_server_default) def get_xend_relocation_ssl_server(self): """Get the flag indicating whether xend should run a ssl relocation server. """ return self.get_config_bool("xend-relocation-ssl-server", self.xend_relocation_ssl_server_default) def get_xend_relocation_server_ssl_key_file(self): name = 'xend-relocation-server-ssl-key-file' file = self.get_config_string(name) if os.path.dirname(file) == "": file = auxbin.xen_configdir() + '/' + file; if not os.path.exists(file): raise XendError("invalid xend config %s: directory '%s' does not exist" % (name, file)) return file def get_xend_relocation_server_ssl_cert_file(self): name = 'xend-relocation-server-ssl-cert-file' file = self.get_config_string(name) if os.path.dirname(file) == "": file = auxbin.xen_configdir() + '/' + file; if not os.path.exists(file): raise XendError("invalid xend config %s: directory '%s' does not exist" % (name, file)) return file def get_xend_udev_event_server(self): return self.get_config_bool("xend-udev-event-server", self.xend_udev_event_server_default) def get_xend_port(self): """Get the port xend listens at for its HTTP interface. """ return self.get_config_int('xend-port', self.xend_port_default) def get_xend_relocation_port(self): """Get the port xend listens at for connection to its relocation server. """ return self.get_config_int('xend-relocation-port', self.xend_relocation_port_default) def get_xend_relocation_ssl_port(self): """Get the port xend listens at for ssl connection to its relocation server. """ return self.get_config_int('xend-relocation-ssl-port', self.xend_relocation_ssl_port_default) def get_xend_relocation_ssl(self): """Whether to use ssl when relocating. """ return self.get_config_bool('xend-relocation-ssl', 'no') def get_xend_relocation_hosts_allow(self): return self.get_config_string("xend-relocation-hosts-allow", self.xend_relocation_hosts_allow_default) def get_xend_address(self): """Get the address xend listens at for its HTTP port. This defaults to the empty string which allows all hosts to connect. If this is set to 'localhost' only the localhost will be able to connect to the HTTP port. """ return self.get_config_string('xend-address', self.xend_address_default) def get_xend_relocation_address(self): """Get the address xend listens at for its relocation server port. This defaults to the empty string which allows all hosts to connect. If this is set to 'localhost' only the localhost will be able to connect to the relocation port. """ return self.get_config_string('xend-relocation-address', self.xend_relocation_address_default) def get_xend_unix_server(self): """Get the flag indicating whether xend should run a unix-domain server. """ return self.get_config_bool("xend-unix-server", self.xend_unix_server_default) def get_xend_unix_path(self): """Get the path the xend unix-domain server listens at. """ return self.get_config_string("xend-unix-path", self.xend_unix_path_default) def get_xend_domains_path(self): """ Get the path for persistent domain configuration storage """ return self.get_config_string("xend-domains-path", self.xend_domains_path_default) def get_xend_state_path(self): """ Get the path for persistent domain configuration storage """ return self.get_config_string("xend-state-path", self.xend_state_path_default) def get_xend_storage_path(self): """ Get the path for persistent domain configuration storage """ return self.get_config_string("xend-storage-path", self.xend_storage_path_default) def get_xend_security_path(self): """ Get the path for security state """ return self.get_config_string("xend-security-path", self.xend_security_path_default) def get_network_script(self): """@return the script used to alter the network configuration when Xend starts and stops, or None if no such script is specified.""" s = self.get_config_string('network-script') if s: result = s.split(" ") result[0] = os.path.join(self.network_script_dir, result[0]) return result else: return None def get_external_migration_tool(self): """@return the name of the tool to handle virtual TPM migration.""" return self.get_config_string('external-migration-tool', self.external_migration_tool_default) def get_enable_dump(self): return self.get_config_bool('enable-dump', 'no') def get_vif_script(self): return self.get_config_string('vif-script', self.vif_script) def get_dom0_min_mem(self): return self.get_config_int('dom0-min-mem', self.dom0_min_mem_default) def get_enable_dom0_ballooning(self): enable_dom0_ballooning_default = 'yes' if self.get_dom0_min_mem() == 0: enable_dom0_ballooning_default = 'no' return self.get_config_bool('enable-dom0-ballooning', enable_dom0_ballooning_default) def get_reserved_memory(self): if not self.get_enable_dom0_ballooning(): return 0 #no ballooning of dom0 will close this item else: return self.get_config_int('total_available_memory', self.reserved_memory_default) def get_dom0_vcpus(self): return self.get_config_int('dom0-cpus', self.dom0_vcpus_default) def get_console_limit(self): return self.get_config_int('console-limit', 1024) def get_vnclisten_address(self): return self.get_config_string('vnc-listen', self.xend_vnc_listen_default) def get_vncpasswd_default(self): return self.get_config_string('vncpasswd', self.vncpasswd_default) def get_keymap(self): return self.get_config_string('keymap', None) def get_resource_label_change_script(self): s = self.get_config_string('resource-label-change-script') if s: result = s.split(" ") result[0] = os.path.join(auxbin.scripts_dir(), result[0]) return result else: return None def get_vnc_tls(self): return self.get_config_string('vnc-tls', self.xend_vnc_tls) def get_vnc_x509_cert_dir(self): name = 'vnc-x509-cert-dir' vncdir = self.get_config_string(name, self.xend_vnc_x509_cert_dir) if os.path.dirname(vncdir) == "": vncdir = auxbin.xen_configdir() + '/' + vncdir if not os.path.exists(vncdir): raise XendError("invalid xend config %s: directory '%s' does not exist" % (name, vncdir)) return vncdir def get_vnc_x509_verify(self): return self.get_config_string('vnc-x509-verify', self.xend_vnc_x509_verify) def get_qemu_dm_logrotate_count(self): return self.get_config_int("qemu-dm-logrotate-count", self.qemu_dm_logrotate_count) def get_device_create_timeout(self): return self.get_config_int("device-create-timeout", self.device_create_timeout_default) def get_device_destroy_timeout(self): return self.get_config_int("device-destroy-timeout", self.device_destroy_timeout_default) def get_pci_dev_assign_strict_check(self): return self.get_config_bool("pci-passthrough-strict-check", self.pci_dev_assign_strict_check_default) def get_pscsi_device_mask(self): return self.get_config_value("pscsi-device-mask", self.xend_pscsi_device_mask) class XendOptionsFile(XendOptions): """Default path to the config file.""" config_default = auxbin.xen_configdir() + "/xend-config.sxp" """Environment variable used to override config_default.""" config_var = "XEND_CONFIG" def set_config(self): """If the config file exists, read it. If not, ignore it. The config file is a sequence of sxp forms. """ self.config_path = os.getenv(self.config_var, self.config_default) if os.path.exists(self.config_path): try: fin = file(self.config_path, 'rb') try: config = sxp.parse(fin) finally: fin.close() if config is None: config = ['xend-config'] else: config.insert(0, 'xend-config') self.config = config except Exception, ex: self._logError('Reading config file %s: %s', self.config_path, str(ex)) raise else: self._logError('Config file does not exist: %s', self.config_path) self.config = ['xend-config'] def get_config_value(self, name, val=None): """Get the value of an atomic configuration element. @param name: element name @param val: default value (optional, defaults to None) @return: value """ return sxp.child_value(self.config, name, val=val) def get_config_bool(self, name, val=None): v = string.lower(str(self.get_config_value(name, val))) if v in ['yes', 'y', '1', 'on', 'true', 't']: return True if v in ['no', 'n', '0', 'off', 'false', 'f']: return False raise XendError("invalid xend config %s: expected bool: %s" % (name, v)) def get_config_int(self, name, val=None): v = self.get_config_value(name, val) try: return int(v) except Exception: raise XendError("invalid xend config %s: expected int: %s" % (name, v)) def get_config_string(self, name, val=None): return self.get_config_value(name, val) def get_xen_api_server(self): """Get the Xen-API server configuration. """ return self.get_config_value('xen-api-server', self.xen_api_server_default) def get_xsm_module_name(self): """Get the Xen Security Module name. """ return self.get_config_string('xsm_module_name', self.xsm_module_default) if os.uname()[0] == 'SunOS': class XendOptionsSMF(XendOptions): def set_config(self): pass def get_config_bool(self, name, val=None): try: return scf.get_bool(name) except scf.error, e: if e[0] == scf.SCF_ERROR_NOT_FOUND: if val in ['yes', 'y', '1', 'on', 'true', 't']: return True if val in ['no', 'n', '0', 'off', 'false', 'f']: return False return val else: raise XendError("option %s: %s:%s" % (name, e[1], e[2])) def get_config_int(self, name, val=None): try: return scf.get_int(name) except scf.error, e: if e[0] == scf.SCF_ERROR_NOT_FOUND: return val else: raise XendError("option %s: %s:%s" % (name, e[1], e[2])) def get_config_string(self, name, val=None): try: return scf.get_string(name) except scf.error, e: if e[0] == scf.SCF_ERROR_NOT_FOUND: return val else: raise XendError("option %s: %s:%s" % (name, e[1], e[2])) def get_xen_api_server(self): # When the new server is a supported configuration, we should # expand this. return [["unix"]] def instance(): """Get an instance of XendOptions. Use this instead of the constructor. """ global inst try: inst except: if os.uname()[0] == 'SunOS': inst = XendOptionsSMF() else: inst = XendOptionsFile() return inst
gpl-2.0
1,331,049,694,321,367,000
36.089947
102
0.595625
false
Z2Y/CUIT-ACM-Website
config.py
1
3878
# coding=utf-8 #The database URI that should be used for the connection. #fomate: dialect+driver://username:password@host:port/database #mysql format : mysql://scott:tiger@localhost/database_name SQLALCHEMY_DATABASE_URI = 'mysql://root:63005610@localhost/cuit_acm' #A dictionary that maps bind keys to SQLAlchemy connection URIs. SQLALCHEMY_BINDS = {} SQLALCHEMY_TRACK_MODIFICATIONS = True ADMIN = ['Rayn', 'dreameracm'] SCHOOL_MAP = { 'cuit': u'成都信息工程大学' } SCHOOL_COLLEGE_MAP = { '0': u"软件工程学院", '1': u"计算机学院", '2': u"信息安全工程学院", '3': u"电子工程学院", '4': u"通信工程学院", '5': u"应用数学学院", '6': u"资源环境学院", '7': u"光电技术学院", '8': u"控制工程学院", '9': u"大气科学学院", '10':u"外国语学院", '11':u"管理学院", '12':u"政治学院", '13':u"文化艺术学院", '14':u"统计学院", '15':u"商学院", '16':u"物流学院" , } HONOR_LEVEL_MAP = { 0: u'区域赛金奖', 1: u'区域赛银奖', 2: u'区域赛铜奖', 3: u'区域赛优胜奖', 4: u'省赛一等奖', 5: u'省赛二等奖', 6: u'省赛三等奖', 7: u'省赛优胜奖', 8: u'校赛特等奖', 9: u'校赛一等奖', 10: u'校赛二等奖', 11: u'校赛三等奖', } OJ_MAP = { 'hdu': 'HDU', 'cf': 'Codeforces', 'bc': 'BestCoder', 'poj': 'POJ', 'zoj': 'ZOJ', 'bnu': 'BNU', 'uva': 'UVA', 'vj': 'Virtual Judge', } CSRF_ENABLED = True import os.path UPLOADED_RESOURCE_DEST = os.path.split(os.path.realpath(__file__))[0] + '/upload/' UPLOADED_RESOURCE_URL = '/upload/resource/' RESIZE_URL = UPLOADED_RESOURCE_URL RESIZE_ROOT = UPLOADED_RESOURCE_DEST IMAGE_FILE_PATH = 'static/image/bookimg/' SECRET_KEY = 'a very hard string' from datetime import timedelta REMEMBER_COOKIE_DURATION = timedelta(days=1) ## some config for front end NEWS_PER_PAGE = 10 ARTICLE_PER_PAGE = 5 USER_MANAGE_PER_PAGE = 8 NEWS_MANAGE_PER_PAGE = 8 ARTICLE_MANAGE_PER_PAGE = 8 HONOR_MANAGE_PER_PAGE = 8 RESOURCE_MANAGE_PER_PAGE = 12 SITUATION_PER_PAGE = 25 RANK_TABLE_PER_PAGE = 15 #index information RECENT_CONTEST_JSON = os.path.split(os.path.realpath(__file__))[0] + '/static/json/contests.json' RECOMMEND_SITE = { u'ACM/ICPC信息站' : 'http://acmicpc.info', 'BNU OJ' : 'http://acm.bnu.edu.cn', u'ACM-ICPC官网' : 'https://icpc.baylor.edu/', 'BestCoder': 'http://bestcoder.acmcoder.com/', u'CUIT学校主页': 'http://www.cuit.edu.cn' } #mail config MAIL_SERVER = 'mail.cuit.edu.cn' MAIL_PORT = 25 MAIL_USE_TLS = True MAIL_USE_SSL = False MAIL_USERNAME = "[email protected]" MAIL_PASSWORD = "xbnahn" MAIL_DEFAULT_SENDER = "[email protected]" MAIL_DEBUG = True #mail template APPLY_ACCEPT_MAIL = { 'subject' : u"CUIT ACM Team 申请准许通过", 'body' : u''' {name},非常欢迎你加入我们的团队: 1、加新生群 392397904 (CUIT ACM/ICPC FM),记得改下备注哦,格式 “学院年级-姓名”,例如“软工151-XX“; 2、完成ACM校队官网上的(http://acm.cuit.edu.cn)的新生训练计划; 3、遇到不懂的问题可以多在群里吼吼,有各种强的师兄师姐热心解答哦; 4、如果有空的话可以关注各大OJ近期比赛汇总(ACM校队官网首页可以查到),多参加下新生赛,练练手。 CUIT ACM/ICPC Team ''' } APPLY_REJECT_MAIL = { 'subject' : u"CUIT ACM Team 申请拒绝通过", 'body' : u''' {name},非常感谢你的申请,但不幸运的是我们不能通过你的申请,可能是由于你的申请信息填写 有误,你可以访问 http://acm.cuit.edu.cn/join_us 尝试重新申请。 CUIT ACM/ICPC Team ''' }
mit
811,916,324,765,602,000
21.637681
97
0.615557
false
benwu232/train_hard
train.py
1
4904
''' https://drive.google.com/file/d/0B3zSzVUgsG-FNTliNFl2a2t5dzQ/view?usp=sharing ''' import pickle import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, TimeDistributed from keras.layers.convolutional import Convolution2D, Convolution1D, AveragePooling2D, AveragePooling1D, MaxPooling1D, MaxPooling2D, ZeroPadding1D, ZeroPadding2D from keras.optimizers import * from keras.callbacks import Callback def load_dump(dump_file): fp = open(dump_file, 'rb') if not fp: print('Fail to open the dump file: %s' % dump_file) return None dump = pickle.load(fp) fp.close() return dump def defnet1(nb_filter_base = 64, nb_mid_blk = 1): '''A VGG-like net ''' input_dim = 128 prefix = '' act_type = 'tanh' act_type = 'linear' act_type = 'relu' act_type = 'sigmoid' act = keras.layers.advanced_activations.PReLU(init='zero', weights=None) init_type = 'uniform' init_type = 'glorot_uniform' init_type = 'he_normal' init_type = 'he_uniform' model = Sequential() model.add(Convolution2D(nb_filter_base, 2, 3, init=init_type, activation=act_type, input_shape=(1, 2, input_dim), border_mode='valid', name=prefix+'conv_input')) model.add(Dropout(0.5)) for k in range(nb_mid_blk): nb_filter = nb_filter_base * (2**k) model.add(Convolution2D(nb_filter, 1, 3, init=init_type, activation=act_type, border_mode='same', name=prefix+'conv{}_1'.format(k+1))) model.add(Convolution2D(nb_filter, 1, 3, init=init_type, activation=act_type, border_mode='same', name=prefix+'conv{}_2'.format(k+1))) model.add(AveragePooling2D((1,2), strides=(1,2), name=prefix+'pool{}'.format(k+1))) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dropout(0.5)) #model.add(Dense(64, activation='relu')) #model.add(Dropout(0.5)) model.add(Dense(3, activation='softmax', name=prefix+'softmax')) optimizer = Adam() optimizer = Adadelta() optimizer = SGD(lr=1e-4, decay=1e-4, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) print(model.summary()) return model class LearningRateMonitor(Callback): '''Learning rate monitor, monitor the learning rate and change it conditionally # Arguments epoch_num: monitor range shrinkage: shrinkage of learning rate ''' def __init__(self, epoch_num=10, shrinkage=3.0, min_lr=1e-7): self.epoch = [] self.history = {} self.epoch_num = epoch_num self.shrinkage = shrinkage self.min_lr = min_lr self.pre_sum = 0.0 self.cur_sum = 0.0 def on_train_begin(self, logs={}): self.epoch = [] self.history = {} self.pause_cnt = 0 def on_epoch_end(self, epoch, logs={}): assert hasattr(self.model.optimizer, 'lr'), \ 'Optimizer must have a "lr" attribute.' self.epoch.append(epoch) for k, v in logs.items(): self.history.setdefault(k, []).append(v) #if epoch < self.epoch_num * 2: # return lr = float(K.get_value(self.model.optimizer.lr)) if lr < self.min_lr: self.model.stop_training = True return self.pause_cnt += 1 if self.pause_cnt < self.epoch_num: return type_name = 'val_acc' pre_sum = sum(self.history[type_name][-self.epoch_num*2:-self.epoch_num]) cur_sum = sum(self.history[type_name][-self.epoch_num:]) if cur_sum < pre_sum: lr = float(K.get_value(self.model.optimizer.lr)) assert type(lr) == float, 'The output of the "schedule" function should be float.' new_lr = float(lr / self.shrinkage) K.set_value(self.model.optimizer.lr, new_lr) print('************* Change learning rate to: %f *****************' % new_lr) self.pause_cnt = 0 def train(): #load data train_data = load_dump('train_data.pkl') train_target = load_dump('train_target.pkl') validate_data = load_dump('validate_data.pkl') validate_target = load_dump('validate_target.pkl') model = defnet1(nb_filter_base=64, nb_mid_blk=1) lr_monitor = LearningRateMonitor(epoch_num=10, shrinkage=2.0, min_lr=1e-5) result = model.fit(train_data, train_target, nb_epoch=1000, batch_size=128, validation_data=(validate_data, validate_target), class_weight={0:1, 1:20, 2:20}, callbacks=[lr_monitor], verbose=2) model.save('final_model.json') model.save_weights('final_model.h5') if __name__ == '__main__': train()
mit
7,173,574,711,716,224,000
32.82069
161
0.597675
false
watchdogpolska/poradnia.siecobywatelska.pl
poradnia/cases/forms.py
3
3813
from atom.ext.crispy_forms.forms import ( FormHorizontalMixin, HelperMixin, SingleButtonMixin, ) from braces.forms import UserKwargModelFormMixin from crispy_forms.layout import Submit from dal import autocomplete from django import forms from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from guardian.shortcuts import assign_perm from .models import Case, PermissionGroup from django.urls import reverse class CaseForm( UserKwargModelFormMixin, FormHorizontalMixin, SingleButtonMixin, forms.ModelForm ): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if "instance" in kwargs: self.helper.form_action = kwargs["instance"].get_edit_url() def save(self, commit=True, *args, **kwargs): obj = super().save(commit=False, *args, **kwargs) if obj.pk: # old obj.modified_by = self.user if obj.status == Case.STATUS.assigned: obj.send_notification( actor=self.user, user_qs=obj.get_users_with_perms().filter(is_staff=True), verb="updated", ) else: # new obj.send_notification( actor=self.user, user_qs=obj.get_users_with_perms().filter(is_staff=True), verb="created", ) obj.created_by = self.user if commit: obj.save() return obj class Meta: model = Case fields = ("name", "status", "has_project") class CaseGroupPermissionForm(HelperMixin, forms.Form): action_text = _("Grant") user = forms.ModelChoiceField( queryset=None, required=True, widget=autocomplete.ModelSelect2("users:autocomplete"), label=_("User"), ) group = forms.ModelChoiceField( queryset=PermissionGroup.objects.all(), label=_("Permissions group") ) def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") self.case = kwargs.pop("case") super().__init__(*args, **kwargs) self.fields["user"].queryset = get_user_model().objects.for_user(self.user) self.helper.form_class = "form-inline" self.helper.layout.append(Submit("grant", _("Grant"))) self.helper.form_action = reverse( "cases:permission_grant", kwargs={"pk": str(self.case.pk)} ) def assign(self): for perm in self.cleaned_data["group"].permissions.all(): assign_perm(perm, self.cleaned_data["user"], self.case) self.case.send_notification( actor=self.user, verb="grant_group", action_object=self.cleaned_data["user"], action_target=self.cleaned_data["group"], user_qs=self.case.get_users_with_perms().filter(is_staff=True), ) class CaseCloseForm(UserKwargModelFormMixin, HelperMixin, forms.ModelForm): notify = forms.BooleanField(required=False, label=_("Notify user")) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper.add_input(Submit("action", _("Close"), css_class="btn-primary")) if "instance" in kwargs: self.helper.form_action = kwargs["instance"].get_close_url() def save(self, commit=True, *args, **kwargs): obj = super().save(commit=False, *args, **kwargs) obj.modified_by = self.user obj.status = Case.STATUS.closed if self.cleaned_data["notify"]: obj.send_notification( actor=self.user, user_qs=obj.get_users_with_perms(), verb="closed" ) if commit: obj.save() return obj class Meta: model = Case fields = ()
bsd-3-clause
-5,255,106,025,743,283,000
32.447368
84
0.594807
false
YeEmrick/learning
PCI/PCI_Code/chapter9/advancedclassify.py
3
4403
class matchrow: def __init__(self,row,allnum=False): if allnum: self.data=[float(row[i]) for i in range(len(row)-1)] else: self.data=row[0:len(row)-1] self.match=int(row[len(row)-1]) def loadmatch(f,allnum=False): rows=[] for line in file(f): rows.append(matchrow(line.split(','),allnum)) return rows from pylab import * def plotagematches(rows): xdm,ydm=[r.data[0] for r in rows if r.match==1],\ [r.data[1] for r in rows if r.match==1] xdn,ydn=[r.data[0] for r in rows if r.match==0],\ [r.data[1] for r in rows if r.match==0] plot(xdm,ydm,'bo') plot(xdn,ydn,'b+') show() def lineartrain(rows): averages={} counts={} for row in rows: # Get the class of this point cl=row.match averages.setdefault(cl,[0.0]*(len(row.data))) counts.setdefault(cl,0) # Add this point to the averages for i in range(len(row.data)): averages[cl][i]+=float(row.data[i]) # Keep track of how many points in each class counts[cl]+=1 # Divide sums by counts to get the averages for cl,avg in averages.items(): for i in range(len(avg)): avg[i]/=counts[cl] return averages def dotproduct(v1,v2): return sum([v1[i]*v2[i] for i in range(len(v1))]) def veclength(v): return sum([p**2 for p in v]) def dpclassify(point,avgs): b=(dotproduct(avgs[1],avgs[1])-dotproduct(avgs[0],avgs[0]))/2 y=dotproduct(point,avgs[0])-dotproduct(point,avgs[1])+b if y>0: return 0 else: return 1 def yesno(v): if v=='yes': return 1 elif v=='no': return -1 else: return 0 def matchcount(interest1,interest2): l1=interest1.split(':') l2=interest2.split(':') x=0 for v in l1: if v in l2: x+=1 return x yahookey="YOUR API KEY" from xml.dom.minidom import parseString from urllib import urlopen,quote_plus loc_cache={} def getlocation(address): if address in loc_cache: return loc_cache[address] data=urlopen('http://api.local.yahoo.com/MapsService/V1/'+\ 'geocode?appid=%s&location=%s' % (yahookey,quote_plus(address))).read() doc=parseString(data) lat=doc.getElementsByTagName('Latitude')[0].firstChild.nodeValue long=doc.getElementsByTagName('Longitude')[0].firstChild.nodeValue loc_cache[address]=(float(lat),float(long)) return loc_cache[address] def milesdistance(a1,a2): lat1,long1=getlocation(a1) lat2,long2=getlocation(a2) latdif=69.1*(lat2-lat1) longdif=53.0*(long2-long1) return (latdif**2+longdif**2)**.5 def loadnumerical(): oldrows=loadmatch('matchmaker.csv') newrows=[] for row in oldrows: d=row.data data=[float(d[0]),yesno(d[1]),yesno(d[2]), float(d[5]),yesno(d[6]),yesno(d[7]), matchcount(d[3],d[8]), milesdistance(d[4],d[9]), row.match] newrows.append(matchrow(data)) return newrows def scaledata(rows): low=[999999999.0]*len(rows[0].data) high=[-999999999.0]*len(rows[0].data) # Find the lowest and highest values for row in rows: d=row.data for i in range(len(d)): if d[i]<low[i]: low[i]=d[i] if d[i]>high[i]: high[i]=d[i] # Create a function that scales data def scaleinput(d): return [(d[i]-low[i])/(high[i]-low[i]) for i in range(len(low))] # Scale all the data newrows=[matchrow(scaleinput(row.data)+[row.match]) for row in rows] # Return the new data and the function return newrows,scaleinput def rbf(v1,v2,gamma=10): dv=[v1[i]-v2[i] for i in range(len(v1))] l=veclength(dv) return math.e**(-gamma*l) def nlclassify(point,rows,offset,gamma=10): sum0=0.0 sum1=0.0 count0=0 count1=0 for row in rows: if row.match==0: sum0+=rbf(point,row.data,gamma) count0+=1 else: sum1+=rbf(point,row.data,gamma) count1+=1 y=(1.0/count0)*sum0-(1.0/count1)*sum1+offset if y>0: return 0 else: return 1 def getoffset(rows,gamma=10): l0=[] l1=[] for row in rows: if row.match==0: l0.append(row.data) else: l1.append(row.data) sum0=sum(sum([rbf(v1,v2,gamma) for v1 in l0]) for v2 in l0) sum1=sum(sum([rbf(v1,v2,gamma) for v1 in l1]) for v2 in l1) return (1.0/(len(l1)**2))*sum1-(1.0/(len(l0)**2))*sum0
apache-2.0
6,678,705,473,298,663,000
24.208333
70
0.601408
false
batxes/4c2vhic
src/HiC_comp.py
2
5352
#!/usr/bin/python # script to compare virtual and original Hi-c's import re import os import sys import subprocess from multiprocessing import Pool from itertools import combinations, chain import time import ConfigParser import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt #plt.style.use('ggplot') from matplotlib.backends.backend_pdf import PdfPages from scipy.stats.stats import pearsonr from scipy.stats.stats import spearmanr if True: number_of_arguments = len(sys.argv) if number_of_arguments != 3: #Or all parameters, or no parameters print "Not enought parameters. virtual Hi-c matrix and Original Hi-C matrix are required. You passed: ",sys.argv[1:] sys.exit() if len(sys.argv) > 1: #if we pass the arguments (in the cluster) matrix_path = sys.argv[1] matrix_path2 = sys.argv[2] n_viewpoints = 70 max_distance = 5000 #read the config file matrix = np.zeros((n_viewpoints,n_viewpoints)) matrix2 = np.zeros((n_viewpoints,n_viewpoints)) matrix_final = np.ones((n_viewpoints,n_viewpoints)) count1 = -1 print "Filling first half..." for bead1 in range(n_viewpoints): count1 += 1 count2 = -1 for bead2 in range(n_viewpoints): count2 += 1 with open("{}".format(matrix_path), "r") as mtx: for line in mtx: values = re.split(",", line) if int(values[0]) == bead1 and int(values[1]) == bead2: matrix[count1][count2] = float(values[2]) matrix[count2][count1] = float(values[2]) break print "Filling the other half..." count1 = -1 for bead1 in range(n_viewpoints): count1 += 1 count2 = -1 for bead2 in range(n_viewpoints): count2 += 1 with open("{}".format(matrix_path2), "r") as mtx2: for line in mtx2: values = re.split(",", line) if int(values[0]) == bead1 and int(values[1]) == bead2: matrix2[count2][count1] = float(values[2]) matrix2[count1][count2] = float(values[2]) break max_list1 = [] max_list2 = [] for i in range(n_viewpoints): for j in range(n_viewpoints): max_list1.append(matrix[i][j]) max_list2.append(matrix2[i][j]) print "pearson: "+str(pearsonr(max_list1,max_list2)) print "spearman: "+str(spearmanr(max_list1,max_list2)) max_value_vhic = max(max_list1) min_value_vhic = min(max_list1) max_value_hic = max(max_list2) min_value_hic = min(max_list2) print "max and min vhic: {} - {}:".format(max_value_vhic,min_value_vhic) print "max and min hic: {} - {}:".format(max_value_hic,min_value_hic) max_list1 = [] max_list2 = [] for i in range(n_viewpoints): for j in range(n_viewpoints): if not j == i: vhic_value = 1-matrix[i][j]/max_distance try: hic_value = matrix2[i][j]/max_value_hic if hic_value != 0.0 and vhic_value != 0.0: max_list1.append(vhic_value) max_list2.append(hic_value) matrix_final[i][j] = vhic_value matrix_final[j][i] = hic_value except: continue print "pearson: "+str(pearsonr(max_list1,max_list2)) print "spearman: "+str(spearmanr(max_list1,max_list2)) print len(max_list1) print len(max_list2) fig = plt.figure() ax = plt.subplot(1,1,1) z = np.array(matrix_final) #maximum_hic_value = max(matrix_final) maximum_hic_value = max(max_list2) #only for rao #maximum_hic_value = 0.03 c = plt.pcolor(z,cmap=plt.cm.magma,vmax=maximum_hic_value, vmin=0) #for y in range(z.shape[0]): # for x in range(z.shape[1]): # plt.text(x+0.5,y+0.5,'%.2f' % z[y,x],horizontalalignment='center',verticalalignment='center',size=5) #ax.set_frame_on(False) plt.colorbar() plt.tick_params(axis='both', which='major', labelsize=8) plt.xticks(rotation=90) plt.axis([0,z.shape[1],0,z.shape[0]]) fig.set_facecolor('white') plt.show() print "Matrix saved in this directory." fig.savefig('HiC_comp.png',dpi = 300) #pp = PdfPages('HiC_comp.pdf') #pp.savefig(fig) #pp.close() else: #supp fig 8 # to do a little matrix of correlations matrix_corr = np.zeros((5,5)) matrix_corr[0][1] = 0.75187534318386928 matrix_corr[0][2] = 0.66754083023667898 matrix_corr[0][3] = 0.55333425695285288 matrix_corr[0][4] = 0.6635652284316963 matrix_corr[1][2] = 0.72785481811649311 matrix_corr[1][3] = 0.53935018788718381 matrix_corr[1][4] = 0.69158619892835715 matrix_corr[2][3] = 0.60221587323595382 matrix_corr[2][4] = 0.66368559486847933 matrix_corr[3][4] = 0.59119889876050857 fig = plt.figure() ax = plt.subplot(1,1,1) z = np.array(matrix_corr) c = plt.pcolor(z,cmap=plt.cm.hot_r,vmax=1, vmin=0.5) plt.colorbar() plt.axis([0,z.shape[1],0,z.shape[0]]) fig.set_facecolor('white') plt.show() fig.savefig('HiC_comp.png',dpi = 300)
gpl-3.0
-108,518,024,398,423,920
32.660377
124
0.581465
false
patrickwestphal/owlapy
tests/model/owlnamedindividual_tests.py
1
9342
import unittest from owlapy.model import IRI from owlapy.model import OWLAnnotationProperty from owlapy.model import OWLClass from owlapy.model import OWLDataProperty from owlapy.model import OWLDatatype from owlapy.model import OWLNamedIndividual from owlapy.model import OWLObject from owlapy.model import OWLObjectVisitor from owlapy.model import OWLObjectVisitorEx from owlapy.model import OWLObjectProperty from owlapy.model import OWLRuntimeException from owlapy.model import EntityType class TestOWLNamedIndividual(unittest.TestCase): def test___init___(self): iri = IRI('http://ex.org/sth') named_indiv = OWLNamedIndividual(iri) self.assertEqual(iri, named_indiv.iri) def test___str__(self): iri = IRI('http://ex.org/sth') named_indiv = OWLNamedIndividual(iri) self.assertEqual(str(iri), str(named_indiv)) def test___repr__(self): iri = IRI('http://ex.org/sth') named_indiv = OWLNamedIndividual(iri) self.assertEqual(str(iri), named_indiv.__repr__()) def test___eq__01(self): """named indiv vs. None --> False""" named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertNotEqual(named_indiv, None) def test___eq__02(self): """None vs. named indiv --> False""" named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertNotEqual(None, named_indiv) def test___eq__03(self): """named indiv vs. arbitrary object --> False""" named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertFalse(named_indiv == 23) def test___eq__04(self): """arbitrary object vs. named indiv--> False""" named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertFalse(23 == named_indiv) def test___eq__05(self): """named indiv vs. superclass object (differing IRI)--> False""" named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) obj = OWLObject() self.assertFalse(named_indiv == obj) def test___eq__06(self): """named indiv vs. named indiv (differing IRI) --> False""" named_indiv1 = OWLNamedIndividual(IRI('http://ex.org/sth')) named_indiv2 = OWLNamedIndividual(IRI('http://ex.org/sthElse')) self.assertFalse(named_indiv1 == named_indiv2) def test___eq__07(self): """named indiv vs. named indiv (same IRI) --> True""" named_indiv1 = OWLNamedIndividual(IRI('http://ex.org/sth')) named_indiv2 = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertTrue(named_indiv1 == named_indiv2) def test___eq__08(self): """named indiv vs. named indiv (same IRI) --> True""" named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertTrue(named_indiv == named_indiv) def test_is_named(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertTrue(named_indiv.is_named()) def test_get_entity_type(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertEqual(EntityType.NAMED_INDIVIDUAL, named_indiv.get_entity_type()) def test_get_owl_entity_01(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) # named individual owl_entity = named_indiv.get_owl_entity(EntityType.NAMED_INDIVIDUAL) self.assertTrue(isinstance(owl_entity, OWLNamedIndividual)) self.assertEqual(named_indiv.iri, owl_entity.iri) def test_get_owl_entity_02(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) # annotation property owl_entity = named_indiv.get_owl_entity(EntityType.ANNOTATION_PROPERTY) self.assertTrue(isinstance(owl_entity, OWLAnnotationProperty)) self.assertEqual(named_indiv.iri, owl_entity.iri) def test_get_owl_entity_03(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) # class owl_entity = named_indiv.get_owl_entity(EntityType.CLASS) self.assertTrue(isinstance(owl_entity, OWLClass)) self.assertEqual(named_indiv.iri, owl_entity.iri) def test_get_owl_entity_04(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) # data property owl_entity = named_indiv.get_owl_entity(EntityType.DATA_PROPERTY) self.assertTrue(isinstance(owl_entity, OWLDataProperty)) self.assertEqual(named_indiv.iri, owl_entity.iri) def test_get_owl_entity_05(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) # datatype owl_entity = named_indiv.get_owl_entity(EntityType.DATATYPE) self.assertTrue(isinstance(owl_entity, OWLDatatype)) self.assertEqual(named_indiv.iri, owl_entity.iri) def test_get_owl_entity_06(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) # object property owl_entity = named_indiv.get_owl_entity(EntityType.OBJECT_PROPERTY) self.assertTrue(isinstance(owl_entity, OWLObjectProperty)) self.assertEqual(named_indiv.iri, owl_entity.iri) def test_is_type_01(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertFalse(named_indiv.is_type(None)) def test_is_type_02(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertFalse(named_indiv.is_type(EntityType.CLASS)) def test_is_type_03(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertTrue(named_indiv.is_type(EntityType.NAMED_INDIVIDUAL)) def test_is_owl_named_individual(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertTrue(named_indiv.is_owl_named_individual()) def test_is_anonymous(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertFalse(named_indiv.is_anonymous()) def test_as_owl_named_individual(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertEqual(named_indiv, named_indiv.as_owl_named_individual()) def test_as_owl_anonymous_individual(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertRaises(OWLRuntimeException, OWLNamedIndividual.as_owl_anonymous_individual, named_indiv) def test_as_owl_annotation_property(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertRaises(OWLRuntimeException, OWLNamedIndividual.as_owl_annotation_property, named_indiv) def test_is_owl_annotation_property(self): named_indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertFalse(named_indiv.is_owl_annotation_property()) def test_get_annotations(self): self.fail() def test_get_annotation_assertion_axioms(self): self.fail() def test_get_referencing_axioms(self): self.fail() def test__compare_object_of_same_type_01(self): """same named individual --> 0""" indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertEqual(0, indiv._compare_object_of_same_type(indiv)) def test__compare_object_of_same_type_02(self): """same IRI --> 0""" iri = IRI('http://ex.org/sth') indiv1 = OWLNamedIndividual(iri) indiv2 = OWLNamedIndividual(iri) self.assertEqual(0, indiv1._compare_object_of_same_type(indiv2)) def test__compare_object_of_same_type_03(self): """same IRI string --> 0""" indiv1 = OWLNamedIndividual(IRI('http://ex.org/sth')) indiv2 = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertEqual(0, indiv1._compare_object_of_same_type(indiv2)) def test__compare_object_of_same_type_04(self): """differing IRI string --> -4""" indiv1 = OWLNamedIndividual(IRI('http://ex.org/sth')) indiv2 = OWLNamedIndividual(IRI('http://ex.org/sthElse')) self.assertEqual(-4, indiv1._compare_object_of_same_type(indiv2)) def test_accept_01(self): class DummyVisitor(OWLObjectVisitorEx): def __init__(self): self.visited = False def visit(self, visitee): self.visited = True return 23 visitor = DummyVisitor() indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) result = indiv.accept(visitor) self.assertEqual(23, result) self.assertTrue(visitor.visited) def test_accept_02(self): class DummyVisitor(OWLObjectVisitor): def __init__(self): self.visited = False def visit(self, visitee): self.visited = True visitor = DummyVisitor() indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) result = indiv.accept(visitor) self.assertIsNone(result) self.assertTrue(visitor.visited) def test_accept_03(self): not_a_visitor = 'this is not a visitor' indiv = OWLNamedIndividual(IRI('http://ex.org/sth')) self.assertRaises(OWLRuntimeException, OWLNamedIndividual.accept, indiv, not_a_visitor)
gpl-3.0
-1,929,371,452,084,963,800
37.925
79
0.639049
false
proxysh/Safejumper-for-Mac
buildlinux/env32/lib/python2.7/site-packages/twisted/words/service.py
13
38173
# -*- test-case-name: twisted.words.test.test_service -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ A module that needs a better name. Implements new cred things for words. How does this thing work? - Network connection on some port expecting to speak some protocol - Protocol-specific authentication, resulting in some kind of credentials object - twisted.cred.portal login using those credentials for the interface IUser and with something implementing IChatClient as the mind - successful login results in an IUser avatar the protocol can call methods on, and state added to the realm such that the mind will have methods called on it as is necessary - protocol specific actions lead to calls onto the avatar; remote events lead to calls onto the mind - protocol specific hangup, realm is notified, user is removed from active play, the end. """ from time import time, ctime from zope.interface import implementer from twisted import copyright from twisted.cred import portal, credentials, error as ecred from twisted.internet import defer, protocol from twisted.python import log, failure, reflect from twisted.python.compat import itervalues, unicode from twisted.python.components import registerAdapter from twisted.spread import pb from twisted.words import iwords, ewords from twisted.words.protocols import irc @implementer(iwords.IGroup) class Group(object): def __init__(self, name): self.name = name self.users = {} self.meta = { "topic": "", "topic_author": "", } def _ebUserCall(self, err, p): return failure.Failure(Exception(p, err)) def _cbUserCall(self, results): for (success, result) in results: if not success: user, err = result.value # XXX self.remove(user, err.getErrorMessage()) def add(self, user): assert iwords.IChatClient.providedBy(user), "%r is not a chat client" % (user,) if user.name not in self.users: additions = [] self.users[user.name] = user for p in itervalues(self.users): if p is not user: d = defer.maybeDeferred(p.userJoined, self, user) d.addErrback(self._ebUserCall, p=p) additions.append(d) defer.DeferredList(additions).addCallback(self._cbUserCall) return defer.succeed(None) def remove(self, user, reason=None): try: del self.users[user.name] except KeyError: pass else: removals = [] for p in itervalues(self.users): if p is not user: d = defer.maybeDeferred(p.userLeft, self, user, reason) d.addErrback(self._ebUserCall, p=p) removals.append(d) defer.DeferredList(removals).addCallback(self._cbUserCall) return defer.succeed(None) def size(self): return defer.succeed(len(self.users)) def receive(self, sender, recipient, message): assert recipient is self receives = [] for p in itervalues(self.users): if p is not sender: d = defer.maybeDeferred(p.receive, sender, self, message) d.addErrback(self._ebUserCall, p=p) receives.append(d) defer.DeferredList(receives).addCallback(self._cbUserCall) return defer.succeed(None) def setMetadata(self, meta): self.meta = meta sets = [] for p in itervalues(self.users): d = defer.maybeDeferred(p.groupMetaUpdate, self, meta) d.addErrback(self._ebUserCall, p=p) sets.append(d) defer.DeferredList(sets).addCallback(self._cbUserCall) return defer.succeed(None) def iterusers(self): # XXX Deferred? return iter(self.users.values()) @implementer(iwords.IUser) class User(object): realm = None mind = None def __init__(self, name): self.name = name self.groups = [] self.lastMessage = time() def loggedIn(self, realm, mind): self.realm = realm self.mind = mind self.signOn = time() def join(self, group): def cbJoin(result): self.groups.append(group) return result return group.add(self.mind).addCallback(cbJoin) def leave(self, group, reason=None): def cbLeave(result): self.groups.remove(group) return result return group.remove(self.mind, reason).addCallback(cbLeave) def send(self, recipient, message): self.lastMessage = time() return recipient.receive(self.mind, recipient, message) def itergroups(self): return iter(self.groups) def logout(self): for g in self.groups[:]: self.leave(g) NICKSERV = 'NickServ!NickServ@services' @implementer(iwords.IChatClient) class IRCUser(irc.IRC): """ Protocol instance representing an IRC user connected to the server. """ # A list of IGroups in which I am participating groups = None # A no-argument callable I should invoke when I go away logout = None # An IUser we use to interact with the chat service avatar = None # To whence I belong realm = None # How to handle unicode (TODO: Make this customizable on a per-user basis) encoding = 'utf-8' # Twisted callbacks def connectionMade(self): self.irc_PRIVMSG = self.irc_NICKSERV_PRIVMSG self.realm = self.factory.realm self.hostname = self.realm.name def connectionLost(self, reason): if self.logout is not None: self.logout() self.avatar = None # Make sendMessage a bit more useful to us def sendMessage(self, command, *parameter_list, **kw): if 'prefix' not in kw: kw['prefix'] = self.hostname if 'to' not in kw: kw['to'] = self.name.encode(self.encoding) arglist = [self, command, kw['to']] + list(parameter_list) arglistUnicode = [] for arg in arglist: if isinstance(arg, bytes): arg = arg.decode("utf-8") arglistUnicode.append(arg) irc.IRC.sendMessage(*arglistUnicode, **kw) # IChatClient implementation def userJoined(self, group, user): self.join( "%s!%s@%s" % (user.name, user.name, self.hostname), '#' + group.name) def userLeft(self, group, user, reason=None): self.part( "%s!%s@%s" % (user.name, user.name, self.hostname), '#' + group.name, (reason or u"leaving")) def receive(self, sender, recipient, message): #>> :[email protected] PRIVMSG glyph_ :hello # omg??????????? if iwords.IGroup.providedBy(recipient): recipientName = '#' + recipient.name else: recipientName = recipient.name text = message.get('text', '<an unrepresentable message>') for L in text.splitlines(): self.privmsg( '%s!%s@%s' % (sender.name, sender.name, self.hostname), recipientName, L) def groupMetaUpdate(self, group, meta): if 'topic' in meta: topic = meta['topic'] author = meta.get('topic_author', '') self.topic( self.name, '#' + group.name, topic, '%s!%s@%s' % (author, author, self.hostname) ) # irc.IRC callbacks - starting with login related stuff. nickname = None password = None def irc_PASS(self, prefix, params): """ Password message -- Register a password. Parameters: <password> [REQUIRED] Note that IRC requires the client send this *before* NICK and USER. """ self.password = params[-1] def irc_NICK(self, prefix, params): """ Nick message -- Set your nickname. Parameters: <nickname> [REQUIRED] """ nickname = params[0] try: if isinstance(nickname, bytes): nickname = nickname.decode(self.encoding) except UnicodeDecodeError: self.privmsg( NICKSERV, repr(nickname), 'Your nickname cannot be decoded. Please use ASCII or UTF-8.') self.transport.loseConnection() return self.nickname = nickname self.name = nickname for code, text in self._motdMessages: self.sendMessage(code, text % self.factory._serverInfo) if self.password is None: self.privmsg( NICKSERV, nickname, 'Password?') else: password = self.password self.password = None self.logInAs(nickname, password) def irc_USER(self, prefix, params): """ User message -- Set your realname. Parameters: <user> <mode> <unused> <realname> """ # Note: who gives a crap about this? The IUser has the real # information we care about. Save it anyway, I guess, just # for fun. self.realname = params[-1] def irc_NICKSERV_PRIVMSG(self, prefix, params): """ Send a (private) message. Parameters: <msgtarget> <text to be sent> """ target = params[0] password = params[-1] if self.nickname is None: # XXX Send an error response here self.transport.loseConnection() elif target.lower() != "nickserv": self.privmsg( NICKSERV, self.nickname, "Denied. Please send me (NickServ) your password.") else: nickname = self.nickname self.nickname = None self.logInAs(nickname, password) def logInAs(self, nickname, password): d = self.factory.portal.login( credentials.UsernamePassword(nickname, password), self, iwords.IUser) d.addCallbacks(self._cbLogin, self._ebLogin, errbackArgs=(nickname,)) _welcomeMessages = [ (irc.RPL_WELCOME, ":connected to Twisted IRC"), (irc.RPL_YOURHOST, ":Your host is %(serviceName)s, running version %(serviceVersion)s"), (irc.RPL_CREATED, ":This server was created on %(creationDate)s"), # "Bummer. This server returned a worthless 004 numeric. # I'll have to guess at all the values" # -- epic (irc.RPL_MYINFO, # w and n are the currently supported channel and user modes # -- specify this better "%(serviceName)s %(serviceVersion)s w n") ] _motdMessages = [ (irc.RPL_MOTDSTART, ":- %(serviceName)s Message of the Day - "), (irc.RPL_ENDOFMOTD, ":End of /MOTD command.") ] def _cbLogin(self, result): (iface, avatar, logout) = result assert iface is iwords.IUser, "Realm is buggy, got %r" % (iface,) # Let them send messages to the world del self.irc_PRIVMSG self.avatar = avatar self.logout = logout for code, text in self._welcomeMessages: self.sendMessage(code, text % self.factory._serverInfo) def _ebLogin(self, err, nickname): if err.check(ewords.AlreadyLoggedIn): self.privmsg( NICKSERV, nickname, "Already logged in. No pod people allowed!") elif err.check(ecred.UnauthorizedLogin): self.privmsg( NICKSERV, nickname, "Login failed. Goodbye.") else: log.msg("Unhandled error during login:") log.err(err) self.privmsg( NICKSERV, nickname, "Server error during login. Sorry.") self.transport.loseConnection() # Great, now that's out of the way, here's some of the interesting # bits def irc_PING(self, prefix, params): """ Ping message Parameters: <server1> [ <server2> ] """ if self.realm is not None: self.sendMessage('PONG', self.hostname) def irc_QUIT(self, prefix, params): """ Quit Parameters: [ <Quit Message> ] """ self.transport.loseConnection() def _channelMode(self, group, modes=None, *args): if modes: self.sendMessage( irc.ERR_UNKNOWNMODE, ":Unknown MODE flag.") else: self.channelMode(self.name, '#' + group.name, '+') def _userMode(self, user, modes=None): if modes: self.sendMessage( irc.ERR_UNKNOWNMODE, ":Unknown MODE flag.") elif user is self.avatar: self.sendMessage( irc.RPL_UMODEIS, "+") else: self.sendMessage( irc.ERR_USERSDONTMATCH, ":You can't look at someone else's modes.") def irc_MODE(self, prefix, params): """ User mode message Parameters: <nickname> *( ( "+" / "-" ) *( "i" / "w" / "o" / "O" / "r" ) ) """ try: channelOrUser = params[0] if isinstance(channelOrUser, bytes): channelOrUser = channelOrUser.decode(self.encoding) except UnicodeDecodeError: self.sendMessage( irc.ERR_NOSUCHNICK, params[0], ":No such nickname (could not decode your unicode!)") return if channelOrUser.startswith('#'): def ebGroup(err): err.trap(ewords.NoSuchGroup) self.sendMessage( irc.ERR_NOSUCHCHANNEL, params[0], ":That channel doesn't exist.") d = self.realm.lookupGroup(channelOrUser[1:]) d.addCallbacks( self._channelMode, ebGroup, callbackArgs=tuple(params[1:])) else: def ebUser(err): self.sendMessage( irc.ERR_NOSUCHNICK, ":No such nickname.") d = self.realm.lookupUser(channelOrUser) d.addCallbacks( self._userMode, ebUser, callbackArgs=tuple(params[1:])) def irc_USERHOST(self, prefix, params): """ Userhost message Parameters: <nickname> *( SPACE <nickname> ) [Optional] """ pass def irc_PRIVMSG(self, prefix, params): """ Send a (private) message. Parameters: <msgtarget> <text to be sent> """ try: targetName = params[0] if isinstance(targetName, bytes): targetName = targetName.decode(self.encoding) except UnicodeDecodeError: self.sendMessage( irc.ERR_NOSUCHNICK, params[0], ":No such nick/channel (could not decode your unicode!)") return messageText = params[-1] if targetName.startswith('#'): target = self.realm.lookupGroup(targetName[1:]) else: target = self.realm.lookupUser(targetName).addCallback(lambda user: user.mind) def cbTarget(targ): if targ is not None: return self.avatar.send(targ, {"text": messageText}) def ebTarget(err): self.sendMessage( irc.ERR_NOSUCHNICK, targetName, ":No such nick/channel.") target.addCallbacks(cbTarget, ebTarget) def irc_JOIN(self, prefix, params): """ Join message Parameters: ( <channel> *( "," <channel> ) [ <key> *( "," <key> ) ] ) """ try: groupName = params[0] if isinstance(groupName, bytes): groupName = groupName.decode(self.encoding) except UnicodeDecodeError: self.sendMessage( irc.ERR_NOSUCHCHANNEL, params[0], ":No such channel (could not decode your unicode!)") return if groupName.startswith('#'): groupName = groupName[1:] def cbGroup(group): def cbJoin(ign): self.userJoined(group, self) self.names( self.name, '#' + group.name, [user.name for user in group.iterusers()]) self._sendTopic(group) return self.avatar.join(group).addCallback(cbJoin) def ebGroup(err): self.sendMessage( irc.ERR_NOSUCHCHANNEL, '#' + groupName, ":No such channel.") self.realm.getGroup(groupName).addCallbacks(cbGroup, ebGroup) def irc_PART(self, prefix, params): """ Part message Parameters: <channel> *( "," <channel> ) [ <Part Message> ] """ try: groupName = params[0] if isinstance(params[0], bytes): groupName = params[0].decode(self.encoding) except UnicodeDecodeError: self.sendMessage( irc.ERR_NOTONCHANNEL, params[0], ":Could not decode your unicode!") return if groupName.startswith('#'): groupName = groupName[1:] if len(params) > 1: reason = params[1] if isinstance(reason, bytes): reason = reason.decode('utf-8') else: reason = None def cbGroup(group): def cbLeave(result): self.userLeft(group, self, reason) return self.avatar.leave(group, reason).addCallback(cbLeave) def ebGroup(err): err.trap(ewords.NoSuchGroup) self.sendMessage( irc.ERR_NOTONCHANNEL, '#' + groupName, ":" + err.getErrorMessage()) self.realm.lookupGroup(groupName).addCallbacks(cbGroup, ebGroup) def irc_NAMES(self, prefix, params): """ Names message Parameters: [ <channel> *( "," <channel> ) [ <target> ] ] """ #<< NAMES #python #>> :benford.openprojects.net 353 glyph = #python :Orban ... @glyph ... Zymurgy skreech #>> :benford.openprojects.net 366 glyph #python :End of /NAMES list. try: channel = params[-1] if isinstance(channel, bytes): channel = channel.decode(self.encoding) except UnicodeDecodeError: self.sendMessage( irc.ERR_NOSUCHCHANNEL, params[-1], ":No such channel (could not decode your unicode!)") return if channel.startswith('#'): channel = channel[1:] def cbGroup(group): self.names( self.name, '#' + group.name, [user.name for user in group.iterusers()]) def ebGroup(err): err.trap(ewords.NoSuchGroup) # No group? Fine, no names! self.names( self.name, '#' + channel, []) self.realm.lookupGroup(channel).addCallbacks(cbGroup, ebGroup) def irc_TOPIC(self, prefix, params): """ Topic message Parameters: <channel> [ <topic> ] """ try: channel = params[0] if isinstance(params[0], bytes): channel = channel.decode(self.encoding) except UnicodeDecodeError: self.sendMessage( irc.ERR_NOSUCHCHANNEL, ":That channel doesn't exist (could not decode your unicode!)") return if channel.startswith('#'): channel = channel[1:] if len(params) > 1: self._setTopic(channel, params[1]) else: self._getTopic(channel) def _sendTopic(self, group): """ Send the topic of the given group to this user, if it has one. """ topic = group.meta.get("topic") if topic: author = group.meta.get("topic_author") or "<noone>" date = group.meta.get("topic_date", 0) self.topic(self.name, '#' + group.name, topic) self.topicAuthor(self.name, '#' + group.name, author, date) def _getTopic(self, channel): #<< TOPIC #python #>> :benford.openprojects.net 332 glyph #python :<churchr> I really did. I sprained all my toes. #>> :benford.openprojects.net 333 glyph #python itamar|nyc 994713482 def ebGroup(err): err.trap(ewords.NoSuchGroup) self.sendMessage( irc.ERR_NOSUCHCHANNEL, '=', channel, ":That channel doesn't exist.") self.realm.lookupGroup(channel).addCallbacks(self._sendTopic, ebGroup) def _setTopic(self, channel, topic): #<< TOPIC #divunal :foo #>> :[email protected] TOPIC #divunal :foo def cbGroup(group): newMeta = group.meta.copy() newMeta['topic'] = topic newMeta['topic_author'] = self.name newMeta['topic_date'] = int(time()) def ebSet(err): self.sendMessage( irc.ERR_CHANOPRIVSNEEDED, "#" + group.name, ":You need to be a channel operator to do that.") return group.setMetadata(newMeta).addErrback(ebSet) def ebGroup(err): err.trap(ewords.NoSuchGroup) self.sendMessage( irc.ERR_NOSUCHCHANNEL, '=', channel, ":That channel doesn't exist.") self.realm.lookupGroup(channel).addCallbacks(cbGroup, ebGroup) def list(self, channels): """ Send a group of LIST response lines @type channel: C{list} of C{(str, int, str)} @param channel: Information about the channels being sent: their name, the number of participants, and their topic. """ for (name, size, topic) in channels: self.sendMessage(irc.RPL_LIST, name, str(size), ":" + topic) self.sendMessage(irc.RPL_LISTEND, ":End of /LIST") def irc_LIST(self, prefix, params): """ List query Return information about the indicated channels, or about all channels if none are specified. Parameters: [ <channel> *( "," <channel> ) [ <target> ] ] """ #<< list #python #>> :orwell.freenode.net 321 exarkun Channel :Users Name #>> :orwell.freenode.net 322 exarkun #python 358 :The Python programming language #>> :orwell.freenode.net 323 exarkun :End of /LIST if params: # Return information about indicated channels try: allChannels = params[0] if isinstance(allChannels, bytes): allChannels = allChannels.decode(self.encoding) channels = allChannels.split(',') except UnicodeDecodeError: self.sendMessage( irc.ERR_NOSUCHCHANNEL, params[0], ":No such channel (could not decode your unicode!)") return groups = [] for ch in channels: if ch.startswith('#'): ch = ch[1:] groups.append(self.realm.lookupGroup(ch)) groups = defer.DeferredList(groups, consumeErrors=True) groups.addCallback(lambda gs: [r for (s, r) in gs if s]) else: # Return information about all channels groups = self.realm.itergroups() def cbGroups(groups): def gotSize(size, group): return group.name, size, group.meta.get('topic') d = defer.DeferredList([ group.size().addCallback(gotSize, group) for group in groups]) d.addCallback(lambda results: self.list([r for (s, r) in results if s])) return d groups.addCallback(cbGroups) def _channelWho(self, group): self.who(self.name, '#' + group.name, [(m.name, self.hostname, self.realm.name, m.name, "H", 0, m.name) for m in group.iterusers()]) def _userWho(self, user): self.sendMessage(irc.RPL_ENDOFWHO, ":User /WHO not implemented") def irc_WHO(self, prefix, params): """ Who query Parameters: [ <mask> [ "o" ] ] """ #<< who #python #>> :x.opn 352 glyph #python aquarius pc-62-31-193-114-du.blueyonder.co.uk y.opn Aquarius H :3 Aquarius # ... #>> :x.opn 352 glyph #python foobar europa.tranquility.net z.opn skreech H :0 skreech #>> :x.opn 315 glyph #python :End of /WHO list. ### also #<< who glyph #>> :x.opn 352 glyph #python glyph adsl-64-123-27-108.dsl.austtx.swbell.net x.opn glyph H :0 glyph #>> :x.opn 315 glyph glyph :End of /WHO list. if not params: self.sendMessage(irc.RPL_ENDOFWHO, ":/WHO not supported.") return try: channelOrUser = params[0] if isinstance(channelOrUser, bytes): channelOrUser = channelOrUser.decode(self.encoding) except UnicodeDecodeError: self.sendMessage( irc.RPL_ENDOFWHO, params[0], ":End of /WHO list (could not decode your unicode!)") return if channelOrUser.startswith('#'): def ebGroup(err): err.trap(ewords.NoSuchGroup) self.sendMessage( irc.RPL_ENDOFWHO, channelOrUser, ":End of /WHO list.") d = self.realm.lookupGroup(channelOrUser[1:]) d.addCallbacks(self._channelWho, ebGroup) else: def ebUser(err): err.trap(ewords.NoSuchUser) self.sendMessage( irc.RPL_ENDOFWHO, channelOrUser, ":End of /WHO list.") d = self.realm.lookupUser(channelOrUser) d.addCallbacks(self._userWho, ebUser) def irc_WHOIS(self, prefix, params): """ Whois query Parameters: [ <target> ] <mask> *( "," <mask> ) """ def cbUser(user): self.whois( self.name, user.name, user.name, self.realm.name, user.name, self.realm.name, 'Hi mom!', False, int(time() - user.lastMessage), user.signOn, ['#' + group.name for group in user.itergroups()]) def ebUser(err): err.trap(ewords.NoSuchUser) self.sendMessage( irc.ERR_NOSUCHNICK, params[0], ":No such nick/channel") try: user = params[0] if isinstance(user, bytes): user = user.decode(self.encoding) except UnicodeDecodeError: self.sendMessage( irc.ERR_NOSUCHNICK, params[0], ":No such nick/channel") return self.realm.lookupUser(user).addCallbacks(cbUser, ebUser) # Unsupported commands, here for legacy compatibility def irc_OPER(self, prefix, params): """ Oper message Parameters: <name> <password> """ self.sendMessage(irc.ERR_NOOPERHOST, ":O-lines not applicable") class IRCFactory(protocol.ServerFactory): """ IRC server that creates instances of the L{IRCUser} protocol. @ivar _serverInfo: A dictionary mapping: "serviceName" to the name of the server, "serviceVersion" to the copyright version, "creationDate" to the time that the server was started. """ protocol = IRCUser def __init__(self, realm, portal): self.realm = realm self.portal = portal self._serverInfo = { "serviceName": self.realm.name, "serviceVersion": copyright.version, "creationDate": ctime() } class PBMind(pb.Referenceable): def __init__(self): pass def jellyFor(self, jellier): qual = reflect.qual(PBMind) if isinstance(qual, unicode): qual = qual.encode("utf-8") return qual, jellier.invoker.registerReference(self) def remote_userJoined(self, user, group): pass def remote_userLeft(self, user, group, reason): pass def remote_receive(self, sender, recipient, message): pass def remote_groupMetaUpdate(self, group, meta): pass @implementer(iwords.IChatClient) class PBMindReference(pb.RemoteReference): def receive(self, sender, recipient, message): if iwords.IGroup.providedBy(recipient): rec = PBGroup(self.realm, self.avatar, recipient) else: rec = PBUser(self.realm, self.avatar, recipient) return self.callRemote( 'receive', PBUser(self.realm, self.avatar, sender), rec, message) def groupMetaUpdate(self, group, meta): return self.callRemote( 'groupMetaUpdate', PBGroup(self.realm, self.avatar, group), meta) def userJoined(self, group, user): return self.callRemote( 'userJoined', PBGroup(self.realm, self.avatar, group), PBUser(self.realm, self.avatar, user)) def userLeft(self, group, user, reason=None): return self.callRemote( 'userLeft', PBGroup(self.realm, self.avatar, group), PBUser(self.realm, self.avatar, user), reason) pb.setUnjellyableForClass(PBMind, PBMindReference) class PBGroup(pb.Referenceable): def __init__(self, realm, avatar, group): self.realm = realm self.avatar = avatar self.group = group def processUniqueID(self): return hash((self.realm.name, self.avatar.name, self.group.name)) def jellyFor(self, jellier): qual = reflect.qual(self.__class__) if isinstance(qual, unicode): qual = qual.encode("utf-8") group = self.group.name if isinstance(group, unicode): group = group.encode("utf-8") return qual, group, jellier.invoker.registerReference(self) def remote_leave(self, reason=None): return self.avatar.leave(self.group, reason) def remote_send(self, message): return self.avatar.send(self.group, message) @implementer(iwords.IGroup) class PBGroupReference(pb.RemoteReference): def unjellyFor(self, unjellier, unjellyList): clsName, name, ref = unjellyList self.name = name if bytes != str and isinstance(self.name, bytes): self.name = self.name.decode('utf-8') return pb.RemoteReference.unjellyFor(self, unjellier, [clsName, ref]) def leave(self, reason=None): return self.callRemote("leave", reason) def send(self, message): return self.callRemote("send", message) pb.setUnjellyableForClass(PBGroup, PBGroupReference) class PBUser(pb.Referenceable): def __init__(self, realm, avatar, user): self.realm = realm self.avatar = avatar self.user = user def processUniqueID(self): return hash((self.realm.name, self.avatar.name, self.user.name)) @implementer(iwords.IChatClient) class ChatAvatar(pb.Referenceable): def __init__(self, avatar): self.avatar = avatar def jellyFor(self, jellier): qual = reflect.qual(self.__class__) if isinstance(qual, unicode): qual = qual.encode("utf-8") return qual, jellier.invoker.registerReference(self) def remote_join(self, groupName): def cbGroup(group): def cbJoin(ignored): return PBGroup(self.avatar.realm, self.avatar, group) d = self.avatar.join(group) d.addCallback(cbJoin) return d d = self.avatar.realm.getGroup(groupName) d.addCallback(cbGroup) return d registerAdapter(ChatAvatar, iwords.IUser, pb.IPerspective) class AvatarReference(pb.RemoteReference): def join(self, groupName): return self.callRemote('join', groupName) def quit(self): d = defer.Deferred() self.broker.notifyOnDisconnect(lambda: d.callback(None)) self.broker.transport.loseConnection() return d pb.setUnjellyableForClass(ChatAvatar, AvatarReference) @implementer(portal.IRealm, iwords.IChatService) class WordsRealm(object): _encoding = 'utf-8' def __init__(self, name): self.name = name def userFactory(self, name): return User(name) def groupFactory(self, name): return Group(name) def logoutFactory(self, avatar, facet): def logout(): # XXX Deferred support here getattr(facet, 'logout', lambda: None)() avatar.realm = avatar.mind = None return logout def requestAvatar(self, avatarId, mind, *interfaces): if isinstance(avatarId, bytes): avatarId = avatarId.decode(self._encoding) def gotAvatar(avatar): if avatar.realm is not None: raise ewords.AlreadyLoggedIn() for iface in interfaces: facet = iface(avatar, None) if facet is not None: avatar.loggedIn(self, mind) mind.name = avatarId mind.realm = self mind.avatar = avatar return iface, facet, self.logoutFactory(avatar, facet) raise NotImplementedError(self, interfaces) return self.getUser(avatarId).addCallback(gotAvatar) # IChatService, mostly. createGroupOnRequest = False createUserOnRequest = True def lookupUser(self, name): raise NotImplementedError def lookupGroup(self, group): raise NotImplementedError def addUser(self, user): """ Add the given user to this service. This is an internal method intended to be overridden by L{WordsRealm} subclasses, not called by external code. @type user: L{IUser} @rtype: L{twisted.internet.defer.Deferred} @return: A Deferred which fires with L{None} when the user is added, or which fails with L{twisted.words.ewords.DuplicateUser} if a user with the same name exists already. """ raise NotImplementedError def addGroup(self, group): """ Add the given group to this service. @type group: L{IGroup} @rtype: L{twisted.internet.defer.Deferred} @return: A Deferred which fires with L{None} when the group is added, or which fails with L{twisted.words.ewords.DuplicateGroup} if a group with the same name exists already. """ raise NotImplementedError def getGroup(self, name): if self.createGroupOnRequest: def ebGroup(err): err.trap(ewords.DuplicateGroup) return self.lookupGroup(name) return self.createGroup(name).addErrback(ebGroup) return self.lookupGroup(name) def getUser(self, name): if self.createUserOnRequest: def ebUser(err): err.trap(ewords.DuplicateUser) return self.lookupUser(name) return self.createUser(name).addErrback(ebUser) return self.lookupUser(name) def createUser(self, name): def cbLookup(user): return failure.Failure(ewords.DuplicateUser(name)) def ebLookup(err): err.trap(ewords.NoSuchUser) return self.userFactory(name) name = name.lower() d = self.lookupUser(name) d.addCallbacks(cbLookup, ebLookup) d.addCallback(self.addUser) return d def createGroup(self, name): def cbLookup(group): return failure.Failure(ewords.DuplicateGroup(name)) def ebLookup(err): err.trap(ewords.NoSuchGroup) return self.groupFactory(name) name = name.lower() d = self.lookupGroup(name) d.addCallbacks(cbLookup, ebLookup) d.addCallback(self.addGroup) return d class InMemoryWordsRealm(WordsRealm): def __init__(self, *a, **kw): super(InMemoryWordsRealm, self).__init__(*a, **kw) self.users = {} self.groups = {} def itergroups(self): return defer.succeed(itervalues(self.groups)) def addUser(self, user): if user.name in self.users: return defer.fail(failure.Failure(ewords.DuplicateUser())) self.users[user.name] = user return defer.succeed(user) def addGroup(self, group): if group.name in self.groups: return defer.fail(failure.Failure(ewords.DuplicateGroup())) self.groups[group.name] = group return defer.succeed(group) def lookupUser(self, name): name = name.lower() try: user = self.users[name] except KeyError: return defer.fail(failure.Failure(ewords.NoSuchUser(name))) else: return defer.succeed(user) def lookupGroup(self, name): name = name.lower() try: group = self.groups[name] except KeyError: return defer.fail(failure.Failure(ewords.NoSuchGroup(name))) else: return defer.succeed(group) __all__ = [ 'Group', 'User', 'WordsRealm', 'InMemoryWordsRealm', ]
gpl-2.0
-4,616,086,217,281,156,000
29.081166
111
0.561208
false
sunjeammy/tornado
demos/benchmark/chunk_benchmark.py
31
1572
#!/usr/bin/env python # # Downloads a large file in chunked encoding with both curl and simple clients import logging from tornado.curl_httpclient import CurlAsyncHTTPClient from tornado.simple_httpclient import SimpleAsyncHTTPClient from tornado.ioloop import IOLoop from tornado.options import define, options, parse_command_line from tornado.web import RequestHandler, Application define('port', default=8888) define('num_chunks', default=1000) define('chunk_size', default=2048) class ChunkHandler(RequestHandler): def get(self): for i in xrange(options.num_chunks): self.write('A' * options.chunk_size) self.flush() self.finish() def main(): parse_command_line() app = Application([('/', ChunkHandler)]) app.listen(options.port, address='127.0.0.1') def callback(response): response.rethrow() assert len(response.body) == (options.num_chunks * options.chunk_size) logging.warning("fetch completed in %s seconds", response.request_time) IOLoop.instance().stop() logging.warning("Starting fetch with curl client") curl_client = CurlAsyncHTTPClient() curl_client.fetch('http://localhost:%d/' % options.port, callback=callback) IOLoop.instance().start() logging.warning("Starting fetch with simple client") simple_client = SimpleAsyncHTTPClient() simple_client.fetch('http://localhost:%d/' % options.port, callback=callback) IOLoop.instance().start() if __name__ == '__main__': main()
apache-2.0
8,332,642,254,566,516,000
32.446809
79
0.678117
false
MooglyGuy/mame
scripts/minimaws/lib/htmltmpl.py
29
19706
#!/usr/bin/python ## ## license:BSD-3-Clause ## copyright-holders:Vas Crabb import string ERROR_PAGE = string.Template( '<!DOCTYPE html>\n' \ '<html>\n' \ '<head>\n' \ ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' \ ' <title>${code} ${message}</title>\n' \ '</head>\n' \ '<body>\n' \ '<h1>${message}</h1>\n' \ '</body>\n' \ '</html>\n') SORTABLE_TABLE_EPILOGUE = string.Template( ' </tbody>\n' '</table>\n' '<script>make_table_sortable(document.getElementById("${id}"));</script>\n') MACHINE_PROLOGUE = string.Template( '<!DOCTYPE html>\n' \ '<html>\n' \ '<head>\n' \ ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' \ ' <meta http-equiv="Content-Style-Type" content="text/css">\n' \ ' <meta http-equiv="Content-Script-Type" content="text/javascript">\n' \ ' <link rel="stylesheet" type="text/css" href="${assets}/style.css">\n' \ ' <script type="text/javascript">\n' \ ' var appurl="${app}"\n' \ ' var assetsurl="${assets}"\n' \ ' </script>\n' \ ' <script type="text/javascript" src="${assets}/common.js"></script>\n' \ ' <script type="text/javascript" src="${assets}/machine.js"></script>\n' \ ' <title>Machine: ${description} (${shortname})</title>\n' \ '</head>\n' \ '<body>\n' \ '<h1>${description}</h1>\n' \ '<table class="sysinfo">\n' \ ' <tr><th>Short name:</th><td>${shortname}</td></tr>\n' \ ' <tr><th>Is device:</th><td>${isdevice}</td></tr>\n' \ ' <tr><th>Runnable:</th><td>${runnable}</td></tr>\n' \ ' <tr><th>Source file:</th><td><a href="${sourcehref}">${sourcefile}</a></td></tr>\n') MACHINE_CLONES_PROLOGUE = string.Template( '<h2>Clones</h2>\n' \ '<table id="tbl-clones">\n' \ ' <thead>\n' \ ' <tr>\n' \ ' <th>Short name</th>\n' \ ' <th>Description</th>\n' \ ' <th>Year</th>\n' \ ' <th>Manufacturer</th>\n' \ ' </tr>\n' \ ' </thead>\n' \ ' <tbody>\n') MACHINE_CLONES_ROW = string.Template( ' <tr>\n' \ ' <td><a href="${href}">${shortname}</a></td>\n' \ ' <td><a href="${href}">${description}</a></td>\n' \ ' <td>${year}</td>\n' \ ' <td>${manufacturer}</td>\n' \ ' </tr>\n') MACHINE_SOFTWARELISTS_TABLE_PROLOGUE = string.Template( '<h2 id="heading-softwarelists">Software Lists</h2>\n' \ '<table id="tbl-softwarelists">\n' \ ' <thead>\n' \ ' <tr>\n' \ ' <th>Card</th>\n' \ ' <th>Short name</th>\n' \ ' <th>Description</th>\n' \ ' <th>Status</th>\n' \ ' <th class="numeric">Total</th>\n' \ ' <th class="numeric">Supported</th>\n' \ ' <th class="numeric">Partially supported</th>\n' \ ' <th class="numeric">Unsupported</th>\n' \ ' </tr>\n' \ ' </thead>\n' \ ' <tbody>\n') MACHINE_SOFTWARELISTS_TABLE_ROW = string.Template( ' <tr id="row-softwarelists-${rowid}">\n' \ ' <td></td>\n' \ ' <td><a href="${href}">${shortname}</a></td>\n' \ ' <td><a href="${href}">${description}</a></td>\n' \ ' <td>${status}</td>\n' \ ' <td style="text-align: right">${total}</td>\n' \ ' <td style="text-align: right">${supported}</td>\n' \ ' <td style="text-align: right">${partiallysupported}</td>\n' \ ' <td style="text-align: right">${unsupported}</td>\n' \ ' </tr>\n') MACHINE_SOFTWARELISTS_TABLE_EPILOGUE = string.Template( ' </tbody>\n' \ '</table>\n' \ '<script>\n' \ ' make_table_sortable(document.getElementById("tbl-softwarelists"));\n' \ ' if (!document.getElementById("tbl-softwarelists").tBodies[0].rows.length)\n' \ ' {\n' \ ' document.getElementById("heading-softwarelists").style.display = "none";\n' \ ' document.getElementById("tbl-softwarelists").style.display = "none";\n' \ ' }\n' \ '</script>\n') MACHINE_OPTIONS_HEADING = string.Template( '<h2>Options</h2>\n' \ '<p>\n' \ ' Format: <select id="select-options-format" onchange="update_cmd_preview()"><option value="cmd">Command line</option><option value="ini">INI file</option></select>\n' \ ' <input type="checkbox" id="check-explicit-defaults" onchange="update_cmd_preview()"><label for="check-explicit-defaults">Explicit defaults</label>\n' \ '</p>\n' \ '<p id="para-cmd-preview"></p>\n') MACHINE_BIOS_PROLOGUE = string.Template( '<h3>System BIOS</h3>' \ '<select id="select-system-bios" onchange="update_cmd_preview()">') MACHINE_BIOS_OPTION = string.Template( ' <option value="${name}" data-isdefault="${isdefault}">${name} - ${description}</option>\n') MACHINE_RAM_PROLOGUE = string.Template( '<h3>RAM Size</h3>' \ '<select id="select-ram-option" onchange="update_cmd_preview()">') MACHINE_RAM_OPTION = string.Template( ' <option value="${name}" data-isdefault="${isdefault}">${name} (${size})</option>\n') MACHINE_SLOTS_PLACEHOLDER_PROLOGUE = string.Template( '<h3>Slots</h3>\n' \ '<p id="para-slots-placeholder">Loading slot information&hellip;<p>\n' \ '<script>\n') MACHINE_SLOTS_PLACEHOLDER_EPILOGUE = string.Template( ' populate_slots(${machine});\n' '</script>\n') MACHINE_ROW = string.Template( ' <tr>\n' \ ' <td><a href="${machinehref}">${shortname}</a></td>\n' \ ' <td><a href="${machinehref}">${description}</a></td>\n' \ ' <td><a href="${sourcehref}">${sourcefile}</a></td>\n' \ ' </tr>\n') EXCL_MACHINE_ROW = string.Template( ' <tr>\n' \ ' <td><a href="${machinehref}">${shortname}</a></td>\n' \ ' <td></td>\n' \ ' <td></td>\n' \ ' </tr>\n') COMPATIBLE_SLOT_ROW = string.Template( ' <tr>\n' \ ' <td><a href="${machinehref}">${shortname}</a></td>\n' \ ' <td><a href="${machinehref}">${description}</a></td>\n' \ ' <td>${slot}</td>\n' \ ' <td>${slotoption}</td>\n' \ ' <td><a href="${sourcehref}">${sourcefile}</a></td>\n' \ ' </tr>\n') SOURCEFILE_PROLOGUE = string.Template( '<!DOCTYPE html>\n' \ '<html>\n' \ '<head>\n' \ ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' \ ' <meta http-equiv="Content-Style-Type" content="text/css">\n' \ ' <meta http-equiv="Content-Script-Type" content="text/javascript">\n' \ ' <link rel="stylesheet" type="text/css" href="${assets}/style.css">\n' \ ' <script type="text/javascript">var assetsurl="${assets}"</script>\n' \ ' <script type="text/javascript" src="${assets}/common.js"></script>\n' \ ' <title>Source File: ${filename}</title>\n' \ '</head>\n' \ '<body>\n' \ '<h1>${title}</h1>\n') SOURCEFILE_ROW_PARENT = string.Template( ' <tr>\n' \ ' <td><a href="${machinehref}">${shortname}</a></td>\n' \ ' <td><a href="${machinehref}">${description}</a></td>\n' \ ' <td>${year}</td>\n' \ ' <td>${manufacturer}</td>\n' \ ' <td>${runnable}</td>\n' \ ' <td></td>\n' \ ' </tr>\n') SOURCEFILE_ROW_CLONE = string.Template( ' <tr>\n' \ ' <td><a href="${machinehref}">${shortname}</a></td>\n' \ ' <td><a href="${machinehref}">${description}</a></td>\n' \ ' <td>${year}</td>\n' \ ' <td>${manufacturer}</td>\n' \ ' <td>${runnable}</td>\n' \ ' <td><a href="${parenthref}">${parent}</a></td>\n' \ ' </tr>\n') SOURCEFILE_LIST_PROLOGUE = string.Template( '<!DOCTYPE html>\n' \ '<html>\n' \ '<head>\n' \ ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' \ ' <meta http-equiv="Content-Style-Type" content="text/css">\n' \ ' <meta http-equiv="Content-Script-Type" content="text/javascript">\n' \ ' <link rel="stylesheet" type="text/css" href="${assets}/style.css">\n' \ ' <script type="text/javascript">var assetsurl="${assets}"</script>\n' \ ' <script type="text/javascript" src="${assets}/common.js"></script>\n' \ ' <title>${title}</title>\n' \ '</head>\n' \ '<body>\n' \ '<h1>${heading}</h1>\n' \ '<table id="tbl-sourcefiles">\n' \ ' <thead>\n' \ ' <tr>\n' \ ' <th>Source file</th>\n' \ ' <th class="numeric">Machines</th>\n' \ ' </tr>\n' \ ' </thead>\n' \ ' <tbody>\n') SOURCEFILE_LIST_ROW = string.Template( ' <tr>\n' \ ' <td>${sourcefile}</td>\n' \ ' <td style="text-align: right">${machines}</td>\n' \ ' </tr>\n') SOFTWARE_PROLOGUE = string.Template( '<!DOCTYPE html>\n' \ '<html>\n' \ '<head>\n' \ ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' \ ' <meta http-equiv="Content-Style-Type" content="text/css">\n' \ ' <meta http-equiv="Content-Script-Type" content="text/javascript">\n' \ ' <link rel="stylesheet" type="text/css" href="${assets}/style.css">\n' \ ' <script type="text/javascript">var assetsurl="${assets}"</script>\n' \ ' <script type="text/javascript" src="${assets}/common.js"></script>\n' \ ' <title>${title}</title>\n' \ '</head>\n' \ '<body>\n' \ '<h1>${heading}</h1>\n' \ '<table class="sysinfo">\n' \ ' <tr><th>Software list:</th><td><a href="${softwarelisthref}">${softwarelistdescription} (${softwarelist})</a></td></tr>\n' \ ' <tr><th>Short name:</th><td>${shortname}</td></tr>\n' \ ' <tr><th>Year:</th><td>${year}</td></tr>\n' \ ' <tr><th>Publisher:</th><td>${publisher}</td></tr>\n'); SOFTWARE_CLONES_PROLOGUE = string.Template( '<h2>Clones</h2>\n' \ '<table id="tbl-clones">\n' \ ' <thead>\n' \ ' <tr>\n' \ ' <th>Short name</th>\n' \ ' <th>Description</th>\n' \ ' <th>Year</th>\n' \ ' <th>Publisher</th>\n' \ ' <th>Supported</th>\n' \ ' </tr>\n' \ ' </thead>\n' \ ' <tbody>\n') SOFTWARE_CLONES_ROW = string.Template( ' <tr>\n' \ ' <td><a href="${href}">${shortname}</a></td>\n' \ ' <td><a href="${href}">${description}</a></td>\n' \ ' <td>${year}</td>\n' \ ' <td>${publisher}</td>\n' \ ' <td>${supported}</td>\n' \ ' </tr>\n') SOFTWARE_PART_PROLOGUE = string.Template( '<h3>${heading}</h3>\n' \ '<table class="sysinfo">\n' \ ' <tr><th>Short name:</th><td>${shortname}</td></tr>\n' \ ' <tr><th>Interface:</th><td>${interface}</td></tr>\n') SOFTWARELIST_PROLOGUE = string.Template( '<!DOCTYPE html>\n' \ '<html>\n' \ '<head>\n' \ ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' \ ' <meta http-equiv="Content-Style-Type" content="text/css">\n' \ ' <meta http-equiv="Content-Script-Type" content="text/javascript">\n' \ ' <link rel="stylesheet" type="text/css" href="${assets}/style.css">\n' \ ' <script type="text/javascript">var assetsurl="${assets}"</script>\n' \ ' <script type="text/javascript" src="${assets}/common.js"></script>\n' \ ' <title>${title}</title>\n' \ '</head>\n' \ '<body>\n' \ '<h1>${heading}</h1>\n' \ '<table class="sysinfo">\n' \ ' <tr>\n' \ ' <th>Short name:</th>\n' \ ' <td>${shortname}</td>\n' \ ' </tr>\n' \ ' <tr>\n' \ ' <th>Total:</th>\n' \ ' <td style="text-align: right">${total}</td>\n' \ ' </tr>\n' \ ' <tr>\n' \ ' <th>Supported:</th>\n' \ ' <td style="text-align: right">${supported}</td>\n' \ ' <td style="text-align: right">(${supportedpc}%)</td>\n' \ ' </tr>\n' \ ' <tr>\n' \ ' <th>Partially supported:</th>\n' \ ' <td style="text-align: right">${partiallysupported}</td>\n' \ ' <td style="text-align: right">(${partiallysupportedpc}%)</td>\n' \ ' </tr>\n' \ ' <tr>\n' \ ' <th>Unsupported:</th>\n' \ ' <td style="text-align: right">${unsupported}</td>\n' \ ' <td style="text-align: right">(${unsupportedpc}%)</td>\n' \ ' </tr>\n' \ '</table>\n') SOFTWARELIST_MACHINE_TABLE_HEADER = string.Template( '<h2>Machines</h2>\n' \ '<table id="tbl-machines">\n' \ ' <thead>\n' \ ' <tr>\n' \ ' <th>Short name</th>\n' \ ' <th>Description</th>\n' \ ' <th>Year</th>\n' \ ' <th>Manufacturer</th>\n' \ ' <th>Status</th>\n' \ ' </tr>\n' \ ' </thead>\n' \ ' <tbody>\n') SOFTWARELIST_MACHINE_TABLE_ROW = string.Template( ' <tr>\n' \ ' <td><a href="${machinehref}">${shortname}</a></td>\n' \ ' <td><a href="${machinehref}">${description}</a></td>\n' \ ' <td>${year}</td>\n' \ ' <td>${manufacturer}</td>\n' \ ' <td>${status}</td>\n' \ ' </tr>\n') SOFTWARELIST_SOFTWARE_TABLE_HEADER = string.Template( '<h2>Software</h2>\n' \ '<table id="tbl-software">\n' \ ' <thead>\n' \ ' <tr>\n' \ ' <th>Short name</th>\n' \ ' <th>Description</th>\n' \ ' <th>Year</th>\n' \ ' <th>Publisher</th>\n' \ ' <th>Supported</th>\n' \ ' <th class="numeric">Parts</th>\n' \ ' <th class="numeric">Bad dumps</th>\n' \ ' <th>Parent</th>\n' \ ' </tr>\n' \ ' </thead>\n' \ ' <tbody>\n') SOFTWARELIST_SOFTWARE_ROW = string.Template( ' <tr>\n' \ ' <td><a href="${softwarehref}">${shortname}</a></td>\n' \ ' <td><a href="${softwarehref}">${description}</a></td>\n' \ ' <td>${year}</td>\n' \ ' <td>${publisher}</td>\n' \ ' <td>${supported}</td>\n' \ ' <td style="text-align: right">${parts}</td>\n' \ ' <td style="text-align: right">${baddumps}</td>\n' \ ' <td>${parent}</td>\n' \ ' </tr>\n') SOFTWARELIST_LIST_PROLOGUE = string.Template( '<!DOCTYPE html>\n' \ '<html>\n' \ '<head>\n' \ ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' \ ' <meta http-equiv="Content-Style-Type" content="text/css">\n' \ ' <meta http-equiv="Content-Script-Type" content="text/javascript">\n' \ ' <link rel="stylesheet" type="text/css" href="${assets}/style.css">\n' \ ' <script type="text/javascript">var assetsurl="${assets}"</script>\n' \ ' <script type="text/javascript" src="${assets}/common.js"></script>\n' \ ' <title>${title}</title>\n' \ '</head>\n' \ '<body>\n' \ '<h1>${heading}</h1>\n' \ '<table id="tbl-softwarelists">\n' \ ' <thead>\n' \ ' <tr>\n' \ ' <th>Short name</th>\n' \ ' <th>Description</th>\n' \ ' <th class="numeric">Total</th>\n' \ ' <th class="numeric">Supported</th>\n' \ ' <th class="numeric">Partially supported</th>\n' \ ' <th class="numeric">Unsupported</th>\n' \ ' </tr>\n' \ ' </thead>\n' \ ' <tbody>\n') SOFTWARELIST_LIST_ROW = string.Template( ' <tr>\n' \ ' <td><a href="${href}">${shortname}</a></td>\n' \ ' <td><a href="${href}">${description}</a></td>\n' \ ' <td style="text-align: right">${total}</td>\n' \ ' <td style="text-align: right">${supported}</td>\n' \ ' <td style="text-align: right">${partiallysupported}</td>\n' \ ' <td style="text-align: right">${unsupported}</td>\n' \ ' </tr>\n') ROMIDENT_PAGE = string.Template( '<!DOCTYPE html>\n' \ '<html>\n' \ '<head>\n' \ ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' \ ' <meta http-equiv="Content-Style-Type" content="text/css">\n' \ ' <meta http-equiv="Content-Script-Type" content="text/javascript">\n' \ ' <link rel="stylesheet" type="text/css" href="${assets}/style.css">\n' \ ' <script type="text/javascript">\n' \ ' var appurl="${app}"\n' \ ' var assetsurl="${assets}"\n' \ ' </script>\n' \ ' <script type="text/javascript" src="${assets}/common.js"></script>\n' \ ' <script type="text/javascript" src="${assets}/digest.js"></script>\n' \ ' <script type="text/javascript" src="${assets}/romident.js"></script>\n' \ ' <title>Identify ROM/Disk Dumps</title>\n' \ '</head>\n' \ '<body>\n' \ '<h1>Identify ROM/Disk Dumps</h1>\n' \ '<p>No files are uploaded. Files are examined locally and checksums/digests are sent to the server. File checksums and digests may be logged on the server.</p>\n' \ '<div id="div-dropzone" class="dropzone" ondragover="div_dropzone_dragover(event)" ondrop="div_dropzone_drop(event)">\n' \ '<p><button type="button" onclick="document.getElementById(&quot;input-dumps&quot;).click()">Select ROM/disk dumps</button></p>\n' \ '<p>Drag and drop ROM/disk dump files here to identify them.</p>\n' \ '</div>\n' \ '<input id="input-dumps" type="file" multiple onchange="add_dump_files(this.files)" style="display: none">\n' \ '<div id="div-progress"></div>\n' \ '<div id="div-issues"></div>\n' \ '<div id="div-unmatched"></div>\n' \ '<div id="div-machines"></div>\n' \ '<div id="div-software"></div>\n' \ '</body>\n' \ '</html>\n')
gpl-2.0
5,022,746,982,623,831,000
43.085011
180
0.453415
false
Clinical-Genomics/scout
tests/server/test_links.py
1
2106
"""Tests for scout server links""" from scout.server.links import add_gene_links, cbioportal, mycancergenome, snp_links def test_add_gene_links(): """Test to add gene links to a gene object""" # GIVEN a minimal gene and a genome build gene_obj = {"hgnc_id": 257} build = 37 # WHEN adding the gene links add_gene_links(gene_obj, build) # THEN assert some links are added assert "hgnc_link" in gene_obj def test_add_hg38_gene_links(): """Test to add hg38 gene links to a gene object""" # GIVEN a minimal gene and a genome build gene_obj = {"hgnc_id": 257} build = 38 # WHEN adding the gene links add_gene_links(gene_obj, build) # THEN assert some links are added assert "hgnc_link" in gene_obj def test_ucsc_link(): """Test if ucsc link is correctly added""" # GIVEN a minimal gene and a genome build gene_obj = {"hgnc_id": 257, "ucsc_id": "uc001jwi.4"} build = 37 # WHEN adding the gene links add_gene_links(gene_obj, build) # THEN assert some links are added link = gene_obj.get("ucsc_link") assert link is not None def test_cbioportal_link(): """Test if CBioPortal link is made correctly""" hgnc_symbol = "TP53" protein_change = "p.Ser241Phe" link = cbioportal(hgnc_symbol, protein_change) assert link is not None def test_mycancergenome_link(): hgnc_symbol = "TP53" protein_change = "p.Ser241Phe" link = mycancergenome(hgnc_symbol, protein_change) assert link is not None def test_snp_links(): """Test building the links for the SNP ids of a variant""" # GIVEN a variant with multiple SNP IDs variant_obj = {"dbsnp_id": "rs150429680;431849"} links = snp_links(variant_obj) # THEN the links should point to the right database snp_ids = variant_obj["dbsnp_id"].split(";") for snp in snp_ids: if "rs" in snp: # dbSNP assert links[snp] == f"https://www.ncbi.nlm.nih.gov/snp/{snp}" else: # ClinVar variation assert links[snp] == f"https://www.ncbi.nlm.nih.gov/clinvar/variation/{snp}"
bsd-3-clause
-3,427,942,437,221,359,600
28.661972
88
0.647198
false
MaxHalford/Prince
prince/one_hot.py
1
1092
"""This module contains a custom one-hot encoder. It inherits from sklearn's OneHotEncoder and returns a pandas.SparseDataFrame with appropriate column names and index values. """ import itertools import numpy as np import pandas as pd from sklearn import preprocessing class OneHotEncoder(preprocessing.OneHotEncoder): def __init__(self): super().__init__(sparse=True, dtype=np.uint8, categories='auto') def fit(self, X, y=None): if not isinstance(X, pd.DataFrame): raise ValueError('X must be a pandas.DataFrame') self = super().fit(X) self.column_names_ = list(itertools.chain(*[ [ '{}_{}'.format(col, cat) for cat in self.categories_[i] ] for i, col in enumerate(X.columns) ])) return self def transform(self, X): return pd.SparseDataFrame( data=super().transform(X), columns=self.column_names_, index=X.index if isinstance(X, pd.DataFrame) else None, default_fill_value=0 )
mit
-2,456,115,523,759,489,000
27
76
0.604396
false
stvstnfrd/edx-platform
lms/djangoapps/instructor_task/management/commands/fail_old_tasks.py
5
3684
""" Commands to fail old tasks """ from datetime import datetime from textwrap import dedent from celery.states import FAILURE from django.core.management.base import BaseCommand, CommandError from pytz import utc from lms.djangoapps.instructor_task.models import PROGRESS, QUEUING, InstructorTask class Command(BaseCommand): """ Command to manually fail old "QUEUING" or "PROGRESS" tasks in the instructor task table. Example: ./manage.py lms fail_old_tasks QUEUING --dry-run --after 2001-01-03 \ --before 2001-01-06 --task-type bulk_course_email """ help = dedent(__doc__).strip() def add_arguments(self, parser): """ Add arguments to the command parser. """ parser.add_argument( "task_state", type=str, choices=[QUEUING, PROGRESS], help="choose the current task_state of tasks you want to fail" ) parser.add_argument( '--before', type=str, dest='before', help='Manually fail instructor tasks created before or on this date.', ) parser.add_argument( '--after', type=str, dest='after', help='Manually fail instructor tasks created after or on this date.', ) parser.add_argument( '--dry-run', action='store_true', dest='dry_run', default=False, help='Return the records this command will update without updating them.', ) parser.add_argument( '--task-type', dest='task_type', type=str, default=None, help='Specify the type of task that you want to fail.', ) @staticmethod def parse_date(date_string): """ Converts an isoformat string into a python datetime object. Localizes that datetime object to UTC. """ return utc.localize(datetime.strptime(date_string, "%Y-%m-%d")) def handle(self, *args, **options): if options['before'] is None: raise CommandError("Must provide a 'before' date") if options['after'] is None: raise CommandError("Must provide an 'after' date") before = self.parse_date(options['before']) after = self.parse_date(options['after']) filter_kwargs = { "task_state": options['task_state'], "created__lte": before, "created__gte": after, } if options['task_type'] is not None: filter_kwargs.update({"task_type": options['task_type']}) tasks = InstructorTask.objects.filter(**filter_kwargs) for task in tasks: print( "{task_state} task '{task_id}', of type '{task_type}', created on '{created}', will be marked as 'FAILURE'".format( # lint-amnesty, pylint: disable=line-too-long task_state=task.task_state, task_id=task.task_id, task_type=task.task_type, created=task.created, ) ) if not options['dry_run']: tasks_updated = tasks.update( task_state=FAILURE, ) print("{tasks_updated} records updated.".format( tasks_updated=tasks_updated )) else: print( "This was a dry run, so no records were updated. " "If this command were run for real, {number} records would have been updated.".format( number=tasks.count() ) )
agpl-3.0
7,202,504,289,924,054,000
29.7
178
0.546145
false
dmlc/tvm
python/tvm/contrib/nnpack.py
5
7835
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """External function interface to NNPACK libraries.""" import tvm from tvm import te import tvm._ffi def is_available(): """Check whether NNPACK is available, that is, `nnp_initialize()` returns `nnp_status_success`. """ return _initialize() == 0 def fully_connected_inference(lhs, rhs, nthreads=1): """Create an extern op that compute fully connected of 1D tensor lhs and 2D tensor rhs with nnpack. Parameters ---------- lhs : Tensor lhs 1D array input[input_channels] of FP32 elements rhs : Tensor lhs 2D matrix kernel[output_channels][input_channels] of FP32 elements Returns ------- C : Tensor lhs 1D array out[output_channels] of FP32 elements. """ m = rhs.shape[0] return te.extern( (m,), [lhs, rhs], lambda ins, outs: tvm.tir.call_packed( "tvm.contrib.nnpack.fully_connected_inference", ins[0], ins[1], outs[0], nthreads ), name="C", ) class ConvolutionAlgorithm: AUTO = 0 FFT_8x8 = 1 FFT_16x16 = 2 WT_8x8 = 3 IMPLICIT_GEMM = 4 DIRECT = 5 WT_8x8_FP16 = 6 class ConvolutionTransformStrategy: COMPUTE = 1 PRECOMPUTE = 2 def convolution_inference( data, kernel, bias, padding, stride, nthreads=1, algorithm=ConvolutionAlgorithm.AUTO ): """Create an extern op to do inference convolution of 4D tensor data and 4D tensor kernel and 1D tensor bias with nnpack. Parameters ---------- data : Tensor data 4D tensor input[batch][input_channels][input_height][input_width] of FP32 elements. kernel : Tensor kernel 4D tensor kernel[output_channels][input_channels][kernel_height] [kernel_width] of FP32 elements. bias : Tensor bias 1D array bias[output_channels][input_channels][kernel_height] [kernel_width] of FP32 elements. padding : list padding A 4-dim list of [pad_top, pad_bottom, pad_left, pad_right], which indicates the padding around the feature map. stride : list stride A 2-dim list of [stride_height, stride_width], which indicates the stride. Returns ------- output : Tensor output 4D tensor output[batch][output_channels][output_height][output_width] of FP32 elements. """ assert isinstance(padding, list) and len(padding) == 4 assert isinstance(stride, list) and len(stride) == 2 batch, _, input_height, input_width = data.shape output_channels, _, kernel_height, kernel_width = kernel.shape idxdiv = te.indexdiv output_height = idxdiv(input_height + padding[0] + padding[1] - kernel_height, stride[0]) + 1 output_width = idxdiv(input_width + padding[0] + padding[1] - kernel_width, stride[1]) + 1 return te.extern( (batch, output_channels, output_height, output_width), [data, kernel, bias] if bias is not None else [data, kernel], lambda ins, outs: tvm.tir.call_packed( "tvm.contrib.nnpack.convolution_inference", ins[0], ins[1], ins[2] if bias is not None else 0, outs[0], padding[0], padding[1], padding[2], padding[3], stride[0], stride[1], nthreads, algorithm, ), name="C", ) def convolution_inference_without_weight_transform( data, transformed_kernel, bias, padding, stride, nthreads=1, algorithm=ConvolutionAlgorithm.AUTO ): """Create an extern op to do inference convolution of 4D tensor data and 4D pre-transformed tensor kernel and 1D tensor bias with nnpack. Parameters ---------- data : Tensor data 4D tensor input[batch][input_channels][input_height][input_width] of FP32 elements. transformed_kernel : Tensor transformed_kernel 4D tensor kernel[output_channels][input_channels][tile] [tile] of FP32 elements. bias : Tensor bias 1D array bias[output_channels][input_channels][kernel_height] [kernel_width] of FP32 elements. padding : list padding A 4-dim list of [pad_top, pad_bottom, pad_left, pad_right], which indicates the padding around the feature map. stride : list stride A 2-dim list of [stride_height, stride_width], which indicates the stride. Returns ------- output : Tensor output 4D tensor output[batch][output_channels][output_height][output_width] of FP32 elements. """ assert algorithm in (ConvolutionAlgorithm.WT_8x8, ConvolutionAlgorithm.WT_8x8_FP16) assert isinstance(padding, list) and len(padding) == 4 assert isinstance(stride, list) and len(stride) == 2 batch, _, input_height, input_width = data.shape output_channels, _, _, _ = transformed_kernel.shape kernel_height, kernel_width = (3, 3) idxdiv = te.indexdiv output_height = idxdiv(input_height + padding[0] + padding[1] - kernel_height, stride[0]) + 1 output_width = idxdiv(input_width + padding[0] + padding[1] - kernel_width, stride[1]) + 1 return te.extern( (batch, output_channels, output_height, output_width), [data, transformed_kernel, bias] if bias is not None else [data, transformed_kernel], lambda ins, outs: tvm.tir.call_packed( "tvm.contrib.nnpack.convolution_inference_without_weight_transform", ins[0], ins[1], ins[2] if bias is not None else 0, outs[0], padding[0], padding[1], padding[2], padding[3], stride[0], stride[1], nthreads, algorithm, ), name="C", dtype="float32", ) def convolution_inference_weight_transform( kernel, nthreads=1, algorithm=ConvolutionAlgorithm.AUTO, dtype="float32" ): """Create an extern op to do inference convolution of 3D tensor data and 4D tensor kernel and 1D tensor bias with nnpack. Parameters ---------- kernel : Tensor kernel 4D tensor kernel[output_channels][input_channels][kernel_height] [kernel_width] of FP32 elements. Returns ------- output : Tensor output 4D tensor output[output_channels][input_channels][tile][tile] of FP32 elements. """ assert algorithm in (ConvolutionAlgorithm.WT_8x8, ConvolutionAlgorithm.WT_8x8_FP16) output_channels, input_channels, _, _ = kernel.shape transform_tile_size = 8 if not isinstance(dtype, str): dtype = dtype.dtype return te.extern( (output_channels, input_channels, transform_tile_size, transform_tile_size), [kernel], lambda ins, outs: tvm.tir.call_packed( "tvm.contrib.nnpack.convolution_inference_weight_transform", ins[0], outs[0], nthreads, algorithm, ), name="transform_kernel", dtype=dtype, ) tvm._ffi._init_api("tvm.contrib.nnpack")
apache-2.0
-1,966,758,172,275,899,100
32.340426
100
0.632546
false