repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
fairbird/OpenPLI-BlackHole
lib/python/Tools/Downloader.py
1
2450
from twisted.web import client from twisted.internet import reactor, defer from twisted.python import failure from urlparse import urlparse class HTTPProgressDownloader(client.HTTPDownloader): def __init__(self, url, outfile, headers=None): client.HTTPDownloader.__init__(self, url, outfile, headers=headers, agent="Enigma2 HbbTV/1.1.1 (+PVR+RTSP+DL;BlackHole;;;)") self.status = self.progress_callback = self.error_callback = self.end_callback = None self.deferred = defer.Deferred() def noPage(self, reason): if self.status == "304": client.HTTPDownloader.page(self, "") else: client.HTTPDownloader.noPage(self, reason) if self.error_callback: self.error_callback(reason.getErrorMessage(), self.status) def gotHeaders(self, headers): if self.status == "200": if headers.has_key("content-length"): self.totalbytes = int(headers["content-length"][0]) else: self.totalbytes = 0 self.currentbytes = 0.0 return client.HTTPDownloader.gotHeaders(self, headers) def pagePart(self, packet): if self.status == "200": self.currentbytes += len(packet) if self.totalbytes and self.progress_callback: self.progress_callback(self.currentbytes, self.totalbytes) return client.HTTPDownloader.pagePart(self, packet) def pageEnd(self): ret = client.HTTPDownloader.pageEnd(self) if self.end_callback: self.end_callback() return ret class downloadWithProgress: def __init__(self, url, outputfile, contextFactory=None, *args, **kwargs): parsed = urlparse(url) scheme = parsed.scheme host = parsed.hostname port = parsed.port or (443 if scheme == 'https' else 80) self.factory = HTTPProgressDownloader(url, outputfile, *args, **kwargs) if scheme == 'https': from twisted.internet import ssl if contextFactory is None: contextFactory = ssl.ClientContextFactory() self.connection = reactor.connectSSL(host, port, self.factory, contextFactory) else: self.connection = reactor.connectTCP(host, port, self.factory) def start(self): return self.factory.deferred def stop(self): self.factory.progress_callback = self.factory.end_callback = self.factory.error_callback = None self.connection.disconnect() def addProgress(self, progress_callback): self.factory.progress_callback = progress_callback def addEnd(self, end_callback): self.factory.end_callback = end_callback def addError(self, error_callback): self.factory.error_callback = error_callback
gpl-2.0
EricSchles/regulations-core
regcore/migrations/0008_auto__del_field_notice_cfr_part.py
4
3811
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Notice.cfr_part' db.delete_column(u'regcore_notice', 'cfr_part') def backwards(self, orm): # Adding field 'Notice.cfr_part' db.add_column(u'regcore_notice', 'cfr_part', self.gf('django.db.models.fields.SlugField')(default='????', max_length=10), keep_default=False) models = { u'regcore.diff': { 'Meta': {'unique_together': "(('label', 'old_version', 'new_version'),)", 'object_name': 'Diff', 'index_together': "(('label', 'old_version', 'new_version'),)"}, 'diff': ('regcore.fields.CompressedJSONField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'new_version': ('django.db.models.fields.SlugField', [], {'max_length': '20'}), 'old_version': ('django.db.models.fields.SlugField', [], {'max_length': '20'}) }, u'regcore.layer': { 'Meta': {'unique_together': "(('version', 'name', 'label'),)", 'object_name': 'Layer', 'index_together': "(('version', 'name', 'label'),)"}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'layer': ('regcore.fields.CompressedJSONField', [], {}), 'name': ('django.db.models.fields.SlugField', [], {'max_length': '20'}), 'version': ('django.db.models.fields.SlugField', [], {'max_length': '20'}) }, u'regcore.notice': { 'Meta': {'object_name': 'Notice'}, 'document_number': ('django.db.models.fields.SlugField', [], {'max_length': '20', 'primary_key': 'True'}), 'effective_on': ('django.db.models.fields.DateField', [], {'null': 'True'}), 'fr_url': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'notice': ('regcore.fields.CompressedJSONField', [], {}), 'publication_date': ('django.db.models.fields.DateField', [], {}) }, u'regcore.noticecfrpart': { 'Meta': {'unique_together': "(('notice', 'cfr_part'),)", 'object_name': 'NoticeCFRPart', 'index_together': "(('notice', 'cfr_part'),)"}, 'cfr_part': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '10'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'notice': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['regcore.Notice']"}) }, u'regcore.regulation': { 'Meta': {'unique_together': "(('version', 'label_string'),)", 'object_name': 'Regulation', 'index_together': "(('version', 'label_string'),)"}, 'children': ('regcore.fields.CompressedJSONField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label_string': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'node_type': ('django.db.models.fields.SlugField', [], {'max_length': '10'}), 'root': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'text': ('django.db.models.fields.TextField', [], {}), 'title': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'version': ('django.db.models.fields.SlugField', [], {'max_length': '20'}) } } complete_apps = ['regcore']
cc0-1.0
gptech/ansible
lib/ansible/modules/cloud/univention/udm_dns_record.py
69
5961
#!/usr/bin/python # -*- coding: UTF-8 -*- # Copyright (c) 2016, Adfinis SyGroup AG # Tobias Rueetschi <tobias.ruetschi@adfinis-sygroup.ch> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: udm_dns_record version_added: "2.2" author: "Tobias Rueetschi (@2-B)" short_description: Manage dns entries on a univention corporate server description: - "This module allows to manage dns records on a univention corporate server (UCS). It uses the python API of the UCS to create a new object or edit it." requirements: - Python >= 2.6 - Univention options: state: required: false default: "present" choices: [ present, absent ] description: - Whether the dns record is present or not. name: required: true description: - "Name of the record, this is also the DNS record. E.g. www for www.example.com." zone: required: true description: - Corresponding DNS zone for this record, e.g. example.com. type: required: true choices: [ host_record, alias, ptr_record, srv_record, txt_record ] description: - "Define the record type. C(host_record) is a A or AAAA record, C(alias) is a CNAME, C(ptr_record) is a PTR record, C(srv_record) is a SRV record and C(txt_record) is a TXT record." data: required: false default: [] description: - "Additional data for this record, e.g. ['a': '192.0.2.1']. Required if C(state=present)." ''' EXAMPLES = ''' # Create a DNS record on a UCS - udm_dns_zone: name: www zone: example.com type: host_record data: - a: 192.0.2.1 ''' RETURN = '''# ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.univention_umc import ( umc_module_for_add, umc_module_for_edit, ldap_search, base_dn, config, uldap, ) HAVE_UNIVENTION = False try: from univention.admin.handlers.dns import ( forward_zone, reverse_zone, ) HAVE_UNIVENTION = True except ImportError: pass def main(): module = AnsibleModule( argument_spec = dict( type = dict(required=True, type='str'), zone = dict(required=True, type='str'), name = dict(required=True, type='str'), data = dict(default=[], type='dict'), state = dict(default='present', choices=['present', 'absent'], type='str') ), supports_check_mode=True, required_if = ([ ('state', 'present', ['data']) ]) ) if not HAVE_UNIVENTION: module.fail_json(msg="This module requires univention python bindings") type = module.params['type'] zone = module.params['zone'] name = module.params['name'] data = module.params['data'] state = module.params['state'] changed = False obj = list(ldap_search( '(&(objectClass=dNSZone)(zoneName={})(relativeDomainName={}))'.format(zone, name), attr=['dNSZone'] )) exists = bool(len(obj)) container = 'zoneName={},cn=dns,{}'.format(zone, base_dn()) dn = 'relativeDomainName={},{}'.format(name, container) if state == 'present': try: if not exists: so = forward_zone.lookup( config(), uldap(), '(zone={})'.format(zone), scope='domain', ) or reverse_zone.lookup( config(), uldap(), '(zone={})'.format(zone), scope='domain', ) obj = umc_module_for_add('dns/{}'.format(type), container, superordinate=so[0]) else: obj = umc_module_for_edit('dns/{}'.format(type), dn) obj['name'] = name for k, v in data.items(): obj[k] = v diff = obj.diff() changed = obj.diff() != [] if not module.check_mode: if not exists: obj.create() else: obj.modify() except BaseException as e: module.fail_json( msg='Creating/editing dns entry {} in {} failed: {}'.format(name, container, e) ) if state == 'absent' and exists: try: obj = umc_module_for_edit('dns/{}'.format(type), dn) if not module.check_mode: obj.remove() changed = True except BaseException as e: module.fail_json( msg='Removing dns entry {} in {} failed: {}'.format(name, container, e) ) module.exit_json( changed=changed, name=name, diff=diff, container=container ) if __name__ == '__main__': main()
gpl-3.0
unho/pootle
pootle/i18n/formatter.py
7
1216
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from __future__ import absolute_import from babel import (UnknownLocaleError, core as babel_core, support as babel_support) from django.conf import settings from django.utils.translation import get_language, to_locale def get_locale_formats(locale=None): languages = [locale] if locale else [] languages += [get_language(), settings.LANGUAGE_CODE, 'en-us'] for language in languages: try: locale = babel_core.Locale.parse(to_locale(language)) break except UnknownLocaleError: continue return babel_support.Format(locale) def _clean_zero(number): if number is None or number == '': return 0 return number def number(number): number = _clean_zero(number) return get_locale_formats().number(number) def percent(number, format=None): number = _clean_zero(number) return get_locale_formats().percent(number, format)
gpl-3.0
mrquim/mrquimrepo
repo/plugin.video.mrpiracy/resources/lib/definicoes.py
4
1692
#!/usr/bin/python # -*- coding: utf-8 -*- import os,xbmc,xbmcaddon,xbmcplugin,xbmcgui,xbmcvfs,sys,urllib,urllib2,unicodedata,re,urlparse,json,base64 import threading from datetime import datetime import controlo def getQualidade(): return controlo.addon.getSetting('qualidadeFilmes') def vista_menu(): opcao = controlo.addon.getSetting('menuView') if opcao == '0': xbmc.executebuiltin("Container.SetViewMode(50)") elif opcao == '1': xbmc.executebuiltin("Container.SetViewMode(51") def vista_filmesSeries(): opcao = controlo.addon.getSetting('filmesSeriesView') if opcao == '0': xbmc.executebuiltin("Container.SetViewMode(50)") elif opcao == '1': xbmc.executebuiltin("Container.SetViewMode(51)") elif opcao == '2': xbmc.executebuiltin("Container.SetViewMode(500)") elif opcao == '3': xbmc.executebuiltin("Container.SetViewMode(501)") elif opcao == '4': xbmc.executebuiltin("Container.SetViewMode(508)") elif opcao == '5': xbmc.executebuiltin("Container.SetViewMode(504)") elif opcao == '6': xbmc.executebuiltin("Container.SetViewMode(503)") elif opcao == '7': xbmc.executebuiltin("Container.SetViewMode(515)") def vista_temporadas(): opcao = controlo.addon.getSetting('temporadasView') if opcao == '0': xbmc.executebuiltin("Container.SetViewMode(50)") elif opcao == '1': xbmc.executebuiltin("Container.SetViewMode(51)") elif opcao == '2': xbmc.executebuiltin("Container.SetViewMode(500)") def vista_episodios(): opcao = controlo.addon.getSetting('episodiosView') if opcao == '0': xbmc.executebuiltin("Container.SetViewMode(50)") elif opcao == '1': xbmc.executebuiltin("Container.SetViewMode(51)") elif opcao == '2': xbmc.executebuiltin("Container.SetViewMode(500)")
gpl-2.0
ecohealthalliance/tangelo
tangelo/tangelo/ws4py/compat.py
22
1107
# -*- coding: utf-8 -*- __doc__ = """ This compatibility module is inspired by the one found in CherryPy. It provides a common entry point for the various functions and types that are used with ws4py but which differ from Python 2.x to Python 3.x There are likely better ways for some of them so feel free to provide patches. Note this has been tested against 2.7 and 3.3 only but should hopefully work fine with other versions too. """ import sys if sys.version_info >= (3, 0): py3k = True from urllib.parse import urlsplit range = range unicode = str basestring = (bytes, str) _ord = ord def get_connection(fileobj): return fileobj.raw._sock def detach_connection(fileobj): fileobj.detach() def ord(c): if isinstance(c, int): return c return _ord(c) else: py3k = False from urlparse import urlsplit range = xrange unicode = unicode basestring = basestring ord = ord def get_connection(fileobj): return fileobj._sock def detach_connection(fileobj): fileobj._sock = None
apache-2.0
Lh4cKg/sl4a
python/src/Lib/distutils/command/build.py
53
5598
"""distutils.command.build Implements the Distutils 'build' command.""" # This module should be kept compatible with Python 2.1. __revision__ = "$Id: build.py 62197 2008-04-07 01:53:39Z mark.hammond $" import sys, os from distutils.core import Command from distutils.errors import DistutilsOptionError from distutils.util import get_platform def show_compilers (): from distutils.ccompiler import show_compilers show_compilers() class build (Command): description = "build everything needed to install" user_options = [ ('build-base=', 'b', "base directory for build library"), ('build-purelib=', None, "build directory for platform-neutral distributions"), ('build-platlib=', None, "build directory for platform-specific distributions"), ('build-lib=', None, "build directory for all distribution (defaults to either " + "build-purelib or build-platlib"), ('build-scripts=', None, "build directory for scripts"), ('build-temp=', 't', "temporary build directory"), ('plat-name=', 'p', "platform name to build for, if supported " "(default: %s)" % get_platform()), ('compiler=', 'c', "specify the compiler type"), ('debug', 'g', "compile extensions and libraries with debugging information"), ('force', 'f', "forcibly build everything (ignore file timestamps)"), ('executable=', 'e', "specify final destination interpreter path (build.py)"), ] boolean_options = ['debug', 'force'] help_options = [ ('help-compiler', None, "list available compilers", show_compilers), ] def initialize_options (self): self.build_base = 'build' # these are decided only after 'build_base' has its final value # (unless overridden by the user or client) self.build_purelib = None self.build_platlib = None self.build_lib = None self.build_temp = None self.build_scripts = None self.compiler = None self.plat_name = None self.debug = None self.force = 0 self.executable = None def finalize_options (self): if self.plat_name is None: self.plat_name = get_platform() else: # plat-name only supported for windows (other platforms are # supported via ./configure flags, if at all). Avoid misleading # other platforms. if os.name != 'nt': raise DistutilsOptionError( "--plat-name only supported on Windows (try " "using './configure --help' on your platform)") plat_specifier = ".%s-%s" % (self.plat_name, sys.version[0:3]) # Make it so Python 2.x and Python 2.x with --with-pydebug don't # share the same build directories. Doing so confuses the build # process for C modules if hasattr(sys, 'gettotalrefcount'): plat_specifier += '-pydebug' # 'build_purelib' and 'build_platlib' just default to 'lib' and # 'lib.<plat>' under the base build directory. We only use one of # them for a given distribution, though -- if self.build_purelib is None: self.build_purelib = os.path.join(self.build_base, 'lib') if self.build_platlib is None: self.build_platlib = os.path.join(self.build_base, 'lib' + plat_specifier) # 'build_lib' is the actual directory that we will use for this # particular module distribution -- if user didn't supply it, pick # one of 'build_purelib' or 'build_platlib'. if self.build_lib is None: if self.distribution.ext_modules: self.build_lib = self.build_platlib else: self.build_lib = self.build_purelib # 'build_temp' -- temporary directory for compiler turds, # "build/temp.<plat>" if self.build_temp is None: self.build_temp = os.path.join(self.build_base, 'temp' + plat_specifier) if self.build_scripts is None: self.build_scripts = os.path.join(self.build_base, 'scripts-' + sys.version[0:3]) if self.executable is None: self.executable = os.path.normpath(sys.executable) # finalize_options () def run (self): # Run all relevant sub-commands. This will be some subset of: # - build_py - pure Python modules # - build_clib - standalone C libraries # - build_ext - Python extensions # - build_scripts - (Python) scripts for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) # -- Predicates for the sub-command list --------------------------- def has_pure_modules (self): return self.distribution.has_pure_modules() def has_c_libraries (self): return self.distribution.has_c_libraries() def has_ext_modules (self): return self.distribution.has_ext_modules() def has_scripts (self): return self.distribution.has_scripts() sub_commands = [('build_py', has_pure_modules), ('build_clib', has_c_libraries), ('build_ext', has_ext_modules), ('build_scripts', has_scripts), ] # class build
apache-2.0
balloob/home-assistant
homeassistant/components/sentry/const.py
16
1119
"""Constants for the sentry integration.""" import logging DOMAIN = "sentry" CONF_DSN = "dsn" CONF_ENVIRONMENT = "environment" CONF_EVENT_CUSTOM_COMPONENTS = "event_custom_components" CONF_EVENT_HANDLED = "event_handled" CONF_EVENT_THIRD_PARTY_PACKAGES = "event_third_party_packages" CONF_LOGGING_EVENT_LEVEL = "logging_event_level" CONF_LOGGING_LEVEL = "logging_level" CONF_TRACING = "tracing" CONF_TRACING_SAMPLE_RATE = "tracing_sample_rate" DEFAULT_LOGGING_EVENT_LEVEL = logging.ERROR DEFAULT_LOGGING_LEVEL = logging.WARNING DEFAULT_TRACING_SAMPLE_RATE = 1.0 LOGGING_LEVELS = { logging.DEBUG: "debug", logging.INFO: "info", logging.WARNING: "warning", logging.ERROR: "error", logging.CRITICAL: "critical", } ENTITY_COMPONENTS = [ "air_quality", "alarm_control_panel", "binary_sensor", "calendar", "camera", "climate", "cover", "device_tracker", "fan", "geo_location", "group", "humidifier", "light", "lock", "media_player", "remote", "scene", "sensor", "switch", "vacuum", "water_heater", "weather", ]
apache-2.0
XuanyuZhao1984/MeanJS_train1
node_modules/gulp-sass/node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/__init__.py
1524
22178
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import copy import gyp.input import optparse import os.path import re import shlex import sys import traceback from gyp.common import GypError # Default debug modes for GYP debug = {} # List of "official" debug modes, but you can use anything you like. DEBUG_GENERAL = 'general' DEBUG_VARIABLES = 'variables' DEBUG_INCLUDES = 'includes' def DebugOutput(mode, message, *args): if 'all' in gyp.debug or mode in gyp.debug: ctx = ('unknown', 0, 'unknown') try: f = traceback.extract_stack(limit=2) if f: ctx = f[0][:3] except: pass if args: message %= args print '%s:%s:%d:%s %s' % (mode.upper(), os.path.basename(ctx[0]), ctx[1], ctx[2], message) def FindBuildFiles(): extension = '.gyp' files = os.listdir(os.getcwd()) build_files = [] for file in files: if file.endswith(extension): build_files.append(file) return build_files def Load(build_files, format, default_variables={}, includes=[], depth='.', params=None, check=False, circular_check=True, duplicate_basename_check=True): """ Loads one or more specified build files. default_variables and includes will be copied before use. Returns the generator for the specified format and the data returned by loading the specified build files. """ if params is None: params = {} if '-' in format: format, params['flavor'] = format.split('-', 1) default_variables = copy.copy(default_variables) # Default variables provided by this program and its modules should be # named WITH_CAPITAL_LETTERS to provide a distinct "best practice" namespace, # avoiding collisions with user and automatic variables. default_variables['GENERATOR'] = format default_variables['GENERATOR_FLAVOR'] = params.get('flavor', '') # Format can be a custom python file, or by default the name of a module # within gyp.generator. if format.endswith('.py'): generator_name = os.path.splitext(format)[0] path, generator_name = os.path.split(generator_name) # Make sure the path to the custom generator is in sys.path # Don't worry about removing it once we are done. Keeping the path # to each generator that is used in sys.path is likely harmless and # arguably a good idea. path = os.path.abspath(path) if path not in sys.path: sys.path.insert(0, path) else: generator_name = 'gyp.generator.' + format # These parameters are passed in order (as opposed to by key) # because ActivePython cannot handle key parameters to __import__. generator = __import__(generator_name, globals(), locals(), generator_name) for (key, val) in generator.generator_default_variables.items(): default_variables.setdefault(key, val) # Give the generator the opportunity to set additional variables based on # the params it will receive in the output phase. if getattr(generator, 'CalculateVariables', None): generator.CalculateVariables(default_variables, params) # Give the generator the opportunity to set generator_input_info based on # the params it will receive in the output phase. if getattr(generator, 'CalculateGeneratorInputInfo', None): generator.CalculateGeneratorInputInfo(params) # Fetch the generator specific info that gets fed to input, we use getattr # so we can default things and the generators only have to provide what # they need. generator_input_info = { 'non_configuration_keys': getattr(generator, 'generator_additional_non_configuration_keys', []), 'path_sections': getattr(generator, 'generator_additional_path_sections', []), 'extra_sources_for_rules': getattr(generator, 'generator_extra_sources_for_rules', []), 'generator_supports_multiple_toolsets': getattr(generator, 'generator_supports_multiple_toolsets', False), 'generator_wants_static_library_dependencies_adjusted': getattr(generator, 'generator_wants_static_library_dependencies_adjusted', True), 'generator_wants_sorted_dependencies': getattr(generator, 'generator_wants_sorted_dependencies', False), 'generator_filelist_paths': getattr(generator, 'generator_filelist_paths', None), } # Process the input specific to this generator. result = gyp.input.Load(build_files, default_variables, includes[:], depth, generator_input_info, check, circular_check, duplicate_basename_check, params['parallel'], params['root_targets']) return [generator] + result def NameValueListToDict(name_value_list): """ Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary of the pairs. If a string is simply NAME, then the value in the dictionary is set to True. If VALUE can be converted to an integer, it is. """ result = { } for item in name_value_list: tokens = item.split('=', 1) if len(tokens) == 2: # If we can make it an int, use that, otherwise, use the string. try: token_value = int(tokens[1]) except ValueError: token_value = tokens[1] # Set the variable to the supplied value. result[tokens[0]] = token_value else: # No value supplied, treat it as a boolean and set it. result[tokens[0]] = True return result def ShlexEnv(env_name): flags = os.environ.get(env_name, []) if flags: flags = shlex.split(flags) return flags def FormatOpt(opt, value): if opt.startswith('--'): return '%s=%s' % (opt, value) return opt + value def RegenerateAppendFlag(flag, values, predicate, env_name, options): """Regenerate a list of command line flags, for an option of action='append'. The |env_name|, if given, is checked in the environment and used to generate an initial list of options, then the options that were specified on the command line (given in |values|) are appended. This matches the handling of environment variables and command line flags where command line flags override the environment, while not requiring the environment to be set when the flags are used again. """ flags = [] if options.use_environment and env_name: for flag_value in ShlexEnv(env_name): value = FormatOpt(flag, predicate(flag_value)) if value in flags: flags.remove(value) flags.append(value) if values: for flag_value in values: flags.append(FormatOpt(flag, predicate(flag_value))) return flags def RegenerateFlags(options): """Given a parsed options object, and taking the environment variables into account, returns a list of flags that should regenerate an equivalent options object (even in the absence of the environment variables.) Any path options will be normalized relative to depth. The format flag is not included, as it is assumed the calling generator will set that as appropriate. """ def FixPath(path): path = gyp.common.FixIfRelativePath(path, options.depth) if not path: return os.path.curdir return path def Noop(value): return value # We always want to ignore the environment when regenerating, to avoid # duplicate or changed flags in the environment at the time of regeneration. flags = ['--ignore-environment'] for name, metadata in options._regeneration_metadata.iteritems(): opt = metadata['opt'] value = getattr(options, name) value_predicate = metadata['type'] == 'path' and FixPath or Noop action = metadata['action'] env_name = metadata['env_name'] if action == 'append': flags.extend(RegenerateAppendFlag(opt, value, value_predicate, env_name, options)) elif action in ('store', None): # None is a synonym for 'store'. if value: flags.append(FormatOpt(opt, value_predicate(value))) elif options.use_environment and env_name and os.environ.get(env_name): flags.append(FormatOpt(opt, value_predicate(os.environ.get(env_name)))) elif action in ('store_true', 'store_false'): if ((action == 'store_true' and value) or (action == 'store_false' and not value)): flags.append(opt) elif options.use_environment and env_name: print >>sys.stderr, ('Warning: environment regeneration unimplemented ' 'for %s flag %r env_name %r' % (action, opt, env_name)) else: print >>sys.stderr, ('Warning: regeneration unimplemented for action %r ' 'flag %r' % (action, opt)) return flags class RegeneratableOptionParser(optparse.OptionParser): def __init__(self): self.__regeneratable_options = {} optparse.OptionParser.__init__(self) def add_option(self, *args, **kw): """Add an option to the parser. This accepts the same arguments as OptionParser.add_option, plus the following: regenerate: can be set to False to prevent this option from being included in regeneration. env_name: name of environment variable that additional values for this option come from. type: adds type='path', to tell the regenerator that the values of this option need to be made relative to options.depth """ env_name = kw.pop('env_name', None) if 'dest' in kw and kw.pop('regenerate', True): dest = kw['dest'] # The path type is needed for regenerating, for optparse we can just treat # it as a string. type = kw.get('type') if type == 'path': kw['type'] = 'string' self.__regeneratable_options[dest] = { 'action': kw.get('action'), 'type': type, 'env_name': env_name, 'opt': args[0], } optparse.OptionParser.add_option(self, *args, **kw) def parse_args(self, *args): values, args = optparse.OptionParser.parse_args(self, *args) values._regeneration_metadata = self.__regeneratable_options return values, args def gyp_main(args): my_name = os.path.basename(sys.argv[0]) parser = RegeneratableOptionParser() usage = 'usage: %s [options ...] [build_file ...]' parser.set_usage(usage.replace('%s', '%prog')) parser.add_option('--build', dest='configs', action='append', help='configuration for build after project generation') parser.add_option('--check', dest='check', action='store_true', help='check format of gyp files') parser.add_option('--config-dir', dest='config_dir', action='store', env_name='GYP_CONFIG_DIR', default=None, help='The location for configuration files like ' 'include.gypi.') parser.add_option('-d', '--debug', dest='debug', metavar='DEBUGMODE', action='append', default=[], help='turn on a debugging ' 'mode for debugging GYP. Supported modes are "variables", ' '"includes" and "general" or "all" for all of them.') parser.add_option('-D', dest='defines', action='append', metavar='VAR=VAL', env_name='GYP_DEFINES', help='sets variable VAR to value VAL') parser.add_option('--depth', dest='depth', metavar='PATH', type='path', help='set DEPTH gyp variable to a relative path to PATH') parser.add_option('-f', '--format', dest='formats', action='append', env_name='GYP_GENERATORS', regenerate=False, help='output formats to generate') parser.add_option('-G', dest='generator_flags', action='append', default=[], metavar='FLAG=VAL', env_name='GYP_GENERATOR_FLAGS', help='sets generator flag FLAG to VAL') parser.add_option('--generator-output', dest='generator_output', action='store', default=None, metavar='DIR', type='path', env_name='GYP_GENERATOR_OUTPUT', help='puts generated build files under DIR') parser.add_option('--ignore-environment', dest='use_environment', action='store_false', default=True, regenerate=False, help='do not read options from environment variables') parser.add_option('-I', '--include', dest='includes', action='append', metavar='INCLUDE', type='path', help='files to include in all loaded .gyp files') # --no-circular-check disables the check for circular relationships between # .gyp files. These relationships should not exist, but they've only been # observed to be harmful with the Xcode generator. Chromium's .gyp files # currently have some circular relationships on non-Mac platforms, so this # option allows the strict behavior to be used on Macs and the lenient # behavior to be used elsewhere. # TODO(mark): Remove this option when http://crbug.com/35878 is fixed. parser.add_option('--no-circular-check', dest='circular_check', action='store_false', default=True, regenerate=False, help="don't check for circular relationships between files") # --no-duplicate-basename-check disables the check for duplicate basenames # in a static_library/shared_library project. Visual C++ 2008 generator # doesn't support this configuration. Libtool on Mac also generates warnings # when duplicate basenames are passed into Make generator on Mac. # TODO(yukawa): Remove this option when these legacy generators are # deprecated. parser.add_option('--no-duplicate-basename-check', dest='duplicate_basename_check', action='store_false', default=True, regenerate=False, help="don't check for duplicate basenames") parser.add_option('--no-parallel', action='store_true', default=False, help='Disable multiprocessing') parser.add_option('-S', '--suffix', dest='suffix', default='', help='suffix to add to generated files') parser.add_option('--toplevel-dir', dest='toplevel_dir', action='store', default=None, metavar='DIR', type='path', help='directory to use as the root of the source tree') parser.add_option('-R', '--root-target', dest='root_targets', action='append', metavar='TARGET', help='include only TARGET and its deep dependencies') options, build_files_arg = parser.parse_args(args) build_files = build_files_arg # Set up the configuration directory (defaults to ~/.gyp) if not options.config_dir: home = None home_dot_gyp = None if options.use_environment: home_dot_gyp = os.environ.get('GYP_CONFIG_DIR', None) if home_dot_gyp: home_dot_gyp = os.path.expanduser(home_dot_gyp) if not home_dot_gyp: home_vars = ['HOME'] if sys.platform in ('cygwin', 'win32'): home_vars.append('USERPROFILE') for home_var in home_vars: home = os.getenv(home_var) if home != None: home_dot_gyp = os.path.join(home, '.gyp') if not os.path.exists(home_dot_gyp): home_dot_gyp = None else: break else: home_dot_gyp = os.path.expanduser(options.config_dir) if home_dot_gyp and not os.path.exists(home_dot_gyp): home_dot_gyp = None if not options.formats: # If no format was given on the command line, then check the env variable. generate_formats = [] if options.use_environment: generate_formats = os.environ.get('GYP_GENERATORS', []) if generate_formats: generate_formats = re.split(r'[\s,]', generate_formats) if generate_formats: options.formats = generate_formats else: # Nothing in the variable, default based on platform. if sys.platform == 'darwin': options.formats = ['xcode'] elif sys.platform in ('win32', 'cygwin'): options.formats = ['msvs'] else: options.formats = ['make'] if not options.generator_output and options.use_environment: g_o = os.environ.get('GYP_GENERATOR_OUTPUT') if g_o: options.generator_output = g_o options.parallel = not options.no_parallel for mode in options.debug: gyp.debug[mode] = 1 # Do an extra check to avoid work when we're not debugging. if DEBUG_GENERAL in gyp.debug: DebugOutput(DEBUG_GENERAL, 'running with these options:') for option, value in sorted(options.__dict__.items()): if option[0] == '_': continue if isinstance(value, basestring): DebugOutput(DEBUG_GENERAL, " %s: '%s'", option, value) else: DebugOutput(DEBUG_GENERAL, " %s: %s", option, value) if not build_files: build_files = FindBuildFiles() if not build_files: raise GypError((usage + '\n\n%s: error: no build_file') % (my_name, my_name)) # TODO(mark): Chromium-specific hack! # For Chromium, the gyp "depth" variable should always be a relative path # to Chromium's top-level "src" directory. If no depth variable was set # on the command line, try to find a "src" directory by looking at the # absolute path to each build file's directory. The first "src" component # found will be treated as though it were the path used for --depth. if not options.depth: for build_file in build_files: build_file_dir = os.path.abspath(os.path.dirname(build_file)) build_file_dir_components = build_file_dir.split(os.path.sep) components_len = len(build_file_dir_components) for index in xrange(components_len - 1, -1, -1): if build_file_dir_components[index] == 'src': options.depth = os.path.sep.join(build_file_dir_components) break del build_file_dir_components[index] # If the inner loop found something, break without advancing to another # build file. if options.depth: break if not options.depth: raise GypError('Could not automatically locate src directory. This is' 'a temporary Chromium feature that will be removed. Use' '--depth as a workaround.') # If toplevel-dir is not set, we assume that depth is the root of our source # tree. if not options.toplevel_dir: options.toplevel_dir = options.depth # -D on the command line sets variable defaults - D isn't just for define, # it's for default. Perhaps there should be a way to force (-F?) a # variable's value so that it can't be overridden by anything else. cmdline_default_variables = {} defines = [] if options.use_environment: defines += ShlexEnv('GYP_DEFINES') if options.defines: defines += options.defines cmdline_default_variables = NameValueListToDict(defines) if DEBUG_GENERAL in gyp.debug: DebugOutput(DEBUG_GENERAL, "cmdline_default_variables: %s", cmdline_default_variables) # Set up includes. includes = [] # If ~/.gyp/include.gypi exists, it'll be forcibly included into every # .gyp file that's loaded, before anything else is included. if home_dot_gyp != None: default_include = os.path.join(home_dot_gyp, 'include.gypi') if os.path.exists(default_include): print 'Using overrides found in ' + default_include includes.append(default_include) # Command-line --include files come after the default include. if options.includes: includes.extend(options.includes) # Generator flags should be prefixed with the target generator since they # are global across all generator runs. gen_flags = [] if options.use_environment: gen_flags += ShlexEnv('GYP_GENERATOR_FLAGS') if options.generator_flags: gen_flags += options.generator_flags generator_flags = NameValueListToDict(gen_flags) if DEBUG_GENERAL in gyp.debug.keys(): DebugOutput(DEBUG_GENERAL, "generator_flags: %s", generator_flags) # Generate all requested formats (use a set in case we got one format request # twice) for format in set(options.formats): params = {'options': options, 'build_files': build_files, 'generator_flags': generator_flags, 'cwd': os.getcwd(), 'build_files_arg': build_files_arg, 'gyp_binary': sys.argv[0], 'home_dot_gyp': home_dot_gyp, 'parallel': options.parallel, 'root_targets': options.root_targets, 'target_arch': cmdline_default_variables.get('target_arch', '')} # Start with the default variables from the command line. [generator, flat_list, targets, data] = Load( build_files, format, cmdline_default_variables, includes, options.depth, params, options.check, options.circular_check, options.duplicate_basename_check) # TODO(mark): Pass |data| for now because the generator needs a list of # build files that came in. In the future, maybe it should just accept # a list, and not the whole data dict. # NOTE: flat_list is the flattened dependency graph specifying the order # that targets may be built. Build systems that operate serially or that # need to have dependencies defined before dependents reference them should # generate targets in the order specified in flat_list. generator.GenerateOutput(flat_list, targets, data, params) if options.configs: valid_configs = targets[flat_list[0]]['configurations'].keys() for conf in options.configs: if conf not in valid_configs: raise GypError('Invalid config specified via --build: %s' % conf) generator.PerformBuild(data, options.configs, params) # Done return 0 def main(args): try: return gyp_main(args) except GypError, e: sys.stderr.write("gyp: %s\n" % e) return 1 # NOTE: setuptools generated console_scripts calls function with no arguments def script_main(): return main(sys.argv[1:]) if __name__ == '__main__': sys.exit(script_main())
mit
NickelMedia/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/common/system/filesystem_mock_unittest.py
122
3391
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import re import unittest2 as unittest from webkitpy.common.system import filesystem_mock from webkitpy.common.system import filesystem_unittest class MockFileSystemTest(unittest.TestCase, filesystem_unittest.GenericFileSystemTests): def setUp(self): self.fs = filesystem_mock.MockFileSystem() self.setup_generic_test_dir() def tearDown(self): self.teardown_generic_test_dir() self.fs = None def quick_check(self, test_fn, good_fn, *tests): for test in tests: if hasattr(test, '__iter__'): expected = good_fn(*test) actual = test_fn(*test) else: expected = good_fn(test) actual = test_fn(test) self.assertEqual(expected, actual, 'given %s, expected %s, got %s' % (repr(test), repr(expected), repr(actual))) def test_join(self): self.quick_check(self.fs.join, self.fs._slow_but_correct_join, ('',), ('', 'bar'), ('foo',), ('foo/',), ('foo', ''), ('foo/', ''), ('foo', 'bar'), ('foo', '/bar'), ) def test_normpath(self): self.quick_check(self.fs.normpath, self.fs._slow_but_correct_normpath, '', '/', '.', '/.', 'foo', 'foo/', 'foo/.', 'foo/bar', '/foo', 'foo/../bar', 'foo/../bar/baz', '../foo')
bsd-3-clause
Vauxoo/docker-odoo-instance
runbot/files/entry_point.py
1
9605
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Entry point for Dockerized aplications, this works mainly with Odoo instances that will be launched using supervisor ''' from os import stat, path, getenv, listdir, remove from subprocess import call from shutil import copy2, rmtree import pwd import fileinput import redis import logging import sys import traceback import psycopg2 import ConfigParser import re logging.basicConfig( level=logging.DEBUG, format='%(levelname)s:[%(asctime)s] - %(name)s.%(module)s - %(message)s') logger = logging.getLogger("entry_point") USER_NAME = getenv('ODOO_USER') and getenv('ODOO_USER') or 'odoo' FILESTORE_PATH = getenv('ODOO_FILESTORE_PATH') \ and getenv('ODOO_FILESTORE_PATH') \ or '/home/%s/.local/share/Odoo/filestore' % USER_NAME CONFIGFILE_PATH = getenv('ODOO_CONFIG_FILE') \ and getenv('ODOO_CONFIG_FILE') \ or '/home/%s/.openerp_serverrc' % USER_NAME def change_values(file_name, getter_func): ''' Changes value from a config file, new values are gotten from redis server or env vars :param str file_name: Config file name :getter_func: Fucnttion that will be used for getting new values ''' for line in fileinput.input(file_name, inplace=True): new_str = line logger.debug("Line readed: %s", line.strip()) parts = line.split("=") logger.debug("Parts: %s", len(parts)) if len(parts) > 1: search_str = parts[0].upper().strip() value = getter_func(search_str) logger.debug("Search for: %s and value is: %s", search_str, value) if value: new_str = "%s = %s" % (parts[0], value) print(new_str.replace('\n', '')) def get_owner(file_name): ''' This function gets owner name from system for a directory or file :param str file_name: File or directory name :returns: Owner name ''' file_stat = stat(file_name) try: owner = pwd.getpwuid(file_stat.st_uid).pw_name except KeyError: owner = "None" logger.debug("Owner of %s is %s", file_name, owner) return owner def get_redis_vars(var_name): ''' This function gets values from a has stored in redis :param str var_name: The key or var name :returns: Value ''' res = None r_server = redis.Redis(getenv('REDIS_SERVER')) if getenv('CLIENT_NAME'): key = '%s_%s' % (getenv('CLIENT_NAME'), getenv('STAGE')) else: key = getenv('STAGE') try: res = r_server.hget(key, var_name) except redis.exceptions.ConnectionError as res_error: logger.exception("Error trying to read from redis server: %s", res_error) exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) return res def delete_build_wo_logs(builds_path): ''' Delete static build files :param str builds_path: The path to static build files ''' if path.exists(builds_path): for build_path in listdir(builds_path): if path.isdir(build_path): for item in listdir(build_path): path_item = path.join(build_path, item) if path.isdir(path_item): if item != 'logs': rmtree(path_item) elif path.isfile(path_item): remove(path_item) def run_sql(sql, db_config): ''' Runs a SQL statement in the specified database The dict db_config is espected to have the following elements: { db_name: Database name db_user: User to use to connect to the database db_pass: Password to use for the connection db_host: Db host name or ip (default to docker ip interface) db_port: Db port number (default to 5432) } :param dict db_config: Database connection parameters :returns: the query result ''' str_conn = 'dbname=%s user=%s host=%s port=%s' % \ (db_config.get('db_name'), db_config.get('db_user'), db_config.get('db_host'), db_config.get('db_port')) logger.debug('Connection sting: %s', str_conn) if db_config.get('db_pass'): str_conn = '%s password=%s' % (str_conn, db_config.get('db_pass')) logger.info('Trying to connect to the PostgreSQL server') try: conn = psycopg2.connect(str_conn) conn.set_isolation_level(0) except Exception as e: logger.exception('Could not connect to the database: %s', e.message) raise cur = conn.cursor() res = None try: logger.debug('Query: %s', sql) cur.execute(sql) except Exception as e: logger.exception('Could not excecute the query: %s', e.message) raise else: if cur.rowcount == -1 or sql.strip().upper().startswith('INSERT') or \ sql.strip().upper().startswith('UPDATE'): res = True else: res = cur.fetchall() finally: cur.close() conn.close() return res def clean_runbotbds(db_config): ''' This method clean an existing runbot database: 1 - Drops builds databases 2 - Update builds state and set them to done 3 - Kill connections older than 10 minutes The dict db_config is espected to have the following elements: { db_name: Database name db_user: User to use to connect to the database db_pass: Password to use for the connection db_host: Db host name or ip (default to docker ip interface) db_port: Db port number (default to 5432) } :param dict db_config: Database connection parameters ''' drop_dbs = "SELECT datname FROM pg_catalog.pg_database d " + \ "WHERE pg_catalog.pg_get_userbyid(d.datdba) = '%s' AND datname = '%s'" % \ (db_config.get('db_user'), db_config.get('db_name')) try: logger.debug('Check if database exist') run_sql(drop_dbs, db_config) except psycopg2.OperationalError as e: reg = re.compile(r'database "\w+" does not exist') if reg.search(e.message): logger.warning('Database %s does not exists', db_config.get('db_name')) logger.warning('If this is your intention ognore this message, else check configuration') return drop_dbs = "SELECT datname FROM pg_catalog.pg_database d " + \ "WHERE pg_catalog.pg_get_userbyid(d.datdba) = '%s' " % \ db_config.get('db_user') drop_dbs = drop_dbs + \ "AND (datname like '%-base' OR datname like '%-all' " + \ "OR datname like '%-wodemo')" update_state = "UPDATE runbot_build SET state='done'" kill_connections = "select datid, state_change, now()-state_change " + \ "AS ago, pg_terminate_backend(pid) " + \ "FROM pg_stat_activity " + \ "WHERE now()-state_change >= INTERVAL '10 minutes' " + \ "ORDER BY state_change ASC;" logger.info('Drop databases') dbs = run_sql(drop_dbs, db_config) if dbs: for db in dbs: logger.debug('Drop db %s', db[0]) run_sql('DROP DATABASE "%s"' % db[0], db_config) logger.info('Update state') run_sql(update_state, db_config) logger.info('Kill connections') run_sql(kill_connections, db_config) def read_db_config(config_file): ''' Reads the db config from Odoo config file to use it in case in necesary to clean the runbot database :param str config_file: Full name and path to the config file :returns: A dict with the configuration ''' config = ConfigParser.RawConfigParser() config.read(config_file) db_config = {} db_config.update({'db_host': config.get('options', 'db_host')}) db_config.update({'db_port': config.get('options', 'db_port')}) db_config.update({'db_user': config.get('options', 'db_user')}) db_config.update({'db_pass': config.get('options', 'db_password')}) db_config.update({'db_name': config.get('options', 'db_name')}) return db_config def main(): ''' Main entry point function ''' logger.info("Entering entry point main function") if not path.isfile(CONFIGFILE_PATH): copy2("/external_files/odoo_runbot.conf", CONFIGFILE_PATH) if getenv('REDIS_SERVER'): getter_func = get_redis_vars logger.info("Using redis server: %s", getenv('REDIS_SERVER')) else: getter_func = getenv logger.info("Using env vars") change_values(CONFIGFILE_PATH, getter_func) bd_config = read_db_config(CONFIGFILE_PATH) clean_runbotbds(bd_config) delete_build_wo_logs( '/home/%s/instance/extra_addons/odoo-extra/runbot/static/build' % USER_NAME) if not path.isfile(FILESTORE_PATH): call(["mkdir", "-p", FILESTORE_PATH]) nginx_pid = '/home/%s/instance/extra_addons/odoo-extra/runbot/static/nginx/nginx.pid' % USER_NAME logger.debug('Check if %s file exist', nginx_pid) if path.isfile(nginx_pid): logger.info('Removing nginx pid file') remove(nginx_pid) call(["chown", "-R", "%s:%s" % (USER_NAME, USER_NAME), "/home/%s" % USER_NAME]) call(["chmod", "ugo+rwx", "/tmp"]) call(["service", "nginx", "start"]) logger.info("All changes made, now will run supervidord") call(["/usr/bin/supervisord"]) if __name__ == '__main__': main()
gpl-2.0
calebfoss/tensorflow
tensorflow/contrib/framework/python/framework/checkpoint_utils.py
22
11550
# 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. # ============================================================================== """Tools to work with checkpoints.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from tensorflow.python.ops import io_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.python.ops import variables from tensorflow.python.platform import gfile from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import saver from tensorflow.python.training import training as train __all__ = [ "load_checkpoint", "load_variable", "list_variables", "init_from_checkpoint"] def _get_checkpoint_filename(filepattern): """Returns checkpoint filename given directory or specific filepattern.""" if gfile.IsDirectory(filepattern): return saver.latest_checkpoint(filepattern) return filepattern def load_checkpoint(filepattern): """Returns CheckpointReader for latest checkpoint. Args: filepattern: Directory with checkpoints file or path to checkpoint. Returns: `CheckpointReader` object. Raises: ValueError: if checkpoint_dir doesn't have 'checkpoint' file or checkpoints. """ filename = _get_checkpoint_filename(filepattern) if filename is None: raise ValueError("Couldn't find 'checkpoint' file or checkpoints in " "given directory %s" % filepattern) return train.NewCheckpointReader(filename) def load_variable(checkpoint_dir, name): """Returns a Tensor with the contents of the given variable in the checkpoint. Args: checkpoint_dir: Directory with checkpoints file or path to checkpoint. name: Name of the tensor to return. Returns: `Tensor` object. """ # TODO(b/29227106): Fix this in the right place and remove this. if name.endswith(":0"): name = name[:-2] reader = load_checkpoint(checkpoint_dir) return reader.get_tensor(name) def list_variables(checkpoint_dir): """Returns list of all variables in the latest checkpoint. Args: checkpoint_dir: Directory with checkpoints file or path to checkpoint. Returns: List of tuples `(name, shape)`. """ reader = load_checkpoint(checkpoint_dir) variable_map = reader.get_variable_to_shape_map() names = sorted(variable_map.keys()) result = [] for name in names: result.append((name, variable_map[name])) return result # pylint: disable=protected-access # Currently variable_scope doesn't provide very good APIs to access # all variables under scope and retrieve and check existing scopes. # TODO(ipolosukhin): Refactor variable_scope module to provide nicer APIs. def _set_checkpoint_initializer(variable, file_pattern, tensor_name, slice_spec, name="checkpoint_initializer"): """Sets variable initializer to assign op form value in checkpoint's tensor. Args: variable: `Variable` object. file_pattern: string, where to load checkpoints from. tensor_name: Name of the `Tensor` to load from checkpoint reader. slice_spec: Slice specification for loading partitioned variables. name: Name of the operation. """ base_type = variable.dtype.base_dtype restore_op = io_ops.restore_v2( file_pattern, [tensor_name], [slice_spec], [base_type], name=name)[0] variable._initializer_op = state_ops.assign(variable, restore_op) def _set_variable_or_list_initializer(variable_or_list, file_pattern, tensor_name): if isinstance(variable_or_list, (list, tuple)): # A set of slices. slice_name = None for v in variable_or_list: if slice_name is None: slice_name = v._save_slice_info.full_name elif slice_name != v._save_slice_info.full_name: raise ValueError("Slices must all be from the same tensor: %s != %s" % (slice_name, v._save_slice_info.full_name)) _set_checkpoint_initializer(v, file_pattern, tensor_name, v._save_slice_info.spec) else: _set_checkpoint_initializer(variable_or_list, file_pattern, tensor_name, "") def _collect_partitioned_variable(name, var_scope): if name + "/part_0" in var_scope._vars: var = [] i = 0 while name + "/part_%d" % i in var_scope._vars: var.append(var_scope._vars[name + "/part_%d" % i]) i += 1 return var return None def init_from_checkpoint(checkpoint_dir, assignment_map): """Using assingment map initializes current variables with loaded tensors. Note: This overrides default initialization ops of specified variables and redefines dtype. Assignment map supports following syntax: `'checkpoint_scope_name/': 'scope_name/'` - will load all variables in current `scope_name` from `checkpoint_scope_name` with matching variable names. `'checkpoint_scope_name/some_other_variable': 'scope_name/variable_name'` - will initalize `scope_name/variable_name` variable from `checkpoint_scope_name/some_other_variable`. `'scope_variable_name': variable` - will initialize given `tf.Variable` object with variable from the checkpoint. `'scope_variable_name': list(variable)` - will initialize list of partitioned variables with variable from the checkpoint. `'/': 'scope_name/'` - will load all variables in current `scope_name` from checkpoint's root (e.g. no scope). Supports loading into partitioned variables, which are represented as '<variable>/part_<part #>'. Example: ```python # Create variables. with tf.variable_scope('test'): m = tf.get_variable('my_var') with tf.variable_scope('test2'): var2 = tf.get_variable('my_var') var3 = tf.get_variable(name="my1", shape=[100, 100], partitioner=lambda shape, dtype: [5, 1]) ... # Specify which variables to intialize from checkpoint. init_from_checkpoint(checkpoint_dir, { 'some_var': 'test/my_var', 'some_scope/': 'test2/'}) ... # Or use `Variable` objects to identify what to initialize. init_from_checkpoint(checkpoint_dir, { 'some_scope/var2': var2, }) # Initialize partitioned variables init_from_checkpoint(checkpoint_dir, { 'some_var_from_ckpt': 'part_var', }) # Or specifying the list of `Variable` objects. init_from_checkpoint(checkpoint_dir, { 'some_var_from_ckpt': var3._get_variable_list(), }) ... # Initialize variables as usual. session.run(tf.get_all_variables()) ``` Args: checkpoint_dir: Directory with checkpoints file or path to checkpoint. assignment_map: Dict, where keys are names of the variables in the checkpoint and values are current variables or names of current variables (in default graph). Raises: tf.errors.OpError: If missing checkpoints or tensors in checkpoints. ValueError: If missing variables in current graph. """ filepattern = _get_checkpoint_filename(checkpoint_dir) reader = load_checkpoint(checkpoint_dir) variable_map = reader.get_variable_to_shape_map() for tensor_name_in_ckpt, current_var_or_name in six.iteritems(assignment_map): var = None # Check if this is Variable object or list of Variable objects (in case of # partitioned variables). is_var = lambda x: isinstance(x, variables.Variable) if is_var(current_var_or_name) or ( isinstance(current_var_or_name, list) and all(is_var(v) for v in current_var_or_name)): var = current_var_or_name else: var_scope = vs._get_default_variable_store() # Check if this variable is in var_store. var = var_scope._vars.get(current_var_or_name, None) # Also check if variable is partitioned as list. if var is None: var = _collect_partitioned_variable(current_var_or_name, var_scope) if var is not None: # If 1 to 1 mapping was provided, find variable in the checkpoint. if tensor_name_in_ckpt not in variable_map: raise ValueError("Tensor %s is not found in %s checkpoint %s" % ( tensor_name_in_ckpt, checkpoint_dir, variable_map )) if is_var(var): # Additional at-call-time checks. if not var.get_shape().is_compatible_with( variable_map[tensor_name_in_ckpt]): raise ValueError( "Shape of variable %s (%s) doesn't match with shape of " "tensor %s (%s) from checkpoint reader." % ( var.name, str(var.get_shape()), tensor_name_in_ckpt, str(variable_map[tensor_name_in_ckpt]) )) var_name = var.name else: var_name = ",".join([v.name for v in var]) _set_variable_or_list_initializer(var, filepattern, tensor_name_in_ckpt) logging.info("Initialize variable %s from checkpoint %s with %s" % ( var_name, checkpoint_dir, tensor_name_in_ckpt )) else: scopes = "" # TODO(vihanjain): Support list of 'current_var_or_name' here. if "/" in current_var_or_name: scopes = current_var_or_name[:current_var_or_name.rindex("/")] if not tensor_name_in_ckpt.endswith("/"): raise ValueError( "Assignment map with scope only name {} should map to scope only " "{}. Should be 'scope/': 'other_scope/'.".format( scopes, tensor_name_in_ckpt)) # If scope to scope mapping was provided, find all variables in the scope # and create variable to variable mapping. scope_variables = set() for var_name in var_scope._vars: if var_name.startswith(scopes): # Consume /part_ if partitioned variable. if "/part_" in var_name: var_name = var_name[:var_name.index("/part_")] scope_variables.add(var_name) for var_name in scope_variables: # Lookup name with specified prefix and suffix from current variable. # If tensor_name given is '/' (root), don't use it for full name. if tensor_name_in_ckpt != "/": full_tensor_name = tensor_name_in_ckpt + var_name[len(scopes) + 1:] else: full_tensor_name = var_name[len(scopes) + 1:] if full_tensor_name not in variable_map: raise ValueError( "Tensor %s (%s in %s) is not found in %s checkpoint" % ( full_tensor_name, var_name[len(scopes) + 1:], tensor_name_in_ckpt, checkpoint_dir )) var = var_scope._vars.get(var_name, None) if var is None: var = _collect_partitioned_variable(var_name, var_scope) _set_variable_or_list_initializer(var, filepattern, full_tensor_name) logging.info("Initialize variable %s from checkpoint %s with %s" % ( var_name, checkpoint_dir, full_tensor_name )) # pylint: enable=protected-access
apache-2.0
qt911025/qt-homemade-mod-osp
Source/header_sounds.py
6
1335
################################################### # header_sounds.py # This file contains declarations for sounds # DO NOT EDIT THIS FILE! ################################################### sf_2d = 0x00000001 sf_looping = 0x00000002 sf_start_at_random_pos = 0x00000004 sf_stream_from_hd = 0x00000008 sf_always_send_via_network = 0x00100000 sf_priority_15 = 0x000000f0 sf_priority_14 = 0x000000e0 sf_priority_13 = 0x000000d0 sf_priority_12 = 0x000000c0 sf_priority_11 = 0x000000b0 sf_priority_10 = 0x000000a0 sf_priority_9 = 0x00000090 sf_priority_8 = 0x00000080 sf_priority_7 = 0x00000070 sf_priority_6 = 0x00000060 sf_priority_5 = 0x00000050 sf_priority_4 = 0x00000040 sf_priority_3 = 0x00000030 sf_priority_2 = 0x00000020 sf_priority_1 = 0x00000010 sf_vol_15 = 0x00000f00 sf_vol_14 = 0x00000e00 sf_vol_13 = 0x00000d00 sf_vol_12 = 0x00000c00 sf_vol_11 = 0x00000b00 sf_vol_10 = 0x00000a00 sf_vol_9 = 0x00000900 sf_vol_8 = 0x00000800 sf_vol_7 = 0x00000700 sf_vol_6 = 0x00000600 sf_vol_5 = 0x00000500 sf_vol_4 = 0x00000400 sf_vol_3 = 0x00000300 sf_vol_2 = 0x00000200 sf_vol_1 = 0x00000100
mit
phenoxim/nova
nova/api/openstack/compute/schemas/server_tags.py
12
1071
# 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 nova.api.validation import parameter_types from nova.objects import instance update_all = { "title": "Server tags", "type": "object", "properties": { "tags": { "type": "array", "items": parameter_types.tag, "maxItems": instance.MAX_TAG_COUNT } }, 'required': ['tags'], 'additionalProperties': False } update = { "title": "Server tag", "type": "null", 'required': [], 'additionalProperties': False }
apache-2.0
atlefren/beercalc
app/views.py
1
2230
from flask import (render_template, g, abort) from flask.ext.login import current_user, login_required from app import app from models import Brew, Malt, Hop, Yeast, Style import simplejson ''' @lm.user_loader def load_user(id): return User.query.get(int(id)) ''' @app.before_request def before_request(): g.user = current_user @app.route('/') def index(): return render_template('index.html') @app.route('/ingredients/malt/') def malt_view(): malts = simplejson.dumps( [malt.serialize for malt in Malt.query.order_by(Malt.name)] ) return render_template('malt_list.html', malts=malts) @app.route('/ingredients/hops/') def hops(): hops = simplejson.dumps( [malt.serialize for malt in Hop.query.order_by(Hop.name)] ) return render_template('hop_list.html', hops=hops) @app.route('/ingredients/yeast/') def yeast(): yeasts = simplejson.dumps( [malt.serialize for malt in Yeast.query.order_by(Yeast.name)] ) return render_template('yeast_list.html', yeasts=yeasts) def serialize_styles(): styles = Style.query.all() return simplejson.dumps([style.serialize for style in styles]) @app.route('/brews/my/') @login_required def my_brews(): brews = Brew.query.filter_by(user=g.user).order_by(Brew.name).all() return render_template('brew_list.html', brews=brews, title='My brews') @app.route('/brews/add/') @login_required def add_brew(): return render_template( 'brewsheet.html', brew=None, is_own=True, styles=serialize_styles() ) @app.route('/brews/<int:brew_id>/') def show_brew(brew_id): brew = Brew.query.get(brew_id) is_own = (g.user.is_authenticated() and brew.user_id == g.user.id) if brew.public or is_own: return render_template( 'brewsheet.html', brew=simplejson.dumps(brew.serialize), styles=serialize_styles(), is_own=is_own ) abort(404) @app.route('/brews/browse/') def browse_brews(): brews = Brew.query.filter_by(public=True).order_by(Brew.name).all() return render_template( 'brew_list.html', brews=brews, title='Browse brews', show_brewer=True )
mit
xq262144/hue
desktop/core/ext-py/MySQL-python-1.2.5/tests/test_MySQLdb_nonstandard.py
41
2737
import unittest import _mysql import MySQLdb from MySQLdb.constants import FIELD_TYPE from configdb import connection_factory import warnings warnings.simplefilter("ignore") class TestDBAPISet(unittest.TestCase): def test_set_equality(self): self.assertTrue(MySQLdb.STRING == MySQLdb.STRING) def test_set_inequality(self): self.assertTrue(MySQLdb.STRING != MySQLdb.NUMBER) def test_set_equality_membership(self): self.assertTrue(FIELD_TYPE.VAR_STRING == MySQLdb.STRING) def test_set_inequality_membership(self): self.assertTrue(FIELD_TYPE.DATE != MySQLdb.STRING) class CoreModule(unittest.TestCase): """Core _mysql module features.""" def test_NULL(self): """Should have a NULL constant.""" self.assertEqual(_mysql.NULL, 'NULL') def test_version(self): """Version information sanity.""" self.assertTrue(isinstance(_mysql.__version__, str)) self.assertTrue(isinstance(_mysql.version_info, tuple)) self.assertEqual(len(_mysql.version_info), 5) def test_client_info(self): self.assertTrue(isinstance(_mysql.get_client_info(), str)) def test_thread_safe(self): self.assertTrue(isinstance(_mysql.thread_safe(), int)) class CoreAPI(unittest.TestCase): """Test _mysql interaction internals.""" def setUp(self): self.conn = connection_factory(use_unicode=True) def tearDown(self): self.conn.close() def test_thread_id(self): tid = self.conn.thread_id() self.assertTrue(isinstance(tid, int), "thread_id didn't return an int.") self.assertRaises(TypeError, self.conn.thread_id, ('evil',), "thread_id shouldn't accept arguments.") def test_affected_rows(self): self.assertEquals(self.conn.affected_rows(), 0, "Should return 0 before we do anything.") #def test_debug(self): ## FIXME Only actually tests if you lack SUPER #self.assertRaises(MySQLdb.OperationalError, #self.conn.dump_debug_info) def test_charset_name(self): self.assertTrue(isinstance(self.conn.character_set_name(), str), "Should return a string.") def test_host_info(self): self.assertTrue(isinstance(self.conn.get_host_info(), str), "Should return a string.") def test_proto_info(self): self.assertTrue(isinstance(self.conn.get_proto_info(), int), "Should return an int.") def test_server_info(self): self.assertTrue(isinstance(self.conn.get_server_info(), str), "Should return an str.")
apache-2.0
karan1276/servo
tests/wpt/css-tests/tools/pytest/testing/test_terminal.py
169
28844
""" terminal reporting of the full testing process. """ import collections import sys import _pytest._pluggy as pluggy import _pytest._code import py import pytest from _pytest import runner from _pytest.main import EXIT_NOTESTSCOLLECTED from _pytest.terminal import TerminalReporter, repr_pythonversion, getreportopt from _pytest.terminal import build_summary_stats_line, _plugin_nameversions def basic_run_report(item): runner.call_and_report(item, "setup", log=False) return runner.call_and_report(item, "call", log=False) DistInfo = collections.namedtuple('DistInfo', ['project_name', 'version']) class Option: def __init__(self, verbose=False, fulltrace=False): self.verbose = verbose self.fulltrace = fulltrace @property def args(self): l = [] if self.verbose: l.append('-v') if self.fulltrace: l.append('--fulltrace') return l def pytest_generate_tests(metafunc): if "option" in metafunc.fixturenames: metafunc.addcall(id="default", funcargs={'option': Option(verbose=False)}) metafunc.addcall(id="verbose", funcargs={'option': Option(verbose=True)}) metafunc.addcall(id="quiet", funcargs={'option': Option(verbose= -1)}) metafunc.addcall(id="fulltrace", funcargs={'option': Option(fulltrace=True)}) @pytest.mark.parametrize('input,expected', [ ([DistInfo(project_name='test', version=1)], ['test-1']), ([DistInfo(project_name='pytest-test', version=1)], ['test-1']), ([ DistInfo(project_name='test', version=1), DistInfo(project_name='test', version=1) ], ['test-1']), ], ids=['normal', 'prefix-strip', 'deduplicate']) def test_plugin_nameversion(input, expected): pluginlist = [(None, x) for x in input] result = _plugin_nameversions(pluginlist) assert result == expected class TestTerminal: def test_pass_skip_fail(self, testdir, option): testdir.makepyfile(""" import pytest def test_ok(): pass def test_skip(): pytest.skip("xx") def test_func(): assert 0 """) result = testdir.runpytest(*option.args) if option.verbose: result.stdout.fnmatch_lines([ "*test_pass_skip_fail.py::test_ok PASS*", "*test_pass_skip_fail.py::test_skip SKIP*", "*test_pass_skip_fail.py::test_func FAIL*", ]) else: result.stdout.fnmatch_lines([ "*test_pass_skip_fail.py .sF" ]) result.stdout.fnmatch_lines([ " def test_func():", "> assert 0", "E assert 0", ]) def test_internalerror(self, testdir, linecomp): modcol = testdir.getmodulecol("def test_one(): pass") rep = TerminalReporter(modcol.config, file=linecomp.stringio) excinfo = pytest.raises(ValueError, "raise ValueError('hello')") rep.pytest_internalerror(excinfo.getrepr()) linecomp.assert_contains_lines([ "INTERNALERROR> *ValueError*hello*" ]) def test_writeline(self, testdir, linecomp): modcol = testdir.getmodulecol("def test_one(): pass") rep = TerminalReporter(modcol.config, file=linecomp.stringio) rep.write_fspath_result(modcol.nodeid, ".") rep.write_line("hello world") lines = linecomp.stringio.getvalue().split('\n') assert not lines[0] assert lines[1].endswith(modcol.name + " .") assert lines[2] == "hello world" def test_show_runtest_logstart(self, testdir, linecomp): item = testdir.getitem("def test_func(): pass") tr = TerminalReporter(item.config, file=linecomp.stringio) item.config.pluginmanager.register(tr) location = item.reportinfo() tr.config.hook.pytest_runtest_logstart(nodeid=item.nodeid, location=location, fspath=str(item.fspath)) linecomp.assert_contains_lines([ "*test_show_runtest_logstart.py*" ]) def test_runtest_location_shown_before_test_starts(self, testdir): testdir.makepyfile(""" def test_1(): import time time.sleep(20) """) child = testdir.spawn_pytest("") child.expect(".*test_runtest_location.*py") child.sendeof() child.kill(15) def test_itemreport_subclasses_show_subclassed_file(self, testdir): testdir.makepyfile(test_p1=""" class BaseTests: def test_p1(self): pass class TestClass(BaseTests): pass """) p2 = testdir.makepyfile(test_p2=""" from test_p1 import BaseTests class TestMore(BaseTests): pass """) result = testdir.runpytest(p2) result.stdout.fnmatch_lines([ "*test_p2.py .", "*1 passed*", ]) result = testdir.runpytest("-v", p2) result.stdout.fnmatch_lines([ "*test_p2.py::TestMore::test_p1* <- *test_p1.py*PASSED", ]) def test_itemreport_directclasses_not_shown_as_subclasses(self, testdir): a = testdir.mkpydir("a123") a.join("test_hello123.py").write(_pytest._code.Source(""" class TestClass: def test_method(self): pass """)) result = testdir.runpytest("-v") assert result.ret == 0 result.stdout.fnmatch_lines([ "*a123/test_hello123.py*PASS*", ]) assert " <- " not in result.stdout.str() def test_keyboard_interrupt(self, testdir, option): testdir.makepyfile(""" def test_foobar(): assert 0 def test_spamegg(): import py; pytest.skip('skip me please!') def test_interrupt_me(): raise KeyboardInterrupt # simulating the user """) result = testdir.runpytest(*option.args, no_reraise_ctrlc=True) result.stdout.fnmatch_lines([ " def test_foobar():", "> assert 0", "E assert 0", "*_keyboard_interrupt.py:6: KeyboardInterrupt*", ]) if option.fulltrace: result.stdout.fnmatch_lines([ "*raise KeyboardInterrupt # simulating the user*", ]) else: result.stdout.fnmatch_lines([ "to show a full traceback on KeyboardInterrupt use --fulltrace" ]) result.stdout.fnmatch_lines(['*KeyboardInterrupt*']) def test_keyboard_in_sessionstart(self, testdir): testdir.makeconftest(""" def pytest_sessionstart(): raise KeyboardInterrupt """) testdir.makepyfile(""" def test_foobar(): pass """) result = testdir.runpytest(no_reraise_ctrlc=True) assert result.ret == 2 result.stdout.fnmatch_lines(['*KeyboardInterrupt*']) class TestCollectonly: def test_collectonly_basic(self, testdir): testdir.makepyfile(""" def test_func(): pass """) result = testdir.runpytest("--collect-only",) result.stdout.fnmatch_lines([ "<Module 'test_collectonly_basic.py'>", " <Function 'test_func'>", ]) def test_collectonly_skipped_module(self, testdir): testdir.makepyfile(""" import pytest pytest.skip("hello") """) result = testdir.runpytest("--collect-only", "-rs") result.stdout.fnmatch_lines([ "SKIP*hello*", "*1 skip*", ]) def test_collectonly_failed_module(self, testdir): testdir.makepyfile("""raise ValueError(0)""") result = testdir.runpytest("--collect-only") result.stdout.fnmatch_lines([ "*raise ValueError*", "*1 error*", ]) def test_collectonly_fatal(self, testdir): testdir.makeconftest(""" def pytest_collectstart(collector): assert 0, "urgs" """) result = testdir.runpytest("--collect-only") result.stdout.fnmatch_lines([ "*INTERNAL*args*" ]) assert result.ret == 3 def test_collectonly_simple(self, testdir): p = testdir.makepyfile(""" def test_func1(): pass class TestClass: def test_method(self): pass """) result = testdir.runpytest("--collect-only", p) #assert stderr.startswith("inserting into sys.path") assert result.ret == 0 result.stdout.fnmatch_lines([ "*<Module '*.py'>", "* <Function 'test_func1'*>", "* <Class 'TestClass'>", #"* <Instance '()'>", "* <Function 'test_method'*>", ]) def test_collectonly_error(self, testdir): p = testdir.makepyfile("import Errlkjqweqwe") result = testdir.runpytest("--collect-only", p) assert result.ret == 1 result.stdout.fnmatch_lines(_pytest._code.Source(""" *ERROR* *import Errlk* *ImportError* *1 error* """).strip()) def test_collectonly_missing_path(self, testdir): """this checks issue 115, failure in parseargs will cause session not to have the items attribute """ result = testdir.runpytest("--collect-only", "uhm_missing_path") assert result.ret == 4 result.stderr.fnmatch_lines([ '*ERROR: file not found*', ]) def test_collectonly_quiet(self, testdir): testdir.makepyfile("def test_foo(): pass") result = testdir.runpytest("--collect-only", "-q") result.stdout.fnmatch_lines([ '*test_foo*', ]) def test_collectonly_more_quiet(self, testdir): testdir.makepyfile(test_fun="def test_foo(): pass") result = testdir.runpytest("--collect-only", "-qq") result.stdout.fnmatch_lines([ '*test_fun.py: 1*', ]) def test_repr_python_version(monkeypatch): try: monkeypatch.setattr(sys, 'version_info', (2, 5, 1, 'final', 0)) assert repr_pythonversion() == "2.5.1-final-0" py.std.sys.version_info = x = (2, 3) assert repr_pythonversion() == str(x) finally: monkeypatch.undo() # do this early as pytest can get confused class TestFixtureReporting: def test_setup_fixture_error(self, testdir): testdir.makepyfile(""" def setup_function(function): print ("setup func") assert 0 def test_nada(): pass """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*ERROR at setup of test_nada*", "*setup_function(function):*", "*setup func*", "*assert 0*", "*1 error*", ]) assert result.ret != 0 def test_teardown_fixture_error(self, testdir): testdir.makepyfile(""" def test_nada(): pass def teardown_function(function): print ("teardown func") assert 0 """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*ERROR at teardown*", "*teardown_function(function):*", "*assert 0*", "*Captured stdout*", "*teardown func*", "*1 passed*1 error*", ]) def test_teardown_fixture_error_and_test_failure(self, testdir): testdir.makepyfile(""" def test_fail(): assert 0, "failingfunc" def teardown_function(function): print ("teardown func") assert False """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*ERROR at teardown of test_fail*", "*teardown_function(function):*", "*assert False*", "*Captured stdout*", "*teardown func*", "*test_fail*", "*def test_fail():", "*failingfunc*", "*1 failed*1 error*", ]) class TestTerminalFunctional: def test_deselected(self, testdir): testpath = testdir.makepyfile(""" def test_one(): pass def test_two(): pass def test_three(): pass """ ) result = testdir.runpytest("-k", "test_two:", testpath) result.stdout.fnmatch_lines([ "*test_deselected.py ..", "=* 1 test*deselected by*test_two:*=", ]) assert result.ret == 0 def test_no_skip_summary_if_failure(self, testdir): testdir.makepyfile(""" import pytest def test_ok(): pass def test_fail(): assert 0 def test_skip(): pytest.skip("dontshow") """) result = testdir.runpytest() assert result.stdout.str().find("skip test summary") == -1 assert result.ret == 1 def test_passes(self, testdir): p1 = testdir.makepyfile(""" def test_passes(): pass class TestClass: def test_method(self): pass """) old = p1.dirpath().chdir() try: result = testdir.runpytest() finally: old.chdir() result.stdout.fnmatch_lines([ "test_passes.py ..", "* 2 pass*", ]) assert result.ret == 0 def test_header_trailer_info(self, testdir): testdir.makepyfile(""" def test_passes(): pass """) result = testdir.runpytest() verinfo = ".".join(map(str, py.std.sys.version_info[:3])) result.stdout.fnmatch_lines([ "*===== test session starts ====*", "platform %s -- Python %s*pytest-%s*py-%s*pluggy-%s" % ( py.std.sys.platform, verinfo, pytest.__version__, py.__version__, pluggy.__version__), "*test_header_trailer_info.py .", "=* 1 passed*in *.[0-9][0-9] seconds *=", ]) if pytest.config.pluginmanager.list_plugin_distinfo(): result.stdout.fnmatch_lines([ "plugins: *", ]) def test_showlocals(self, testdir): p1 = testdir.makepyfile(""" def test_showlocals(): x = 3 y = "x" * 5000 assert 0 """) result = testdir.runpytest(p1, '-l') result.stdout.fnmatch_lines([ #"_ _ * Locals *", "x* = 3", "y* = 'xxxxxx*" ]) def test_verbose_reporting(self, testdir, pytestconfig): p1 = testdir.makepyfile(""" import pytest def test_fail(): raise ValueError() def test_pass(): pass class TestClass: def test_skip(self): pytest.skip("hello") def test_gen(): def check(x): assert x == 1 yield check, 0 """) result = testdir.runpytest(p1, '-v') result.stdout.fnmatch_lines([ "*test_verbose_reporting.py::test_fail *FAIL*", "*test_verbose_reporting.py::test_pass *PASS*", "*test_verbose_reporting.py::TestClass::test_skip *SKIP*", "*test_verbose_reporting.py::test_gen*0* *FAIL*", ]) assert result.ret == 1 if not pytestconfig.pluginmanager.get_plugin("xdist"): pytest.skip("xdist plugin not installed") result = testdir.runpytest(p1, '-v', '-n 1') result.stdout.fnmatch_lines([ "*FAIL*test_verbose_reporting.py::test_fail*", ]) assert result.ret == 1 def test_quiet_reporting(self, testdir): p1 = testdir.makepyfile("def test_pass(): pass") result = testdir.runpytest(p1, '-q') s = result.stdout.str() assert 'test session starts' not in s assert p1.basename not in s assert "===" not in s assert "passed" in s def test_more_quiet_reporting(self, testdir): p1 = testdir.makepyfile("def test_pass(): pass") result = testdir.runpytest(p1, '-qq') s = result.stdout.str() assert 'test session starts' not in s assert p1.basename not in s assert "===" not in s assert "passed" not in s def test_fail_extra_reporting(testdir): testdir.makepyfile("def test_this(): assert 0") result = testdir.runpytest() assert 'short test summary' not in result.stdout.str() result = testdir.runpytest('-rf') result.stdout.fnmatch_lines([ "*test summary*", "FAIL*test_fail_extra_reporting*", ]) def test_fail_reporting_on_pass(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest('-rf') assert 'short test summary' not in result.stdout.str() def test_pass_extra_reporting(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest() assert 'short test summary' not in result.stdout.str() result = testdir.runpytest('-rp') result.stdout.fnmatch_lines([ "*test summary*", "PASS*test_pass_extra_reporting*", ]) def test_pass_reporting_on_fail(testdir): testdir.makepyfile("def test_this(): assert 0") result = testdir.runpytest('-rp') assert 'short test summary' not in result.stdout.str() def test_pass_output_reporting(testdir): testdir.makepyfile(""" def test_pass_output(): print("Four score and seven years ago...") """) result = testdir.runpytest() assert 'Four score and seven years ago...' not in result.stdout.str() result = testdir.runpytest('-rP') result.stdout.fnmatch_lines([ "Four score and seven years ago...", ]) def test_color_yes(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest('--color=yes') assert 'test session starts' in result.stdout.str() assert '\x1b[1m' in result.stdout.str() def test_color_no(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest('--color=no') assert 'test session starts' in result.stdout.str() assert '\x1b[1m' not in result.stdout.str() @pytest.mark.parametrize('verbose', [True, False]) def test_color_yes_collection_on_non_atty(testdir, verbose): """skip collect progress report when working on non-terminals. #1397 """ testdir.makepyfile(""" import pytest @pytest.mark.parametrize('i', range(10)) def test_this(i): assert 1 """) args = ['--color=yes'] if verbose: args.append('-vv') result = testdir.runpytest(*args) assert 'test session starts' in result.stdout.str() assert '\x1b[1m' in result.stdout.str() assert 'collecting 10 items' not in result.stdout.str() if verbose: assert 'collecting ...' in result.stdout.str() assert 'collected 10 items' in result.stdout.str() def test_getreportopt(): class config: class option: reportchars = "" config.option.report = "xfailed" assert getreportopt(config) == "x" config.option.report = "xfailed,skipped" assert getreportopt(config) == "xs" config.option.report = "skipped,xfailed" assert getreportopt(config) == "sx" config.option.report = "skipped" config.option.reportchars = "sf" assert getreportopt(config) == "sf" config.option.reportchars = "sfx" assert getreportopt(config) == "sfx" def test_terminalreporter_reportopt_addopts(testdir): testdir.makeini("[pytest]\naddopts=-rs") testdir.makepyfile(""" def pytest_funcarg__tr(request): tr = request.config.pluginmanager.getplugin("terminalreporter") return tr def test_opt(tr): assert tr.hasopt('skipped') assert not tr.hasopt('qwe') """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*1 passed*" ]) def test_tbstyle_short(testdir): p = testdir.makepyfile(""" def pytest_funcarg__arg(request): return 42 def test_opt(arg): x = 0 assert x """) result = testdir.runpytest("--tb=short") s = result.stdout.str() assert 'arg = 42' not in s assert 'x = 0' not in s result.stdout.fnmatch_lines([ "*%s:5*" % p.basename, " assert x", "E assert*", ]) result = testdir.runpytest() s = result.stdout.str() assert 'x = 0' in s assert 'assert x' in s def test_traceconfig(testdir, monkeypatch): result = testdir.runpytest("--traceconfig") result.stdout.fnmatch_lines([ "*active plugins*" ]) assert result.ret == EXIT_NOTESTSCOLLECTED class TestGenericReporting: """ this test class can be subclassed with a different option provider to run e.g. distributed tests. """ def test_collect_fail(self, testdir, option): testdir.makepyfile("import xyz\n") result = testdir.runpytest(*option.args) result.stdout.fnmatch_lines([ "? import xyz", "E ImportError: No module named *xyz*", "*1 error*", ]) def test_maxfailures(self, testdir, option): testdir.makepyfile(""" def test_1(): assert 0 def test_2(): assert 0 def test_3(): assert 0 """) result = testdir.runpytest("--maxfail=2", *option.args) result.stdout.fnmatch_lines([ "*def test_1():*", "*def test_2():*", "*!! Interrupted: stopping after 2 failures*!!*", "*2 failed*", ]) def test_tb_option(self, testdir, option): testdir.makepyfile(""" import pytest def g(): raise IndexError def test_func(): print (6*7) g() # --calling-- """) for tbopt in ["long", "short", "no"]: print('testing --tb=%s...' % tbopt) result = testdir.runpytest('--tb=%s' % tbopt) s = result.stdout.str() if tbopt == "long": assert 'print (6*7)' in s else: assert 'print (6*7)' not in s if tbopt != "no": assert '--calling--' in s assert 'IndexError' in s else: assert 'FAILURES' not in s assert '--calling--' not in s assert 'IndexError' not in s def test_tb_crashline(self, testdir, option): p = testdir.makepyfile(""" import pytest def g(): raise IndexError def test_func1(): print (6*7) g() # --calling-- def test_func2(): assert 0, "hello" """) result = testdir.runpytest("--tb=line") bn = p.basename result.stdout.fnmatch_lines([ "*%s:3: IndexError*" % bn, "*%s:8: AssertionError: hello*" % bn, ]) s = result.stdout.str() assert "def test_func2" not in s def test_pytest_report_header(self, testdir, option): testdir.makeconftest(""" def pytest_sessionstart(session): session.config._somevalue = 42 def pytest_report_header(config): return "hello: %s" % config._somevalue """) testdir.mkdir("a").join("conftest.py").write(""" def pytest_report_header(config, startdir): return ["line1", str(startdir)] """) result = testdir.runpytest("a") result.stdout.fnmatch_lines([ "*hello: 42*", "line1", str(testdir.tmpdir), ]) @pytest.mark.xfail("not hasattr(os, 'dup')") def test_fdopen_kept_alive_issue124(testdir): testdir.makepyfile(""" import os, sys k = [] def test_open_file_and_keep_alive(capfd): stdout = os.fdopen(1, 'w', 1) k.append(stdout) def test_close_kept_alive_file(): stdout = k.pop() stdout.close() """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*2 passed*" ]) def test_tbstyle_native_setup_error(testdir): testdir.makepyfile(""" import pytest @pytest.fixture def setup_error_fixture(): raise Exception("error in exception") def test_error_fixture(setup_error_fixture): pass """) result = testdir.runpytest("--tb=native") result.stdout.fnmatch_lines([ '*File *test_tbstyle_native_setup_error.py", line *, in setup_error_fixture*' ]) def test_terminal_summary(testdir): testdir.makeconftest(""" def pytest_terminal_summary(terminalreporter): w = terminalreporter w.section("hello") w.line("world") """) result = testdir.runpytest() result.stdout.fnmatch_lines(""" *==== hello ====* world """) def test_terminal_summary_warnings_are_displayed(testdir): """Test that warnings emitted during pytest_terminal_summary are displayed. (#1305). """ testdir.makeconftest(""" def pytest_terminal_summary(terminalreporter): config = terminalreporter.config config.warn('C1', 'internal warning') """) result = testdir.runpytest('-rw') result.stdout.fnmatch_lines([ '*C1*internal warning', '*== 1 pytest-warnings in *', ]) @pytest.mark.parametrize("exp_color, exp_line, stats_arg", [ # The method under test only cares about the length of each # dict value, not the actual contents, so tuples of anything # suffice # Important statuses -- the highest priority of these always wins ("red", "1 failed", {"failed": (1,)}), ("red", "1 failed, 1 passed", {"failed": (1,), "passed": (1,)}), ("red", "1 error", {"error": (1,)}), ("red", "1 passed, 1 error", {"error": (1,), "passed": (1,)}), # (a status that's not known to the code) ("yellow", "1 weird", {"weird": (1,)}), ("yellow", "1 passed, 1 weird", {"weird": (1,), "passed": (1,)}), ("yellow", "1 pytest-warnings", {"warnings": (1,)}), ("yellow", "1 passed, 1 pytest-warnings", {"warnings": (1,), "passed": (1,)}), ("green", "5 passed", {"passed": (1,2,3,4,5)}), # "Boring" statuses. These have no effect on the color of the summary # line. Thus, if *every* test has a boring status, the summary line stays # at its default color, i.e. yellow, to warn the user that the test run # produced no useful information ("yellow", "1 skipped", {"skipped": (1,)}), ("green", "1 passed, 1 skipped", {"skipped": (1,), "passed": (1,)}), ("yellow", "1 deselected", {"deselected": (1,)}), ("green", "1 passed, 1 deselected", {"deselected": (1,), "passed": (1,)}), ("yellow", "1 xfailed", {"xfailed": (1,)}), ("green", "1 passed, 1 xfailed", {"xfailed": (1,), "passed": (1,)}), ("yellow", "1 xpassed", {"xpassed": (1,)}), ("green", "1 passed, 1 xpassed", {"xpassed": (1,), "passed": (1,)}), # Likewise if no tests were found at all ("yellow", "no tests ran", {}), # Test the empty-key special case ("yellow", "no tests ran", {"": (1,)}), ("green", "1 passed", {"": (1,), "passed": (1,)}), # A couple more complex combinations ("red", "1 failed, 2 passed, 3 xfailed", {"passed": (1,2), "failed": (1,), "xfailed": (1,2,3)}), ("green", "1 passed, 2 skipped, 3 deselected, 2 xfailed", {"passed": (1,), "skipped": (1,2), "deselected": (1,2,3), "xfailed": (1,2)}), ]) def test_summary_stats(exp_line, exp_color, stats_arg): print("Based on stats: %s" % stats_arg) print("Expect summary: \"%s\"; with color \"%s\"" % (exp_line, exp_color)) (line, color) = build_summary_stats_line(stats_arg) print("Actually got: \"%s\"; with color \"%s\"" % (line, color)) assert line == exp_line assert color == exp_color
mpl-2.0
kalxas/geonode
geonode/upload/migrations/24_initial.py
6
2181
# -*- coding: utf-8 -*- from django.db import migrations, models from django.utils.timezone import now from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('layers', '__first__'), ] operations = [ migrations.CreateModel( name='Upload', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('import_id', models.BigIntegerField(null=True)), ('state', models.CharField(max_length=16)), ('date', models.DateTimeField(default=now, verbose_name='date')), ('upload_dir', models.CharField(max_length=100, null=True)), ('name', models.CharField(max_length=64, null=True)), ('complete', models.BooleanField(default=False)), ('session', models.TextField(null=True)), ('metadata', models.TextField(null=True)), ('mosaic_time_regex', models.CharField(max_length=128, null=True)), ('mosaic_time_value', models.CharField(max_length=128, null=True)), ('mosaic_elev_regex', models.CharField(max_length=128, null=True)), ('mosaic_elev_value', models.CharField(max_length=128, null=True)), ('layer', models.ForeignKey(to='layers.Layer', on_delete=models.SET_NULL, null=True)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)), ], options={ 'ordering': ['-date'], }, ), migrations.CreateModel( name='UploadFile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('file', models.FileField(upload_to='uploads')), ('slug', models.SlugField(blank=True)), ('upload', models.ForeignKey(blank=True, to='upload.Upload', on_delete=models.SET_NULL, null=True)), ], ), ]
gpl-3.0
libdynd/dynd-python
dynd/nd/test/test_arithmetic.py
5
2110
import unittest from dynd import nd import sys @unittest.skip('Test disabled since translate_exception is not being applied properly') class TestScalarConstructor(unittest.TestCase): def test_arithmetic_exceptions(self): # Check that translate_exception is properly # used to catch exceptions that arise when using # arithmetic operators. a = nd.array([1, 2, 3]) b = nd.array([4, 5]) self.assertRaises(RuntimeError, a.__add__, b) self.assertRaises(RuntimeError, a.__radd__, b) self.assertRaises(RuntimeError, a.__sub__, b) self.assertRaises(RuntimeError, a.__rsub__, b) self.assertRaises(RuntimeError, a.__mul__, b) self.assertRaises(RuntimeError, a.__rmul__, b) if sys.version_info[0] >= 0: self.assertRaises(RuntimeError, a.__truediv__, b) self.assertRaises(RuntimeError, a.__rtruediv__, b) else: self.assertRaises(RuntimeError, a.__div__, b) self.assertRaises(RuntimeError, a.__rdiv__, b) self.assertRaises(RuntimeError, a.__mod__, b) self.assertRaises(RuntimeError, a.__rmod__, b) self.assertRaises(RuntimeError, a.__and__, b) self.assertRaises(RuntimeError, a.__rand__, b) self.assertRaises(RuntimeError, a.__or__, b) self.assertRaises(RuntimeError, a.__ror__, b) self.assertRaises(RuntimeError, a.__xor__, b) self.assertRaises(RuntimeError, a.__rxor__, b) self.assertRaises(RuntimeError, a.__lshift__, b) self.assertRaises(RuntimeError, a.__rlshift__, b) self.assertRaises(RuntimeError, a.__rshift__, b) self.assertRaises(RuntimeError, a.__rrshift__, b) self.assertRaises(RuntimeError, a.__pow__, b) # Check that the optional third argument to pow causes an error # if it is used. It should be implemented eventually, # but should not fail silently. self.assertRaises(ValueError, a.__pow__, a, a) self.assertRaises(RuntimeError, a.__rpow__, b) if __name__ == '__main__': unittest.main(verbosity=2)
bsd-2-clause
abhattad4/Digi-Menu
digimenu2/build/lib.linux-x86_64-2.7/django/db/migrations/writer.py
42
20479
from __future__ import unicode_literals import collections import datetime import decimal import inspect import math import os import re import sys import types from importlib import import_module from django.apps import apps from django.db import migrations, models from django.db.migrations.loader import MigrationLoader from django.db.migrations.operations.base import Operation from django.utils import datetime_safe, six from django.utils._os import upath from django.utils.encoding import force_text from django.utils.functional import Promise from django.utils.timezone import utc from django.utils.version import get_docs_version COMPILED_REGEX_TYPE = type(re.compile('')) class SettingsReference(str): """ Special subclass of string which actually references a current settings value. It's treated as the value in memory, but serializes out to a settings.NAME attribute reference. """ def __new__(self, value, setting_name): return str.__new__(self, value) def __init__(self, value, setting_name): self.setting_name = setting_name class OperationWriter(object): def __init__(self, operation, indentation=2): self.operation = operation self.buff = [] self.indentation = indentation def serialize(self): def _write(_arg_name, _arg_value): if (_arg_name in self.operation.serialization_expand_args and isinstance(_arg_value, (list, tuple, dict))): if isinstance(_arg_value, dict): self.feed('%s={' % _arg_name) self.indent() for key, value in _arg_value.items(): key_string, key_imports = MigrationWriter.serialize(key) arg_string, arg_imports = MigrationWriter.serialize(value) args = arg_string.splitlines() if len(args) > 1: self.feed('%s: %s' % (key_string, args[0])) for arg in args[1:-1]: self.feed(arg) self.feed('%s,' % args[-1]) else: self.feed('%s: %s,' % (key_string, arg_string)) imports.update(key_imports) imports.update(arg_imports) self.unindent() self.feed('},') else: self.feed('%s=[' % _arg_name) self.indent() for item in _arg_value: arg_string, arg_imports = MigrationWriter.serialize(item) args = arg_string.splitlines() if len(args) > 1: for arg in args[:-1]: self.feed(arg) self.feed('%s,' % args[-1]) else: self.feed('%s,' % arg_string) imports.update(arg_imports) self.unindent() self.feed('],') else: arg_string, arg_imports = MigrationWriter.serialize(_arg_value) args = arg_string.splitlines() if len(args) > 1: self.feed('%s=%s' % (_arg_name, args[0])) for arg in args[1:-1]: self.feed(arg) self.feed('%s,' % args[-1]) else: self.feed('%s=%s,' % (_arg_name, arg_string)) imports.update(arg_imports) imports = set() name, args, kwargs = self.operation.deconstruct() argspec = inspect.getargspec(self.operation.__init__) # See if this operation is in django.db.migrations. If it is, # We can just use the fact we already have that imported, # otherwise, we need to add an import for the operation class. if getattr(migrations, name, None) == self.operation.__class__: self.feed('migrations.%s(' % name) else: imports.add('import %s' % (self.operation.__class__.__module__)) self.feed('%s.%s(' % (self.operation.__class__.__module__, name)) self.indent() # Start at one because argspec includes "self" for i, arg in enumerate(args, 1): arg_value = arg arg_name = argspec.args[i] _write(arg_name, arg_value) i = len(args) # Only iterate over remaining arguments for arg_name in argspec.args[i + 1:]: if arg_name in kwargs: arg_value = kwargs[arg_name] _write(arg_name, arg_value) self.unindent() self.feed('),') return self.render(), imports def indent(self): self.indentation += 1 def unindent(self): self.indentation -= 1 def feed(self, line): self.buff.append(' ' * (self.indentation * 4) + line) def render(self): return '\n'.join(self.buff) class MigrationWriter(object): """ Takes a Migration instance and is able to produce the contents of the migration file from it. """ def __init__(self, migration): self.migration = migration self.needs_manual_porting = False def as_string(self): """ Returns a string of the file contents. """ items = { "replaces_str": "", } imports = set() # Deconstruct operations operations = [] for operation in self.migration.operations: operation_string, operation_imports = OperationWriter(operation).serialize() imports.update(operation_imports) operations.append(operation_string) items["operations"] = "\n".join(operations) + "\n" if operations else "" # Format dependencies and write out swappable dependencies right dependencies = [] for dependency in self.migration.dependencies: if dependency[0] == "__setting__": dependencies.append(" migrations.swappable_dependency(settings.%s)," % dependency[1]) imports.add("from django.conf import settings") else: # No need to output bytestrings for dependencies dependency = tuple(force_text(s) for s in dependency) dependencies.append(" %s," % self.serialize(dependency)[0]) items["dependencies"] = "\n".join(dependencies) + "\n" if dependencies else "" # Format imports nicely, swapping imports of functions from migration files # for comments migration_imports = set() for line in list(imports): if re.match("^import (.*)\.\d+[^\s]*$", line): migration_imports.add(line.split("import")[1].strip()) imports.remove(line) self.needs_manual_porting = True imports.discard("from django.db import models") items["imports"] = "\n".join(imports) + "\n" if imports else "" if migration_imports: items["imports"] += ( "\n\n# Functions from the following migrations need manual " "copying.\n# Move them and any dependencies into this file, " "then update the\n# RunPython operations to refer to the local " "versions:\n# %s" ) % "\n# ".join(migration_imports) # If there's a replaces, make a string for it if self.migration.replaces: items['replaces_str'] = "\n replaces = %s\n" % self.serialize(self.migration.replaces)[0] return (MIGRATION_TEMPLATE % items).encode("utf8") @staticmethod def serialize_datetime(value): """ Returns a serialized version of a datetime object that is valid, executable python code. It converts timezone-aware values to utc with an 'executable' utc representation of tzinfo. """ if value.tzinfo is not None and value.tzinfo != utc: value = value.astimezone(utc) value_repr = repr(value).replace("<UTC>", "utc") if isinstance(value, datetime_safe.datetime): value_repr = "datetime.%s" % value_repr return value_repr @property def filename(self): return "%s.py" % self.migration.name @property def path(self): migrations_package_name = MigrationLoader.migrations_module(self.migration.app_label) # See if we can import the migrations module directly try: migrations_module = import_module(migrations_package_name) # Python 3 fails when the migrations directory does not have a # __init__.py file if not hasattr(migrations_module, '__file__'): raise ImportError basedir = os.path.dirname(upath(migrations_module.__file__)) except ImportError: app_config = apps.get_app_config(self.migration.app_label) migrations_package_basename = migrations_package_name.split(".")[-1] # Alright, see if it's a direct submodule of the app if '%s.%s' % (app_config.name, migrations_package_basename) == migrations_package_name: basedir = os.path.join(app_config.path, migrations_package_basename) else: # In case of using MIGRATION_MODULES setting and the custom # package doesn't exist, create one. package_dirs = migrations_package_name.split(".") create_path = os.path.join(upath(sys.path[0]), *package_dirs) if not os.path.isdir(create_path): os.makedirs(create_path) for i in range(1, len(package_dirs) + 1): init_dir = os.path.join(upath(sys.path[0]), *package_dirs[:i]) init_path = os.path.join(init_dir, "__init__.py") if not os.path.isfile(init_path): open(init_path, "w").close() return os.path.join(create_path, self.filename) return os.path.join(basedir, self.filename) @classmethod def serialize_deconstructed(cls, path, args, kwargs): name, imports = cls._serialize_path(path) strings = [] for arg in args: arg_string, arg_imports = cls.serialize(arg) strings.append(arg_string) imports.update(arg_imports) for kw, arg in kwargs.items(): arg_string, arg_imports = cls.serialize(arg) imports.update(arg_imports) strings.append("%s=%s" % (kw, arg_string)) return "%s(%s)" % (name, ", ".join(strings)), imports @classmethod def _serialize_path(cls, path): module, name = path.rsplit(".", 1) if module == "django.db.models": imports = {"from django.db import models"} name = "models.%s" % name else: imports = {"import %s" % module} name = path return name, imports @classmethod def serialize(cls, value): """ Serializes the value to a string that's parsable by Python, along with any needed imports to make that string work. More advanced than repr() as it can encode things like datetime.datetime.now. """ # FIXME: Ideally Promise would be reconstructible, but for now we # use force_text on them and defer to the normal string serialization # process. if isinstance(value, Promise): value = force_text(value) # Sequences if isinstance(value, (list, set, tuple)): imports = set() strings = [] for item in value: item_string, item_imports = cls.serialize(item) imports.update(item_imports) strings.append(item_string) if isinstance(value, set): # Don't use the literal "{%s}" as it doesn't support empty set format = "set([%s])" elif isinstance(value, tuple): # When len(value)==0, the empty tuple should be serialized as # "()", not "(,)" because (,) is invalid Python syntax. format = "(%s)" if len(value) != 1 else "(%s,)" else: format = "[%s]" return format % (", ".join(strings)), imports # Dictionaries elif isinstance(value, dict): imports = set() strings = [] for k, v in value.items(): k_string, k_imports = cls.serialize(k) v_string, v_imports = cls.serialize(v) imports.update(k_imports) imports.update(v_imports) strings.append((k_string, v_string)) return "{%s}" % (", ".join("%s: %s" % (k, v) for k, v in strings)), imports # Datetimes elif isinstance(value, datetime.datetime): value_repr = cls.serialize_datetime(value) imports = ["import datetime"] if value.tzinfo is not None: imports.append("from django.utils.timezone import utc") return value_repr, set(imports) # Dates elif isinstance(value, datetime.date): value_repr = repr(value) if isinstance(value, datetime_safe.date): value_repr = "datetime.%s" % value_repr return value_repr, {"import datetime"} # Times elif isinstance(value, datetime.time): value_repr = repr(value) if isinstance(value, datetime_safe.time): value_repr = "datetime.%s" % value_repr return value_repr, {"import datetime"} # Timedeltas elif isinstance(value, datetime.timedelta): return repr(value), {"import datetime"} # Settings references elif isinstance(value, SettingsReference): return "settings.%s" % value.setting_name, {"from django.conf import settings"} # Simple types elif isinstance(value, float): if math.isnan(value) or math.isinf(value): return 'float("{}")'.format(value), set() return repr(value), set() elif isinstance(value, six.integer_types + (bool, type(None))): return repr(value), set() elif isinstance(value, six.binary_type): value_repr = repr(value) if six.PY2: # Prepend the `b` prefix since we're importing unicode_literals value_repr = 'b' + value_repr return value_repr, set() elif isinstance(value, six.text_type): value_repr = repr(value) if six.PY2: # Strip the `u` prefix since we're importing unicode_literals value_repr = value_repr[1:] return value_repr, set() # Decimal elif isinstance(value, decimal.Decimal): return repr(value), {"from decimal import Decimal"} # Django fields elif isinstance(value, models.Field): attr_name, path, args, kwargs = value.deconstruct() return cls.serialize_deconstructed(path, args, kwargs) # Classes elif isinstance(value, type): special_cases = [ (models.Model, "models.Model", []), ] for case, string, imports in special_cases: if case is value: return string, set(imports) if hasattr(value, "__module__"): module = value.__module__ if module == six.moves.builtins.__name__: return value.__name__, set() else: return "%s.%s" % (module, value.__name__), {"import %s" % module} elif isinstance(value, models.manager.BaseManager): as_manager, manager_path, qs_path, args, kwargs = value.deconstruct() if as_manager: name, imports = cls._serialize_path(qs_path) return "%s.as_manager()" % name, imports else: return cls.serialize_deconstructed(manager_path, args, kwargs) elif isinstance(value, Operation): string, imports = OperationWriter(value, indentation=0).serialize() # Nested operation, trailing comma is handled in upper OperationWriter._write() return string.rstrip(','), imports # Anything that knows how to deconstruct itself. elif hasattr(value, 'deconstruct'): return cls.serialize_deconstructed(*value.deconstruct()) # Functions elif isinstance(value, (types.FunctionType, types.BuiltinFunctionType)): # @classmethod? if getattr(value, "__self__", None) and isinstance(value.__self__, type): klass = value.__self__ module = klass.__module__ return "%s.%s.%s" % (module, klass.__name__, value.__name__), {"import %s" % module} # Further error checking if value.__name__ == '<lambda>': raise ValueError("Cannot serialize function: lambda") if value.__module__ is None: raise ValueError("Cannot serialize function %r: No module" % value) # Python 3 is a lot easier, and only uses this branch if it's not local. if getattr(value, "__qualname__", None) and getattr(value, "__module__", None): if "<" not in value.__qualname__: # Qualname can include <locals> return "%s.%s" % (value.__module__, value.__qualname__), {"import %s" % value.__module__} # Python 2/fallback version module_name = value.__module__ # Make sure it's actually there and not an unbound method module = import_module(module_name) if not hasattr(module, value.__name__): raise ValueError( "Could not find function %s in %s.\n" "Please note that due to Python 2 limitations, you cannot " "serialize unbound method functions (e.g. a method " "declared and used in the same class body). Please move " "the function into the main module body to use migrations.\n" "For more information, see " "https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" % (value.__name__, module_name, get_docs_version())) return "%s.%s" % (module_name, value.__name__), {"import %s" % module_name} # Other iterables elif isinstance(value, collections.Iterable): imports = set() strings = [] for item in value: item_string, item_imports = cls.serialize(item) imports.update(item_imports) strings.append(item_string) # When len(strings)==0, the empty iterable should be serialized as # "()", not "(,)" because (,) is invalid Python syntax. format = "(%s)" if len(strings) != 1 else "(%s,)" return format % (", ".join(strings)), imports # Compiled regex elif isinstance(value, COMPILED_REGEX_TYPE): imports = {"import re"} regex_pattern, pattern_imports = cls.serialize(value.pattern) regex_flags, flag_imports = cls.serialize(value.flags) imports.update(pattern_imports) imports.update(flag_imports) args = [regex_pattern] if value.flags: args.append(regex_flags) return "re.compile(%s)" % ', '.join(args), imports # Uh oh. else: raise ValueError( "Cannot serialize: %r\nThere are some values Django cannot serialize into " "migration files.\nFor more, see https://docs.djangoproject.com/en/%s/" "topics/migrations/#migration-serializing" % (value, get_docs_version()) ) MIGRATION_TEMPLATE = """\ # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations %(imports)s class Migration(migrations.Migration): %(replaces_str)s dependencies = [ %(dependencies)s\ ] operations = [ %(operations)s\ ] """
bsd-3-clause
qrkourier/ansible
test/units/modules/network/f5/test_bigip_command.py
47
3394
# -*- coding: utf-8 -*- # # Copyright 2017 F5 Networks Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import sys from nose.plugins.skip import SkipTest if sys.version_info < (2, 7): raise SkipTest("F5 Ansible modules require Python >= 2.7") from ansible.compat.tests import unittest from ansible.compat.tests.mock import patch, Mock from ansible.module_utils import basic from ansible.module_utils._text import to_bytes from ansible.module_utils.f5_utils import AnsibleF5Client try: from library.bigip_command import Parameters from library.bigip_command import ModuleManager from library.bigip_command import ArgumentSpec except ImportError: try: from ansible.modules.network.f5.bigip_command import Parameters from ansible.modules.network.f5.bigip_command import ModuleManager from ansible.modules.network.f5.bigip_command import ArgumentSpec except ImportError: raise SkipTest("F5 Ansible modules require the f5-sdk Python library") fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def set_module_args(args): args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) basic._ANSIBLE_ARGS = to_bytes(args) def load_fixture(name): path = os.path.join(fixture_path, name) with open(path) as f: data = f.read() try: data = json.loads(data) except Exception: pass return data class TestParameters(unittest.TestCase): def test_module_parameters(self): args = dict( commands=[ "tmsh show sys version" ], server='localhost', user='admin', password='password' ) p = Parameters(args) assert len(p.commands) == 2 @patch('ansible.module_utils.f5_utils.AnsibleF5Client._get_mgmt_root', return_value=True) class TestManager(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() def test_run_single_command(self, *args): set_module_args(dict( commands=[ "tmsh show sys version" ], server='localhost', user='admin', password='password' )) client = AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) mm = ModuleManager(client) # Override methods to force specific logic in the module to happen mm.execute_on_device = Mock(return_value='foo') results = mm.exec_module() assert results['changed'] is True
gpl-3.0
ahmed-mahran/hue
desktop/core/ext-py/Django-1.6.10/tests/raw_query/tests.py
50
9182
from __future__ import absolute_import from datetime import date from django.db.models.query_utils import InvalidQuery from django.test import TestCase, skipUnlessDBFeature from .models import Author, Book, Coffee, Reviewer, FriendlyAuthor class RawQueryTests(TestCase): fixtures = ['raw_query_books.json'] def assertSuccessfulRawQuery(self, model, query, expected_results, expected_annotations=(), params=[], translations=None): """ Execute the passed query against the passed model and check the output """ results = list(model.objects.raw(query, params=params, translations=translations)) self.assertProcessed(model, results, expected_results, expected_annotations) self.assertAnnotations(results, expected_annotations) def assertProcessed(self, model, results, orig, expected_annotations=()): """ Compare the results of a raw query against expected results """ self.assertEqual(len(results), len(orig)) for index, item in enumerate(results): orig_item = orig[index] for annotation in expected_annotations: setattr(orig_item, *annotation) for field in model._meta.fields: # Check that all values on the model are equal self.assertEqual(getattr(item,field.attname), getattr(orig_item,field.attname)) # This includes checking that they are the same type self.assertEqual(type(getattr(item,field.attname)), type(getattr(orig_item,field.attname))) def assertNoAnnotations(self, results): """ Check that the results of a raw query contain no annotations """ self.assertAnnotations(results, ()) def assertAnnotations(self, results, expected_annotations): """ Check that the passed raw query results contain the expected annotations """ if expected_annotations: for index, result in enumerate(results): annotation, value = expected_annotations[index] self.assertTrue(hasattr(result, annotation)) self.assertEqual(getattr(result, annotation), value) def testSimpleRawQuery(self): """ Basic test of raw query with a simple database query """ query = "SELECT * FROM raw_query_author" authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def testRawQueryLazy(self): """ Raw queries are lazy: they aren't actually executed until they're iterated over. """ q = Author.objects.raw('SELECT * FROM raw_query_author') self.assertTrue(q.query.cursor is None) list(q) self.assertTrue(q.query.cursor is not None) def testFkeyRawQuery(self): """ Test of a simple raw query against a model containing a foreign key """ query = "SELECT * FROM raw_query_book" books = Book.objects.all() self.assertSuccessfulRawQuery(Book, query, books) def testDBColumnHandler(self): """ Test of a simple raw query against a model containing a field with db_column defined. """ query = "SELECT * FROM raw_query_coffee" coffees = Coffee.objects.all() self.assertSuccessfulRawQuery(Coffee, query, coffees) def testOrderHandler(self): """ Test of raw raw query's tolerance for columns being returned in any order """ selects = ( ('dob, last_name, first_name, id'), ('last_name, dob, first_name, id'), ('first_name, last_name, dob, id'), ) for select in selects: query = "SELECT %s FROM raw_query_author" % select authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def testTranslations(self): """ Test of raw query's optional ability to translate unexpected result column names to specific model fields """ query = "SELECT first_name AS first, last_name AS last, dob, id FROM raw_query_author" translations = {'first': 'first_name', 'last': 'last_name'} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations) def testParams(self): """ Test passing optional query parameters """ query = "SELECT * FROM raw_query_author WHERE first_name = %s" author = Author.objects.all()[2] params = [author.first_name] qset = Author.objects.raw(query, params=params) results = list(qset) self.assertProcessed(Author, results, [author]) self.assertNoAnnotations(results) self.assertEqual(len(results), 1) self.assertIsInstance(repr(qset), str) @skipUnlessDBFeature('supports_paramstyle_pyformat') def testPyformatParams(self): """ Test passing optional query parameters """ query = "SELECT * FROM raw_query_author WHERE first_name = %(first)s" author = Author.objects.all()[2] params = {'first': author.first_name} qset = Author.objects.raw(query, params=params) results = list(qset) self.assertProcessed(Author, results, [author]) self.assertNoAnnotations(results) self.assertEqual(len(results), 1) self.assertIsInstance(repr(qset), str) def testManyToMany(self): """ Test of a simple raw query against a model containing a m2m field """ query = "SELECT * FROM raw_query_reviewer" reviewers = Reviewer.objects.all() self.assertSuccessfulRawQuery(Reviewer, query, reviewers) def testExtraConversions(self): """ Test to insure that extra translations are ignored. """ query = "SELECT * FROM raw_query_author" translations = {'something': 'else'} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations) def testMissingFields(self): query = "SELECT id, first_name, dob FROM raw_query_author" for author in Author.objects.raw(query): self.assertNotEqual(author.first_name, None) # last_name isn't given, but it will be retrieved on demand self.assertNotEqual(author.last_name, None) def testMissingFieldsWithoutPK(self): query = "SELECT first_name, dob FROM raw_query_author" try: list(Author.objects.raw(query)) self.fail('Query without primary key should fail') except InvalidQuery: pass def testAnnotations(self): query = "SELECT a.*, count(b.id) as book_count FROM raw_query_author a LEFT JOIN raw_query_book b ON a.id = b.author_id GROUP BY a.id, a.first_name, a.last_name, a.dob ORDER BY a.id" expected_annotations = ( ('book_count', 3), ('book_count', 0), ('book_count', 1), ('book_count', 0), ) authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, expected_annotations) def testWhiteSpaceQuery(self): query = " SELECT * FROM raw_query_author" authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def testMultipleIterations(self): query = "SELECT * FROM raw_query_author" normal_authors = Author.objects.all() raw_authors = Author.objects.raw(query) # First Iteration first_iterations = 0 for index, raw_author in enumerate(raw_authors): self.assertEqual(normal_authors[index], raw_author) first_iterations += 1 # Second Iteration second_iterations = 0 for index, raw_author in enumerate(raw_authors): self.assertEqual(normal_authors[index], raw_author) second_iterations += 1 self.assertEqual(first_iterations, second_iterations) def testGetItem(self): # Indexing on RawQuerySets query = "SELECT * FROM raw_query_author ORDER BY id ASC" third_author = Author.objects.raw(query)[2] self.assertEqual(third_author.first_name, 'Bob') first_two = Author.objects.raw(query)[0:2] self.assertEqual(len(first_two), 2) self.assertRaises(TypeError, lambda: Author.objects.raw(query)['test']) def test_inheritance(self): # date is the end of the Cuban Missile Crisis, I have no idea when # Wesley was bron f = FriendlyAuthor.objects.create(first_name="Wesley", last_name="Chun", dob=date(1962, 10, 28)) query = "SELECT * FROM raw_query_friendlyauthor" self.assertEqual( [o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk] ) def test_query_count(self): self.assertNumQueries(1, list, Author.objects.raw("SELECT * FROM raw_query_author") )
apache-2.0
RonnChyran/DesuraTools-py
ui/guihelpers.py
1
3045
#coding=utf-8 import logging import webbrowser from PySide.QtCore import QThread, Qt from PySide.QtGui import QDialog, QStyle, QMessageBox, QPixmap from ui.ui_progressbar import Ui_ProgressBar import windows __author__ = 'ron975' class DesuraWaiter(QThread): def __init__(self, username, parent=None): super(DesuraWaiter, self).__init__(parent) self.username = username def run(self): if len(self.username) == 0: return if not windows.desura_running(self.username): start_desura() while not windows.desura_running(self.username): self.msleep(100) return return class ProgressBarDialog(QDialog, Ui_ProgressBar): def __init__(self, parent=None): super(ProgressBarDialog, self).__init__(parent) self.setupUi(self) self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint) self.iconLabel.setPixmap(QStyle.standardPixmap(self.style(), QStyle.SP_MessageBoxInformation)) def setText(self, text): self.textLabel.setText(text) def setInformativeText(self, text): self.infoTextLabel.setText(text) def setMaximum(self, maximum): self.progressBar.setMaximum(maximum) def setAccount(self, account, adverb='by'): self.accountLabel.setText("{0} account {1}".format(adverb, account)) def increment(self, increment, game): value = self.progressBar.value() self.progressBar.setValue(value+increment) self.currentGame.setText(game) def user_choice(text, windowtitle, icon, acceptbutton="OK"): choice_dialog = QMessageBox() choice_dialog.setWindowIcon(QPixmap("../icons/desuratools_256.png")) choice_dialog.setText(text) choice_dialog.setIcon(icon) choice_dialog.setStandardButtons(QMessageBox.Cancel) choice_dialog.setWindowTitle(windowtitle) choice_dialog.addButton(acceptbutton, QMessageBox.AcceptRole) return choice_dialog def error_message(text): errorbox = QMessageBox() errorbox.setWindowIcon(QPixmap("../icons/desuratools_256.png")) errorbox.setWindowTitle("Error") errorbox.setText(text) errorbox.setIcon(QMessageBox.Critical) return errorbox def get_logger(name, fh): logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) fh = logging.FileHandler(fh) sh = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s') fh.setFormatter(formatter) sh.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(sh) return logger def start_desura(): try: windows.start_desura() except WindowsError: error_message("Desura has not been installed or is not installed correctly. <br />" "Please install Desura before using DesuraTools").exec_() webbrowser.open("http://www.desura.com/install", 2) except Exception, e: error_message("Error occured when launching Desura <br /> {0}".format(e.message))
gpl-3.0
izonder/intellij-community
python/helpers/pydev/third_party/pep8/lib2to3/lib2to3/pgen2/pgen.py
321
13786
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # Pgen imports from . import grammar, token, tokenize class PgenGrammar(grammar.Grammar): pass class ParserGenerator(object): def __init__(self, filename, stream=None): close_stream = None if stream is None: stream = open(filename) close_stream = stream.close self.filename = filename self.stream = stream self.generator = tokenize.generate_tokens(stream.readline) self.gettoken() # Initialize lookahead self.dfas, self.startsymbol = self.parse() if close_stream is not None: close_stream() self.first = {} # map from symbol name to set of tokens self.addfirstsets() def make_grammar(self): c = PgenGrammar() names = self.dfas.keys() names.sort() names.remove(self.startsymbol) names.insert(0, self.startsymbol) for name in names: i = 256 + len(c.symbol2number) c.symbol2number[name] = i c.number2symbol[i] = name for name in names: dfa = self.dfas[name] states = [] for state in dfa: arcs = [] for label, next in state.arcs.iteritems(): arcs.append((self.make_label(c, label), dfa.index(next))) if state.isfinal: arcs.append((0, dfa.index(state))) states.append(arcs) c.states.append(states) c.dfas[c.symbol2number[name]] = (states, self.make_first(c, name)) c.start = c.symbol2number[self.startsymbol] return c def make_first(self, c, name): rawfirst = self.first[name] first = {} for label in rawfirst: ilabel = self.make_label(c, label) ##assert ilabel not in first # XXX failed on <> ... != first[ilabel] = 1 return first def make_label(self, c, label): # XXX Maybe this should be a method on a subclass of converter? ilabel = len(c.labels) if label[0].isalpha(): # Either a symbol name or a named token if label in c.symbol2number: # A symbol name (a non-terminal) if label in c.symbol2label: return c.symbol2label[label] else: c.labels.append((c.symbol2number[label], None)) c.symbol2label[label] = ilabel return ilabel else: # A named token (NAME, NUMBER, STRING) itoken = getattr(token, label, None) assert isinstance(itoken, int), label assert itoken in token.tok_name, label if itoken in c.tokens: return c.tokens[itoken] else: c.labels.append((itoken, None)) c.tokens[itoken] = ilabel return ilabel else: # Either a keyword or an operator assert label[0] in ('"', "'"), label value = eval(label) if value[0].isalpha(): # A keyword if value in c.keywords: return c.keywords[value] else: c.labels.append((token.NAME, value)) c.keywords[value] = ilabel return ilabel else: # An operator (any non-numeric token) itoken = grammar.opmap[value] # Fails if unknown token if itoken in c.tokens: return c.tokens[itoken] else: c.labels.append((itoken, None)) c.tokens[itoken] = ilabel return ilabel def addfirstsets(self): names = self.dfas.keys() names.sort() for name in names: if name not in self.first: self.calcfirst(name) #print name, self.first[name].keys() def calcfirst(self, name): dfa = self.dfas[name] self.first[name] = None # dummy to detect left recursion state = dfa[0] totalset = {} overlapcheck = {} for label, next in state.arcs.iteritems(): if label in self.dfas: if label in self.first: fset = self.first[label] if fset is None: raise ValueError("recursion for rule %r" % name) else: self.calcfirst(label) fset = self.first[label] totalset.update(fset) overlapcheck[label] = fset else: totalset[label] = 1 overlapcheck[label] = {label: 1} inverse = {} for label, itsfirst in overlapcheck.iteritems(): for symbol in itsfirst: if symbol in inverse: raise ValueError("rule %s is ambiguous; %s is in the" " first sets of %s as well as %s" % (name, symbol, label, inverse[symbol])) inverse[symbol] = label self.first[name] = totalset def parse(self): dfas = {} startsymbol = None # MSTART: (NEWLINE | RULE)* ENDMARKER while self.type != token.ENDMARKER: while self.type == token.NEWLINE: self.gettoken() # RULE: NAME ':' RHS NEWLINE name = self.expect(token.NAME) self.expect(token.OP, ":") a, z = self.parse_rhs() self.expect(token.NEWLINE) #self.dump_nfa(name, a, z) dfa = self.make_dfa(a, z) #self.dump_dfa(name, dfa) oldlen = len(dfa) self.simplify_dfa(dfa) newlen = len(dfa) dfas[name] = dfa #print name, oldlen, newlen if startsymbol is None: startsymbol = name return dfas, startsymbol def make_dfa(self, start, finish): # To turn an NFA into a DFA, we define the states of the DFA # to correspond to *sets* of states of the NFA. Then do some # state reduction. Let's represent sets as dicts with 1 for # values. assert isinstance(start, NFAState) assert isinstance(finish, NFAState) def closure(state): base = {} addclosure(state, base) return base def addclosure(state, base): assert isinstance(state, NFAState) if state in base: return base[state] = 1 for label, next in state.arcs: if label is None: addclosure(next, base) states = [DFAState(closure(start), finish)] for state in states: # NB states grows while we're iterating arcs = {} for nfastate in state.nfaset: for label, next in nfastate.arcs: if label is not None: addclosure(next, arcs.setdefault(label, {})) for label, nfaset in arcs.iteritems(): for st in states: if st.nfaset == nfaset: break else: st = DFAState(nfaset, finish) states.append(st) state.addarc(st, label) return states # List of DFAState instances; first one is start def dump_nfa(self, name, start, finish): print "Dump of NFA for", name todo = [start] for i, state in enumerate(todo): print " State", i, state is finish and "(final)" or "" for label, next in state.arcs: if next in todo: j = todo.index(next) else: j = len(todo) todo.append(next) if label is None: print " -> %d" % j else: print " %s -> %d" % (label, j) def dump_dfa(self, name, dfa): print "Dump of DFA for", name for i, state in enumerate(dfa): print " State", i, state.isfinal and "(final)" or "" for label, next in state.arcs.iteritems(): print " %s -> %d" % (label, dfa.index(next)) def simplify_dfa(self, dfa): # This is not theoretically optimal, but works well enough. # Algorithm: repeatedly look for two states that have the same # set of arcs (same labels pointing to the same nodes) and # unify them, until things stop changing. # dfa is a list of DFAState instances changes = True while changes: changes = False for i, state_i in enumerate(dfa): for j in range(i+1, len(dfa)): state_j = dfa[j] if state_i == state_j: #print " unify", i, j del dfa[j] for state in dfa: state.unifystate(state_j, state_i) changes = True break def parse_rhs(self): # RHS: ALT ('|' ALT)* a, z = self.parse_alt() if self.value != "|": return a, z else: aa = NFAState() zz = NFAState() aa.addarc(a) z.addarc(zz) while self.value == "|": self.gettoken() a, z = self.parse_alt() aa.addarc(a) z.addarc(zz) return aa, zz def parse_alt(self): # ALT: ITEM+ a, b = self.parse_item() while (self.value in ("(", "[") or self.type in (token.NAME, token.STRING)): c, d = self.parse_item() b.addarc(c) b = d return a, b def parse_item(self): # ITEM: '[' RHS ']' | ATOM ['+' | '*'] if self.value == "[": self.gettoken() a, z = self.parse_rhs() self.expect(token.OP, "]") a.addarc(z) return a, z else: a, z = self.parse_atom() value = self.value if value not in ("+", "*"): return a, z self.gettoken() z.addarc(a) if value == "+": return a, z else: return a, a def parse_atom(self): # ATOM: '(' RHS ')' | NAME | STRING if self.value == "(": self.gettoken() a, z = self.parse_rhs() self.expect(token.OP, ")") return a, z elif self.type in (token.NAME, token.STRING): a = NFAState() z = NFAState() a.addarc(z, self.value) self.gettoken() return a, z else: self.raise_error("expected (...) or NAME or STRING, got %s/%s", self.type, self.value) def expect(self, type, value=None): if self.type != type or (value is not None and self.value != value): self.raise_error("expected %s/%s, got %s/%s", type, value, self.type, self.value) value = self.value self.gettoken() return value def gettoken(self): tup = self.generator.next() while tup[0] in (tokenize.COMMENT, tokenize.NL): tup = self.generator.next() self.type, self.value, self.begin, self.end, self.line = tup #print token.tok_name[self.type], repr(self.value) def raise_error(self, msg, *args): if args: try: msg = msg % args except: msg = " ".join([msg] + map(str, args)) raise SyntaxError(msg, (self.filename, self.end[0], self.end[1], self.line)) class NFAState(object): def __init__(self): self.arcs = [] # list of (label, NFAState) pairs def addarc(self, next, label=None): assert label is None or isinstance(label, str) assert isinstance(next, NFAState) self.arcs.append((label, next)) class DFAState(object): def __init__(self, nfaset, final): assert isinstance(nfaset, dict) assert isinstance(iter(nfaset).next(), NFAState) assert isinstance(final, NFAState) self.nfaset = nfaset self.isfinal = final in nfaset self.arcs = {} # map from label to DFAState def addarc(self, next, label): assert isinstance(label, str) assert label not in self.arcs assert isinstance(next, DFAState) self.arcs[label] = next def unifystate(self, old, new): for label, next in self.arcs.iteritems(): if next is old: self.arcs[label] = new def __eq__(self, other): # Equality test -- ignore the nfaset instance variable assert isinstance(other, DFAState) if self.isfinal != other.isfinal: return False # Can't just return self.arcs == other.arcs, because that # would invoke this method recursively, with cycles... if len(self.arcs) != len(other.arcs): return False for label, next in self.arcs.iteritems(): if next is not other.arcs.get(label): return False return True __hash__ = None # For Py3 compatibility. def generate_grammar(filename="Grammar.txt"): p = ParserGenerator(filename) return p.make_grammar()
apache-2.0
salvarico/my-project
docs/source/conf.py
2
8700
# -*- coding: utf-8 -*- # This file is based upon the file generated by sphinx-quickstart. However, # where sphinx-quickstart hardcodes values in this file that you input, this # file has been changed to pull from your module's metadata module. # # This file is execfile()d with the current directory set to its containing # dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../..')) # Import project metadata from my_module import metadata # -- General configuration ---------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] # show todos todo_include_todos = True # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = metadata.project copyright = metadata.copyright # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = metadata.version # The full version, including alpha/beta/rc tags. release = metadata.version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output -------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = metadata.project_no_spaces + 'doc' # -- Options for LaTeX output ------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, # documentclass [howto/manual]). latex_documents = [ ('index', metadata.project_no_spaces + '.tex', metadata.project + ' Documentation', metadata.authors_string, 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', metadata.package, metadata.project + ' Documentation', metadata.authors_string, 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ----------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', metadata.project_no_spaces, metadata.project + ' Documentation', metadata.authors_string, metadata.project_no_spaces, metadata.description, 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'python': ('http://docs.python.org/', None), } # Extra local configuration. This is useful for placing the class description # in the class docstring and the __init__ parameter documentation in the # __init__ docstring. See # <http://sphinx-doc.org/ext/autodoc.html#confval-autoclass_content> for more # information. autoclass_content = 'both'
mit
drnextgis/QGIS
python/plugins/processing/algs/gdal/GridNearest.py
5
4628
# -*- coding: utf-8 -*- """ *************************************************************************** GridNearest.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ from builtins import str __author__ = 'Alexander Bruy' __date__ = 'October 2013' __copyright__ = '(C) 2013, Alexander Bruy' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.PyQt.QtGui import QIcon from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterTableField from processing.core.parameters import ParameterNumber from processing.core.parameters import ParameterSelection from processing.core.outputs import OutputRaster from processing.tools import dataobjects from processing.algs.gdal.GdalUtils import GdalUtils pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] class GridNearest(GdalAlgorithm): INPUT = 'INPUT' Z_FIELD = 'Z_FIELD' RADIUS_1 = 'RADIUS_1' RADIUS_2 = 'RADIUS_2' ANGLE = 'ANGLE' NODATA = 'NODATA' OUTPUT = 'OUTPUT' RTYPE = 'RTYPE' TYPE = ['Byte', 'Int16', 'UInt16', 'UInt32', 'Int32', 'Float32', 'Float64'] def getIcon(self): return QIcon(os.path.join(pluginPath, 'images', 'gdaltools', 'grid.png')) def commandLineName(self): return "gdalogr:gridnearestneighbor" def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Grid (Nearest neighbor)') self.group, self.i18n_group = self.trAlgorithm('[GDAL] Analysis') self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'), [dataobjects.TYPE_VECTOR_POINT])) self.addParameter(ParameterTableField(self.Z_FIELD, self.tr('Z field'), self.INPUT, ParameterTableField.DATA_TYPE_NUMBER, True)) self.addParameter(ParameterNumber(self.RADIUS_1, self.tr('Radius 1'), 0.0, 99999999.999999, 0.0)) self.addParameter(ParameterNumber(self.RADIUS_2, self.tr('Radius 2'), 0.0, 99999999.999999, 0.0)) self.addParameter(ParameterNumber(self.ANGLE, self.tr('Angle'), 0.0, 359.0, 0.0)) self.addParameter(ParameterNumber(self.NODATA, self.tr('Nodata'), 0.0, 99999999.999999, 0.0)) self.addParameter(ParameterSelection(self.RTYPE, self.tr('Output raster type'), self.TYPE, 5)) self.addOutput(OutputRaster(self.OUTPUT, self.tr('Interpolated nearest neighbor'))) def getConsoleCommands(self): arguments = ['-l'] arguments.append( os.path.basename(os.path.splitext( str(self.getParameterValue(self.INPUT)))[0])) fieldName = self.getParameterValue(self.Z_FIELD) if fieldName is not None and fieldName != '': arguments.append('-zfield') arguments.append(fieldName) params = 'nearest' params += ':radius1=%s' % self.getParameterValue(self.RADIUS_1) params += ':radius2=%s' % self.getParameterValue(self.RADIUS_2) params += ':angle=%s' % self.getParameterValue(self.ANGLE) params += ':nodata=%s' % self.getParameterValue(self.NODATA) arguments.append('-a') arguments.append(params) arguments.append('-ot') arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)]) arguments.append(str(self.getParameterValue(self.INPUT))) arguments.append(str(self.getOutputValue(self.OUTPUT))) return ['gdal_grid', GdalUtils.escapeAndJoin(arguments)]
gpl-2.0
fighterCui/L4ReFiascoOC
l4/pkg/python/contrib/Lib/test/test_bool.py
96
13248
# Test properties of bool promised by PEP 285 import unittest from test import test_support import os class BoolTest(unittest.TestCase): def assertIs(self, a, b): self.assert_(a is b) def assertIsNot(self, a, b): self.assert_(a is not b) def test_subclass(self): try: class C(bool): pass except TypeError: pass else: self.fail("bool should not be subclassable") self.assertRaises(TypeError, int.__new__, bool, 0) def test_print(self): try: fo = open(test_support.TESTFN, "wb") print >> fo, False, True fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), 'False True\n') finally: fo.close() os.remove(test_support.TESTFN) def test_repr(self): self.assertEqual(repr(False), 'False') self.assertEqual(repr(True), 'True') self.assertEqual(eval(repr(False)), False) self.assertEqual(eval(repr(True)), True) def test_str(self): self.assertEqual(str(False), 'False') self.assertEqual(str(True), 'True') def test_int(self): self.assertEqual(int(False), 0) self.assertIsNot(int(False), False) self.assertEqual(int(True), 1) self.assertIsNot(int(True), True) def test_math(self): self.assertEqual(+False, 0) self.assertIsNot(+False, False) self.assertEqual(-False, 0) self.assertIsNot(-False, False) self.assertEqual(abs(False), 0) self.assertIsNot(abs(False), False) self.assertEqual(+True, 1) self.assertIsNot(+True, True) self.assertEqual(-True, -1) self.assertEqual(abs(True), 1) self.assertIsNot(abs(True), True) self.assertEqual(~False, -1) self.assertEqual(~True, -2) self.assertEqual(False+2, 2) self.assertEqual(True+2, 3) self.assertEqual(2+False, 2) self.assertEqual(2+True, 3) self.assertEqual(False+False, 0) self.assertIsNot(False+False, False) self.assertEqual(False+True, 1) self.assertIsNot(False+True, True) self.assertEqual(True+False, 1) self.assertIsNot(True+False, True) self.assertEqual(True+True, 2) self.assertEqual(True-True, 0) self.assertIsNot(True-True, False) self.assertEqual(False-False, 0) self.assertIsNot(False-False, False) self.assertEqual(True-False, 1) self.assertIsNot(True-False, True) self.assertEqual(False-True, -1) self.assertEqual(True*1, 1) self.assertEqual(False*1, 0) self.assertIsNot(False*1, False) self.assertEqual(True/1, 1) self.assertIsNot(True/1, True) self.assertEqual(False/1, 0) self.assertIsNot(False/1, False) for b in False, True: for i in 0, 1, 2: self.assertEqual(b**i, int(b)**i) self.assertIsNot(b**i, bool(int(b)**i)) for a in False, True: for b in False, True: self.assertIs(a&b, bool(int(a)&int(b))) self.assertIs(a|b, bool(int(a)|int(b))) self.assertIs(a^b, bool(int(a)^int(b))) self.assertEqual(a&int(b), int(a)&int(b)) self.assertIsNot(a&int(b), bool(int(a)&int(b))) self.assertEqual(a|int(b), int(a)|int(b)) self.assertIsNot(a|int(b), bool(int(a)|int(b))) self.assertEqual(a^int(b), int(a)^int(b)) self.assertIsNot(a^int(b), bool(int(a)^int(b))) self.assertEqual(int(a)&b, int(a)&int(b)) self.assertIsNot(int(a)&b, bool(int(a)&int(b))) self.assertEqual(int(a)|b, int(a)|int(b)) self.assertIsNot(int(a)|b, bool(int(a)|int(b))) self.assertEqual(int(a)^b, int(a)^int(b)) self.assertIsNot(int(a)^b, bool(int(a)^int(b))) self.assertIs(1==1, True) self.assertIs(1==0, False) self.assertIs(0<1, True) self.assertIs(1<0, False) self.assertIs(0<=0, True) self.assertIs(1<=0, False) self.assertIs(1>0, True) self.assertIs(1>1, False) self.assertIs(1>=1, True) self.assertIs(0>=1, False) self.assertIs(0!=1, True) self.assertIs(0!=0, False) x = [1] self.assertIs(x is x, True) self.assertIs(x is not x, False) self.assertIs(1 in x, True) self.assertIs(0 in x, False) self.assertIs(1 not in x, False) self.assertIs(0 not in x, True) x = {1: 2} self.assertIs(x is x, True) self.assertIs(x is not x, False) self.assertIs(1 in x, True) self.assertIs(0 in x, False) self.assertIs(1 not in x, False) self.assertIs(0 not in x, True) self.assertIs(not True, False) self.assertIs(not False, True) def test_convert(self): self.assertRaises(TypeError, bool, 42, 42) self.assertIs(bool(10), True) self.assertIs(bool(1), True) self.assertIs(bool(-1), True) self.assertIs(bool(0), False) self.assertIs(bool("hello"), True) self.assertIs(bool(""), False) self.assertIs(bool(), False) def test_hasattr(self): self.assertIs(hasattr([], "append"), True) self.assertIs(hasattr([], "wobble"), False) def test_callable(self): self.assertIs(callable(len), True) self.assertIs(callable(1), False) def test_isinstance(self): self.assertIs(isinstance(True, bool), True) self.assertIs(isinstance(False, bool), True) self.assertIs(isinstance(True, int), True) self.assertIs(isinstance(False, int), True) self.assertIs(isinstance(1, bool), False) self.assertIs(isinstance(0, bool), False) def test_issubclass(self): self.assertIs(issubclass(bool, int), True) self.assertIs(issubclass(int, bool), False) def test_haskey(self): self.assertIs({}.has_key(1), False) self.assertIs({1:1}.has_key(1), True) def test_string(self): self.assertIs("xyz".endswith("z"), True) self.assertIs("xyz".endswith("x"), False) self.assertIs("xyz0123".isalnum(), True) self.assertIs("@#$%".isalnum(), False) self.assertIs("xyz".isalpha(), True) self.assertIs("@#$%".isalpha(), False) self.assertIs("0123".isdigit(), True) self.assertIs("xyz".isdigit(), False) self.assertIs("xyz".islower(), True) self.assertIs("XYZ".islower(), False) self.assertIs(" ".isspace(), True) self.assertIs("XYZ".isspace(), False) self.assertIs("X".istitle(), True) self.assertIs("x".istitle(), False) self.assertIs("XYZ".isupper(), True) self.assertIs("xyz".isupper(), False) self.assertIs("xyz".startswith("x"), True) self.assertIs("xyz".startswith("z"), False) if test_support.have_unicode: self.assertIs(unicode("xyz", 'ascii').endswith(unicode("z", 'ascii')), True) self.assertIs(unicode("xyz", 'ascii').endswith(unicode("x", 'ascii')), False) self.assertIs(unicode("xyz0123", 'ascii').isalnum(), True) self.assertIs(unicode("@#$%", 'ascii').isalnum(), False) self.assertIs(unicode("xyz", 'ascii').isalpha(), True) self.assertIs(unicode("@#$%", 'ascii').isalpha(), False) self.assertIs(unicode("0123", 'ascii').isdecimal(), True) self.assertIs(unicode("xyz", 'ascii').isdecimal(), False) self.assertIs(unicode("0123", 'ascii').isdigit(), True) self.assertIs(unicode("xyz", 'ascii').isdigit(), False) self.assertIs(unicode("xyz", 'ascii').islower(), True) self.assertIs(unicode("XYZ", 'ascii').islower(), False) self.assertIs(unicode("0123", 'ascii').isnumeric(), True) self.assertIs(unicode("xyz", 'ascii').isnumeric(), False) self.assertIs(unicode(" ", 'ascii').isspace(), True) self.assertIs(unicode("XYZ", 'ascii').isspace(), False) self.assertIs(unicode("X", 'ascii').istitle(), True) self.assertIs(unicode("x", 'ascii').istitle(), False) self.assertIs(unicode("XYZ", 'ascii').isupper(), True) self.assertIs(unicode("xyz", 'ascii').isupper(), False) self.assertIs(unicode("xyz", 'ascii').startswith(unicode("x", 'ascii')), True) self.assertIs(unicode("xyz", 'ascii').startswith(unicode("z", 'ascii')), False) def test_boolean(self): self.assertEqual(True & 1, 1) self.assert_(not isinstance(True & 1, bool)) self.assertIs(True & True, True) self.assertEqual(True | 1, 1) self.assert_(not isinstance(True | 1, bool)) self.assertIs(True | True, True) self.assertEqual(True ^ 1, 0) self.assert_(not isinstance(True ^ 1, bool)) self.assertIs(True ^ True, False) def test_fileclosed(self): try: f = file(test_support.TESTFN, "w") self.assertIs(f.closed, False) f.close() self.assertIs(f.closed, True) finally: os.remove(test_support.TESTFN) def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) self.assertIs(operator.isCallable(0), False) self.assertIs(operator.isCallable(len), True) self.assertIs(operator.isNumberType(None), False) self.assertIs(operator.isNumberType(0), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.isSequenceType(0), False) self.assertIs(operator.isSequenceType([]), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.isMappingType(1), False) self.assertIs(operator.isMappingType({}), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True) def test_marshal(self): import marshal self.assertIs(marshal.loads(marshal.dumps(True)), True) self.assertIs(marshal.loads(marshal.dumps(False)), False) def test_pickle(self): import pickle self.assertIs(pickle.loads(pickle.dumps(True)), True) self.assertIs(pickle.loads(pickle.dumps(False)), False) self.assertIs(pickle.loads(pickle.dumps(True, True)), True) self.assertIs(pickle.loads(pickle.dumps(False, True)), False) def test_cpickle(self): import cPickle self.assertIs(cPickle.loads(cPickle.dumps(True)), True) self.assertIs(cPickle.loads(cPickle.dumps(False)), False) self.assertIs(cPickle.loads(cPickle.dumps(True, True)), True) self.assertIs(cPickle.loads(cPickle.dumps(False, True)), False) def test_mixedpickle(self): import pickle, cPickle self.assertIs(pickle.loads(cPickle.dumps(True)), True) self.assertIs(pickle.loads(cPickle.dumps(False)), False) self.assertIs(pickle.loads(cPickle.dumps(True, True)), True) self.assertIs(pickle.loads(cPickle.dumps(False, True)), False) self.assertIs(cPickle.loads(pickle.dumps(True)), True) self.assertIs(cPickle.loads(pickle.dumps(False)), False) self.assertIs(cPickle.loads(pickle.dumps(True, True)), True) self.assertIs(cPickle.loads(pickle.dumps(False, True)), False) def test_picklevalues(self): import pickle, cPickle # Test for specific backwards-compatible pickle values self.assertEqual(pickle.dumps(True), "I01\n.") self.assertEqual(pickle.dumps(False), "I00\n.") self.assertEqual(cPickle.dumps(True), "I01\n.") self.assertEqual(cPickle.dumps(False), "I00\n.") self.assertEqual(pickle.dumps(True, True), "I01\n.") self.assertEqual(pickle.dumps(False, True), "I00\n.") self.assertEqual(cPickle.dumps(True, True), "I01\n.") self.assertEqual(cPickle.dumps(False, True), "I00\n.") def test_convert_to_bool(self): # Verify that TypeError occurs when bad things are returned # from __nonzero__(). This isn't really a bool test, but # it's related. check = lambda o: self.assertRaises(TypeError, bool, o) class Foo(object): def __nonzero__(self): return self check(Foo()) class Bar(object): def __nonzero__(self): return "Yes" check(Bar()) class Baz(int): def __nonzero__(self): return self check(Baz()) def test_main(): test_support.run_unittest(BoolTest) if __name__ == "__main__": test_main()
gpl-2.0
samuell/luigi
test/wrap_test.py
18
2841
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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 datetime from helpers import unittest import luigi import luigi.notifications from luigi.mock import MockTarget from luigi.util import inherits luigi.notifications.DEBUG = True class A(luigi.Task): def output(self): return MockTarget('/tmp/a.txt') def run(self): f = self.output().open('w') print('hello, world', file=f) f.close() class B(luigi.Task): date = luigi.DateParameter() def output(self): return MockTarget(self.date.strftime('/tmp/b-%Y-%m-%d.txt')) def run(self): f = self.output().open('w') print('goodbye, space', file=f) f.close() def XMLWrapper(cls): @inherits(cls) class XMLWrapperCls(luigi.Task): def requires(self): return self.clone_parent() def run(self): f = self.input().open('r') g = self.output().open('w') print('<?xml version="1.0" ?>', file=g) for line in f: print('<dummy-xml>' + line.strip() + '</dummy-xml>', file=g) g.close() return XMLWrapperCls class AXML(XMLWrapper(A)): def output(self): return MockTarget('/tmp/a.xml') class BXML(XMLWrapper(B)): def output(self): return MockTarget(self.date.strftime('/tmp/b-%Y-%m-%d.xml')) class WrapperTest(unittest.TestCase): ''' This test illustrates how a task class can wrap another task class by modifying its behavior. See instance_wrap_test.py for an example of how instances can wrap each other. ''' workers = 1 def setUp(self): MockTarget.fs.clear() def test_a(self): luigi.build([AXML()], local_scheduler=True, no_lock=True, workers=self.workers) self.assertEqual(MockTarget.fs.get_data('/tmp/a.xml'), b'<?xml version="1.0" ?>\n<dummy-xml>hello, world</dummy-xml>\n') def test_b(self): luigi.build([BXML(datetime.date(2012, 1, 1))], local_scheduler=True, no_lock=True, workers=self.workers) self.assertEqual(MockTarget.fs.get_data('/tmp/b-2012-01-01.xml'), b'<?xml version="1.0" ?>\n<dummy-xml>goodbye, space</dummy-xml>\n') class WrapperWithMultipleWorkersTest(WrapperTest): workers = 7
apache-2.0
tlatzko/spmcluster
.tox/2.7-cover/lib/python2.7/site-packages/nose/core.py
69
13093
"""Implements nose test program and collector. """ from __future__ import generators import logging import os import sys import time import unittest from nose.config import Config, all_config_files from nose.loader import defaultTestLoader from nose.plugins.manager import PluginManager, DefaultPluginManager, \ RestrictedPluginManager from nose.result import TextTestResult from nose.suite import FinalizingSuiteWrapper from nose.util import isclass, tolist log = logging.getLogger('nose.core') compat_24 = sys.version_info >= (2, 4) __all__ = ['TestProgram', 'main', 'run', 'run_exit', 'runmodule', 'collector', 'TextTestRunner'] class TextTestRunner(unittest.TextTestRunner): """Test runner that uses nose's TextTestResult to enable errorClasses, as well as providing hooks for plugins to override or replace the test output stream, results, and the test case itself. """ def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1, config=None): if config is None: config = Config() self.config = config unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity) def _makeResult(self): return TextTestResult(self.stream, self.descriptions, self.verbosity, self.config) def run(self, test): """Overrides to provide plugin hooks and defer all output to the test result class. """ wrapper = self.config.plugins.prepareTest(test) if wrapper is not None: test = wrapper # plugins can decorate or capture the output stream wrapped = self.config.plugins.setOutputStream(self.stream) if wrapped is not None: self.stream = wrapped result = self._makeResult() start = time.time() try: test(result) except KeyboardInterrupt: pass stop = time.time() result.printErrors() result.printSummary(start, stop) self.config.plugins.finalize(result) return result class TestProgram(unittest.TestProgram): """Collect and run tests, returning success or failure. The arguments to TestProgram() are the same as to :func:`main()` and :func:`run()`: * module: All tests are in this module (default: None) * defaultTest: Tests to load (default: '.') * argv: Command line arguments (default: None; sys.argv is read) * testRunner: Test runner instance (default: None) * testLoader: Test loader instance (default: None) * env: Environment; ignored if config is provided (default: None; os.environ is read) * config: :class:`nose.config.Config` instance (default: None) * suite: Suite or list of tests to run (default: None). Passing a suite or lists of tests will bypass all test discovery and loading. *ALSO NOTE* that if you pass a unittest.TestSuite instance as the suite, context fixtures at the class, module and package level will not be used, and many plugin hooks will not be called. If you want normal nose behavior, either pass a list of tests, or a fully-configured :class:`nose.suite.ContextSuite`. * exit: Exit after running tests and printing report (default: True) * plugins: List of plugins to use; ignored if config is provided (default: load plugins with DefaultPluginManager) * addplugins: List of **extra** plugins to use. Pass a list of plugin instances in this argument to make custom plugins available while still using the DefaultPluginManager. """ verbosity = 1 def __init__(self, module=None, defaultTest='.', argv=None, testRunner=None, testLoader=None, env=None, config=None, suite=None, exit=True, plugins=None, addplugins=None): if env is None: env = os.environ if config is None: config = self.makeConfig(env, plugins) if addplugins: config.plugins.addPlugins(extraplugins=addplugins) self.config = config self.suite = suite self.exit = exit extra_args = {} version = sys.version_info[0:2] if version >= (2,7) and version != (3,0): extra_args['exit'] = exit unittest.TestProgram.__init__( self, module=module, defaultTest=defaultTest, argv=argv, testRunner=testRunner, testLoader=testLoader, **extra_args) def getAllConfigFiles(self, env=None): env = env or {} if env.get('NOSE_IGNORE_CONFIG_FILES', False): return [] else: return all_config_files() def makeConfig(self, env, plugins=None): """Load a Config, pre-filled with user config files if any are found. """ cfg_files = self.getAllConfigFiles(env) if plugins: manager = PluginManager(plugins=plugins) else: manager = DefaultPluginManager() return Config( env=env, files=cfg_files, plugins=manager) def parseArgs(self, argv): """Parse argv and env and configure running environment. """ self.config.configure(argv, doc=self.usage()) log.debug("configured %s", self.config) # quick outs: version, plugins (optparse would have already # caught and exited on help) if self.config.options.version: from nose import __version__ sys.stdout = sys.__stdout__ print "%s version %s" % (os.path.basename(sys.argv[0]), __version__) sys.exit(0) if self.config.options.showPlugins: self.showPlugins() sys.exit(0) if self.testLoader is None: self.testLoader = defaultTestLoader(config=self.config) elif isclass(self.testLoader): self.testLoader = self.testLoader(config=self.config) plug_loader = self.config.plugins.prepareTestLoader(self.testLoader) if plug_loader is not None: self.testLoader = plug_loader log.debug("test loader is %s", self.testLoader) # FIXME if self.module is a string, add it to self.testNames? not sure if self.config.testNames: self.testNames = self.config.testNames else: self.testNames = tolist(self.defaultTest) log.debug('defaultTest %s', self.defaultTest) log.debug('Test names are %s', self.testNames) if self.config.workingDir is not None: os.chdir(self.config.workingDir) self.createTests() def createTests(self): """Create the tests to run. If a self.suite is set, then that suite will be used. Otherwise, tests will be loaded from the given test names (self.testNames) using the test loader. """ log.debug("createTests called with %s", self.suite) if self.suite is not None: # We were given an explicit suite to run. Make sure it's # loaded and wrapped correctly. self.test = self.testLoader.suiteClass(self.suite) else: self.test = self.testLoader.loadTestsFromNames(self.testNames) def runTests(self): """Run Tests. Returns true on success, false on failure, and sets self.success to the same value. """ log.debug("runTests called") if self.testRunner is None: self.testRunner = TextTestRunner(stream=self.config.stream, verbosity=self.config.verbosity, config=self.config) plug_runner = self.config.plugins.prepareTestRunner(self.testRunner) if plug_runner is not None: self.testRunner = plug_runner result = self.testRunner.run(self.test) self.success = result.wasSuccessful() if self.exit: sys.exit(not self.success) return self.success def showPlugins(self): """Print list of available plugins. """ import textwrap class DummyParser: def __init__(self): self.options = [] def add_option(self, *arg, **kw): self.options.append((arg, kw.pop('help', ''))) v = self.config.verbosity self.config.plugins.sort() for p in self.config.plugins: print "Plugin %s" % p.name if v >= 2: print " score: %s" % p.score print '\n'.join(textwrap.wrap(p.help().strip(), initial_indent=' ', subsequent_indent=' ')) if v >= 3: parser = DummyParser() p.addOptions(parser) if len(parser.options): print print " Options:" for opts, help in parser.options: print ' %s' % (', '.join(opts)) if help: print '\n'.join( textwrap.wrap(help.strip(), initial_indent=' ', subsequent_indent=' ')) print def usage(cls): import nose try: ld = nose.__loader__ text = ld.get_data(os.path.join( os.path.dirname(__file__), 'usage.txt')) except AttributeError: f = open(os.path.join( os.path.dirname(__file__), 'usage.txt'), 'r') try: text = f.read() finally: f.close() # Ensure that we return str, not bytes. if not isinstance(text, str): text = text.decode('utf-8') return text usage = classmethod(usage) # backwards compatibility run_exit = main = TestProgram def run(*arg, **kw): """Collect and run tests, returning success or failure. The arguments to `run()` are the same as to `main()`: * module: All tests are in this module (default: None) * defaultTest: Tests to load (default: '.') * argv: Command line arguments (default: None; sys.argv is read) * testRunner: Test runner instance (default: None) * testLoader: Test loader instance (default: None) * env: Environment; ignored if config is provided (default: None; os.environ is read) * config: :class:`nose.config.Config` instance (default: None) * suite: Suite or list of tests to run (default: None). Passing a suite or lists of tests will bypass all test discovery and loading. *ALSO NOTE* that if you pass a unittest.TestSuite instance as the suite, context fixtures at the class, module and package level will not be used, and many plugin hooks will not be called. If you want normal nose behavior, either pass a list of tests, or a fully-configured :class:`nose.suite.ContextSuite`. * plugins: List of plugins to use; ignored if config is provided (default: load plugins with DefaultPluginManager) * addplugins: List of **extra** plugins to use. Pass a list of plugin instances in this argument to make custom plugins available while still using the DefaultPluginManager. With the exception that the ``exit`` argument is always set to False. """ kw['exit'] = False return TestProgram(*arg, **kw).success def runmodule(name='__main__', **kw): """Collect and run tests in a single module only. Defaults to running tests in __main__. Additional arguments to TestProgram may be passed as keyword arguments. """ main(defaultTest=name, **kw) def collector(): """TestSuite replacement entry point. Use anywhere you might use a unittest.TestSuite. The collector will, by default, load options from all config files and execute loader.loadTestsFromNames() on the configured testNames, or '.' if no testNames are configured. """ # plugins that implement any of these methods are disabled, since # we don't control the test runner and won't be able to run them # finalize() is also not called, but plugins that use it aren't disabled, # because capture needs it. setuptools_incompat = ('report', 'prepareTest', 'prepareTestLoader', 'prepareTestRunner', 'setOutputStream') plugins = RestrictedPluginManager(exclude=setuptools_incompat) conf = Config(files=all_config_files(), plugins=plugins) conf.configure(argv=['collector']) loader = defaultTestLoader(conf) if conf.testNames: suite = loader.loadTestsFromNames(conf.testNames) else: suite = loader.loadTestsFromNames(('.',)) return FinalizingSuiteWrapper(suite, plugins.finalize) if __name__ == '__main__': main()
bsd-2-clause
silgon/rlpy
rlpy/Domains/RCCar.py
3
5073
"""RC-Car domain""" from rlpy.Tools import plt, bound, wrap, mpatches, id2vec import matplotlib as mpl from .Domain import Domain import numpy as np __author__ = "Alborz Geramifard" class RCCar(Domain): """ This is a simple simulation of Remote Controlled Car in a room with no obstacle. **STATE:** 4 continuous dimensions: * x, y: (center point on the line connecting the back wheels), * speed (S on the webpage) * heading (theta on the webpage) w.r.t. body frame. positive values => turning right, negative values => turning left **ACTIONS:** Two action dimensions: * accel [forward, coast, backward] * phi [turn left, straight, turn Right] This leads to 3 x 3 = 9 possible actions. **REWARD:** -1 per step, 100 at goal. **REFERENCE:** .. seealso:: http://planning.cs.uiuc.edu/node658.html """ actions_num = 9 state_space_dims = 4 continuous_dims = np.arange(state_space_dims) ROOM_WIDTH = 3 # in meters ROOM_HEIGHT = 2 # in meters XMIN = -ROOM_WIDTH / 2.0 XMAX = ROOM_WIDTH / 2.0 YMIN = -ROOM_HEIGHT / 2.0 YMAX = ROOM_HEIGHT / 2.0 ACCELERATION = .1 TURN_ANGLE = np.pi / 6 SPEEDMIN = -.3 SPEEDMAX = .3 HEADINGMIN = -np.pi HEADINGMAX = np.pi INIT_STATE = np.array([0.0, 0.0, 0.0, 0.0]) STEP_REWARD = -1 GOAL_REWARD = 0 GOAL = [.5, .5] GOAL_RADIUS = .1 actions = np.outer([-1, 0, 1], [-1, 0, 1]) discount_factor = .9 episodeCap = 10000 delta_t = .1 # time between steps CAR_LENGTH = .3 # L on the webpage CAR_WIDTH = .15 # The location of rear wheels if the car facing right with heading 0 REAR_WHEEL_RELATIVE_LOC = .05 # Used for visual stuff: domain_fig = None X_discretization = 20 Y_discretization = 20 SPEED_discretization = 5 HEADING_discretization = 3 ARROW_LENGTH = .2 car_fig = None def __init__(self, noise=0): self.statespace_limits = np.array( [[self.XMIN, self.XMAX], [self.YMIN, self.YMAX], [self.SPEEDMIN, self.SPEEDMAX], [self.HEADINGMIN, self.HEADINGMAX]]) self.Noise = noise super(RCCar, self).__init__() def step(self, a): x, y, speed, heading = self.state # Map a number between [0,8] to a pair. The first element is # acceleration direction. The second one is the indicator for the wheel acc, turn = id2vec(a, [3, 3]) acc -= 1 # Mapping acc to [-1, 0 1] turn -= 1 # Mapping turn to [-1, 0 1] # Calculate next state nx = x + speed * np.cos(heading) * self.delta_t ny = y + speed * np.sin(heading) * self.delta_t nspeed = speed + acc * self.ACCELERATION * self.delta_t nheading = heading + speed / self.CAR_LENGTH * \ np.tan(turn * self.TURN_ANGLE) * self.delta_t # Bound values nx = bound(nx, self.XMIN, self.XMAX) ny = bound(ny, self.YMIN, self.YMAX) nspeed = bound(nspeed, self.SPEEDMIN, self.SPEEDMAX) nheading = wrap(nheading, self.HEADINGMIN, self.HEADINGMAX) # Collision to wall => set the speed to zero if nx == self.XMIN or nx == self.XMAX or ny == self.YMIN or ny == self.YMAX: nspeed = 0 ns = np.array([nx, ny, nspeed, nheading]) self.state = ns.copy() terminal = self.isTerminal() r = self.GOAL_REWARD if terminal else self.STEP_REWARD return r, ns, terminal, self.possibleActions() def s0(self): self.state = self.INIT_STATE.copy() return self.state.copy(), self.isTerminal(), self.possibleActions() def isTerminal(self): return np.linalg.norm(self.state[0:2] - self.GOAL) < self.GOAL_RADIUS def showDomain(self, a): s = self.state # Plot the car x, y, speed, heading = s car_xmin = x - self.REAR_WHEEL_RELATIVE_LOC car_ymin = y - self.CAR_WIDTH / 2. if self.domain_fig is None: # Need to initialize the figure self.domain_fig = plt.figure() # Goal plt.gca( ).add_patch( plt.Circle( self.GOAL, radius=self.GOAL_RADIUS, color='g', alpha=.4)) plt.xlim([self.XMIN, self.XMAX]) plt.ylim([self.YMIN, self.YMAX]) plt.gca().set_aspect('1') # Car if self.car_fig is not None: plt.gca().patches.remove(self.car_fig) self.car_fig = mpatches.Rectangle( [car_xmin, car_ymin], self.CAR_LENGTH, self.CAR_WIDTH, alpha=.4) rotation = mpl.transforms.Affine2D().rotate_deg_around( x, y, heading * 180 / np.pi) + plt.gca().transData self.car_fig.set_transform(rotation) plt.gca().add_patch(self.car_fig) plt.draw()
bsd-3-clause
tortib/nzbToMedia
libs/unidecode/x086.py
252
4614
data = ( 'Tuo ', # 0x00 'Wu ', # 0x01 'Rui ', # 0x02 'Rui ', # 0x03 'Qi ', # 0x04 'Heng ', # 0x05 'Lu ', # 0x06 'Su ', # 0x07 'Tui ', # 0x08 'Mang ', # 0x09 'Yun ', # 0x0a 'Pin ', # 0x0b 'Yu ', # 0x0c 'Xun ', # 0x0d 'Ji ', # 0x0e 'Jiong ', # 0x0f 'Xian ', # 0x10 'Mo ', # 0x11 'Hagi ', # 0x12 'Su ', # 0x13 'Jiong ', # 0x14 '[?] ', # 0x15 'Nie ', # 0x16 'Bo ', # 0x17 'Rang ', # 0x18 'Yi ', # 0x19 'Xian ', # 0x1a 'Yu ', # 0x1b 'Ju ', # 0x1c 'Lian ', # 0x1d 'Lian ', # 0x1e 'Yin ', # 0x1f 'Qiang ', # 0x20 'Ying ', # 0x21 'Long ', # 0x22 'Tong ', # 0x23 'Wei ', # 0x24 'Yue ', # 0x25 'Ling ', # 0x26 'Qu ', # 0x27 'Yao ', # 0x28 'Fan ', # 0x29 'Mi ', # 0x2a 'Lan ', # 0x2b 'Kui ', # 0x2c 'Lan ', # 0x2d 'Ji ', # 0x2e 'Dang ', # 0x2f 'Katsura ', # 0x30 'Lei ', # 0x31 'Lei ', # 0x32 'Hua ', # 0x33 'Feng ', # 0x34 'Zhi ', # 0x35 'Wei ', # 0x36 'Kui ', # 0x37 'Zhan ', # 0x38 'Huai ', # 0x39 'Li ', # 0x3a 'Ji ', # 0x3b 'Mi ', # 0x3c 'Lei ', # 0x3d 'Huai ', # 0x3e 'Luo ', # 0x3f 'Ji ', # 0x40 'Kui ', # 0x41 'Lu ', # 0x42 'Jian ', # 0x43 'San ', # 0x44 '[?] ', # 0x45 'Lei ', # 0x46 'Quan ', # 0x47 'Xiao ', # 0x48 'Yi ', # 0x49 'Luan ', # 0x4a 'Men ', # 0x4b 'Bie ', # 0x4c 'Hu ', # 0x4d 'Hu ', # 0x4e 'Lu ', # 0x4f 'Nue ', # 0x50 'Lu ', # 0x51 'Si ', # 0x52 'Xiao ', # 0x53 'Qian ', # 0x54 'Chu ', # 0x55 'Hu ', # 0x56 'Xu ', # 0x57 'Cuo ', # 0x58 'Fu ', # 0x59 'Xu ', # 0x5a 'Xu ', # 0x5b 'Lu ', # 0x5c 'Hu ', # 0x5d 'Yu ', # 0x5e 'Hao ', # 0x5f 'Jiao ', # 0x60 'Ju ', # 0x61 'Guo ', # 0x62 'Bao ', # 0x63 'Yan ', # 0x64 'Zhan ', # 0x65 'Zhan ', # 0x66 'Kui ', # 0x67 'Ban ', # 0x68 'Xi ', # 0x69 'Shu ', # 0x6a 'Chong ', # 0x6b 'Qiu ', # 0x6c 'Diao ', # 0x6d 'Ji ', # 0x6e 'Qiu ', # 0x6f 'Cheng ', # 0x70 'Shi ', # 0x71 '[?] ', # 0x72 'Di ', # 0x73 'Zhe ', # 0x74 'She ', # 0x75 'Yu ', # 0x76 'Gan ', # 0x77 'Zi ', # 0x78 'Hong ', # 0x79 'Hui ', # 0x7a 'Meng ', # 0x7b 'Ge ', # 0x7c 'Sui ', # 0x7d 'Xia ', # 0x7e 'Chai ', # 0x7f 'Shi ', # 0x80 'Yi ', # 0x81 'Ma ', # 0x82 'Xiang ', # 0x83 'Fang ', # 0x84 'E ', # 0x85 'Pa ', # 0x86 'Chi ', # 0x87 'Qian ', # 0x88 'Wen ', # 0x89 'Wen ', # 0x8a 'Rui ', # 0x8b 'Bang ', # 0x8c 'Bi ', # 0x8d 'Yue ', # 0x8e 'Yue ', # 0x8f 'Jun ', # 0x90 'Qi ', # 0x91 'Ran ', # 0x92 'Yin ', # 0x93 'Qi ', # 0x94 'Tian ', # 0x95 'Yuan ', # 0x96 'Jue ', # 0x97 'Hui ', # 0x98 'Qin ', # 0x99 'Qi ', # 0x9a 'Zhong ', # 0x9b 'Ya ', # 0x9c 'Ci ', # 0x9d 'Mu ', # 0x9e 'Wang ', # 0x9f 'Fen ', # 0xa0 'Fen ', # 0xa1 'Hang ', # 0xa2 'Gong ', # 0xa3 'Zao ', # 0xa4 'Fu ', # 0xa5 'Ran ', # 0xa6 'Jie ', # 0xa7 'Fu ', # 0xa8 'Chi ', # 0xa9 'Dou ', # 0xaa 'Piao ', # 0xab 'Xian ', # 0xac 'Ni ', # 0xad 'Te ', # 0xae 'Qiu ', # 0xaf 'You ', # 0xb0 'Zha ', # 0xb1 'Ping ', # 0xb2 'Chi ', # 0xb3 'You ', # 0xb4 'He ', # 0xb5 'Han ', # 0xb6 'Ju ', # 0xb7 'Li ', # 0xb8 'Fu ', # 0xb9 'Ran ', # 0xba 'Zha ', # 0xbb 'Gou ', # 0xbc 'Pi ', # 0xbd 'Bo ', # 0xbe 'Xian ', # 0xbf 'Zhu ', # 0xc0 'Diao ', # 0xc1 'Bie ', # 0xc2 'Bing ', # 0xc3 'Gu ', # 0xc4 'Ran ', # 0xc5 'Qu ', # 0xc6 'She ', # 0xc7 'Tie ', # 0xc8 'Ling ', # 0xc9 'Gu ', # 0xca 'Dan ', # 0xcb 'Gu ', # 0xcc 'Ying ', # 0xcd 'Li ', # 0xce 'Cheng ', # 0xcf 'Qu ', # 0xd0 'Mou ', # 0xd1 'Ge ', # 0xd2 'Ci ', # 0xd3 'Hui ', # 0xd4 'Hui ', # 0xd5 'Mang ', # 0xd6 'Fu ', # 0xd7 'Yang ', # 0xd8 'Wa ', # 0xd9 'Lie ', # 0xda 'Zhu ', # 0xdb 'Yi ', # 0xdc 'Xian ', # 0xdd 'Kuo ', # 0xde 'Jiao ', # 0xdf 'Li ', # 0xe0 'Yi ', # 0xe1 'Ping ', # 0xe2 'Ji ', # 0xe3 'Ha ', # 0xe4 'She ', # 0xe5 'Yi ', # 0xe6 'Wang ', # 0xe7 'Mo ', # 0xe8 'Qiong ', # 0xe9 'Qie ', # 0xea 'Gui ', # 0xeb 'Gong ', # 0xec 'Zhi ', # 0xed 'Man ', # 0xee 'Ebi ', # 0xef 'Zhi ', # 0xf0 'Jia ', # 0xf1 'Rao ', # 0xf2 'Si ', # 0xf3 'Qi ', # 0xf4 'Xing ', # 0xf5 'Lie ', # 0xf6 'Qiu ', # 0xf7 'Shao ', # 0xf8 'Yong ', # 0xf9 'Jia ', # 0xfa 'Shui ', # 0xfb 'Che ', # 0xfc 'Bai ', # 0xfd 'E ', # 0xfe 'Han ', # 0xff )
gpl-3.0
numansiddique/contrail-controller
src/config/schema-transformer/ifmap_view.py
10
13474
#!/usr/bin/python # # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # import argparse import sys reload(sys) sys.setdefaultencoding('UTF8') import lxml.etree as et import StringIO import re import json from distutils.sysconfig import get_python_lib sys.path.append(get_python_lib() + '/vnc_cfg_api_server') from operator import itemgetter, attrgetter from vnc_api import vnc_api from vnc_cfg_api_server import gen from vnc_api.gen.resource_xsd import * from vnc_api.gen.resource_common import * from vnc_cfg_api_server.gen.vnc_ifmap_client_gen import * from vnc_api.gen.vnc_api_client_gen import * import pycassa from pycassa.system_manager import * # Global variables vnc = None dbg_outfile = None """ Input is list of tuple dictionary <type, name, value, prop, refs> type := project, domain ... value := dependent graph prop := Properties of this node refs := parenr->node reference meta data """ def mypretty(l, indent=0, verbose=0, outfile=sys.stdout): l = sorted(l, key=itemgetter('type')) prop_fmt = '\n' + ' ' * (indent + 1) ref_fmt = '\n' + ' ' * indent for i in l: """ Prepare property string""" propstr = '' propstr2 = '' if i['props']: propstr = [p['name'] for p in i['props']] propstr = ' (' + ', '.join(propstr) + ')' if verbose >= 2: show_list = [] for p in i['props']: if p['name'] not in vnc_viewer.skip: show_list.append(p) propstr2 = ['%s=%s' % (p['name'], p['value']) for p in show_list] propstr2 = '\n'.join(propstr2) propstr2 = propstr2.split('\n') propstr2 = prop_fmt.join(propstr2) outfile.write(' ' * indent + '%s = '\ % (i['type']) + str(i['name']) + propstr + '\n') """ Prepare reference string""" ref_str = [] if verbose >= 1 and i['refs']: ref_str = [r['value'] for r in i['refs']] ref_str = '\n'.join(ref_str) ref_str = ref_str.split('\n') ref_str = ref_fmt.join(ref_str) if len(ref_str) > 0: outfile.write(' ' * indent + ref_str + '\n') if len(propstr2) > 0: outfile.write(' ' * (indent + 1) + propstr2 + '\n') if len(i['value']) > 0: mypretty(i['value'], indent + 1, verbose, outfile) # end mypretty """ Find name in node list. Return the parent and subgraph for subsequent traversal. Otherwise return def_node (typically None) """ def find_node(name, node_list, def_node): # traverse thru list of dict for item in node_list: if name == item['name']: return (item, item['value']) return (def_node, def_node) def find_node_in_tree(fq_path, tree): path = fq_path.split(':') # Traverse until name is finished match, node = find_node('root', tree, tree) for name in path: match, n = find_node(name, node, None) if n is None: return None node = n return node # end find_node_in_tree def parse_config(soap_config): root = et.fromstring(soap_config) config = [] for r_i in root.findall('*/*/*/resultItem'): ids = r_i.findall('identity') ident1 = ids[0].get('name') try: ident2 = ids[1].get('name') except IndexError: ident2 = None metas = r_i.find('metadata') # details dbg_outfile.write('\n' + et.tostring(r_i) + '\n') dbg_outfile.write('ident1 = %s\n' % (ident1)) if ident2: dbg_outfile.write('ident2 = %s\n' % (ident2)) if metas is not None: dbg_outfile.write('metas = %s\n' % (et.tostring(metas))) if not re.match("^contrail:", ident1): continue res = re.search("^contrail:([^:]+):(.*:)*(.*)$", ident1) type1 = res.group(1) name1 = res.group(3) id1 = ident1.split(':') # strip contrail, type id1 = id1[2:] dbg_outfile.write('Ident1 type = %s, name = %s\n' % (type1, name1)) if ident2: res = re.search("^contrail:([^:]+):(.*:)*(.*)$", ident2) type2 = res.group(1) name2 = res.group(3) id2 = ident2.split(':') # strip contrail, type id2 = id2[2:] dbg_outfile.write('Ident2 type = %s, name = %s\n' % (type2, name2)) # Traverse until name is finished match, node = find_node('root', config, config) for name in id1: match, n = find_node(name, node, None) if n is None: node.append( {'type': type1, 'name': name1, 'value': [], 'props': [], 'refs': []}) match = node[-1] node = node[-1]['value'] break node = n node1 = node if ident2: match, n = find_node(name2, node1, None) if n is None: match = {'type': type2, 'name': name2, 'value': [], 'props': [], 'refs': []} node1.append(match) # attach property or reference info if available if metas is None: continue for meta in metas: meta_name = re.sub('{.*}', '', meta.tag) dbg_outfile.write('Handling meta = %s\n' % (meta_name)) if ident2: if meta_name in link_name_to_xsd_type: obj = eval(link_name_to_xsd_type[meta_name])() obj.build(meta) obj_json = json.dumps( obj, default=lambda o: dict( (k, v) for k, v in o.__dict__.iteritems()), indent=4) dbg_outfile.write( 'Attaching Reference %s to Id %s\n' % (meta_name, ident2)) dbg_outfile.write('JSON %s = %s\n' % (meta_name, obj_json)) match['refs'].append( {'name': '%s' % (meta_name), 'value': obj_json}) else: if meta_name in vnc.prop_name_to_xsd_type: obj = eval(vnc.prop_name_to_xsd_type[meta_name])() obj.build(meta) obj_json = json.dumps( obj, default=lambda o: dict( (k, v) for k, v in o.__dict__.iteritems()), indent=4) dbg_outfile.write( 'Attaching Property %s to Id %s\n' % (meta_name, ident1)) dbg_outfile.write('JSON %s = %s\n' % (meta_name, obj_json)) match['props'].append( {'name': '%s' % (meta_name), 'value': obj_json}) return config # end parse_config class IfmapClient(): def __init__(self, ifmap_srv_ip, ifmap_srv_port, uname, passwd): """ .. attention:: username/passwd from right place """ self._CONTRAIL_XSD = "http://www.contrailsystems.com/vnc_cfg.xsd" self._NAMESPACES = { 'a': 'http://www.w3.org/2003/05/soap-envelope', 'b': 'http://www.trustedcomputinggroup.org/2010/IFMAP/2', 'c': self._CONTRAIL_XSD } namespaces = { 'env': "http://www.w3.org/2003/05/soap-envelope", 'ifmap': "http://www.trustedcomputinggroup.org/2010/IFMAP/2", 'meta': "http://www.trustedcomputinggroup.org/" "2010/IFMAP-METADATA/2", 'contrail': self._CONTRAIL_XSD } mapclient = client(("%s" % (ifmap_srv_ip), "%s" % (ifmap_srv_port)), uname, passwd, namespaces) result = mapclient.call('newSession', NewSessionRequest()) mapclient.set_session_id(newSessionResult(result).get_session_id()) mapclient.set_publisher_id(newSessionResult(result).get_publisher_id()) self._mapclient = mapclient # end __init__ def _search(self, start_id, match_meta=None, result_meta=None, max_depth=1): # set ifmap search parmeters srch_params = {} srch_params['max-depth'] = str(max_depth) srch_params['max-size'] = '50000000' if match_meta is not None: srch_params['match-links'] = match_meta if result_meta is not None: # all => don't set result-filter, so server returns all id + meta if result_meta == "all": pass else: srch_params['result-filter'] = result_meta else: # default to return match_meta metadata types only srch_params['result-filter'] = match_meta mapclient = self._mapclient srch_req = SearchRequest(mapclient.get_session_id(), start_id, search_parameters=srch_params ) result = mapclient.call('search', srch_req) return result # end _search def ifmap_read(self, ifmap_id, srch_meta, result_meta, field_names=None): start_id = str( Identity(name=ifmap_id, type='other', other_type='extended')) srch_result = self._search( start_id, srch_meta, result_meta, max_depth=10) return srch_result # end ifmap_read # end class IfmapClient class VncViewer(): def parse_args(self): # Eg. python vnc_ifmap_view.py 192.168.1.17 8443 test2 test2 parser = argparse.ArgumentParser( description="Display IFMAP configuration") parser.add_argument( 'ifmap_server_ip', help="IP address of ifmap server") parser.add_argument('ifmap_server_port', help="Port of ifmap server") parser.add_argument( 'ifmap_username', help="Username known to ifmap server") parser.add_argument( 'ifmap_password', help="Password known to ifmap server") parser.add_argument('-v', type=int, default=0, choices=range(0, 3), help="Turn verbosity on. Default is 0") parser.add_argument('-f', '--format', default='text', choices=['text','xml'], help="Output format. Default is text/human-readable") parser.add_argument('-o', '--outfile', default=sys.stdout, type=argparse.FileType('w'), help="Output file to write to. Default is stdout") """ parser.add_argument('-n', '--node', default=None, help = "Start node (fully qualified name such as default-domain:admin:vn2") parser.add_argument('-s', '--skip', action='append', help = "Skip property (such as id-perms)") """ self._args = parser.parse_args() self.verbose = self._args.v """ self.start_node = self._args.node self.skip = self._args.skip """ self.start_node = None self.skip = ['id-perms'] print 'MAP server connection = %s:%s'\ % (self._args.ifmap_server_ip, self._args.ifmap_server_port) print 'MAP server credentials = %s:%s'\ % (self._args.ifmap_username, self._args.ifmap_password) print 'Start node = %s' % (self.start_node) print 'Skip List = %s' % (self.skip) print 'Verbose = %s' % (self.verbose) print '' # end parse_args def db_connect(self): ifmap_ip = self._args.ifmap_server_ip ifmap_port = self._args.ifmap_server_port user = self._args.ifmap_username passwd = self._args.ifmap_password # ifmap interface db_conn = IfmapClient(ifmap_ip, ifmap_port, user, passwd) self._db_conn = db_conn # end db_connect def main(): vnc_viewer = VncViewer() vnc_viewer.parse_args() vnc_viewer.db_connect() #vnc = VncApi('admin', 'contrail123', 'admin', '127.0.0.1', '8082') global vnc global dbg_outfile vnc = VncApiClientGen(obj_serializer=None) dbg_outfile = file("debug.txt", "w") """ sample search metas srch_meta = 'contrail:config-root-domain' (retunn only domains) srch_meta = ' or '.join(['contrail:config-root-domain', 'contrail:config-root-virtual-router']) (domain or virtual-router) srch_meta = 'contrail:config-root-domain or contrail:config-root-virtual-router' (same as above) srch_meta = 'contrail:domain-project' (search all projects) srch_meta = None (search everything) """ srch_meta = None result_meta = 'all' soap_result = vnc_viewer._db_conn.ifmap_read( 'contrail:config-root:root', srch_meta, result_meta) if vnc_viewer._args.format == 'xml': soap_doc = et.fromstring(soap_result) vnc_viewer._args.outfile.write(et.tostring(soap_doc, pretty_print=True)) # we are done return config = parse_config(soap_result) if vnc_viewer.start_node is None: node = config[0]['value'] else: node = find_node_in_tree(vnc_viewer.start_node, config) mypretty(node, verbose=vnc_viewer.verbose, outfile=vnc_viewer._args.outfile) if __name__ == '__main__': main()
apache-2.0
Seldaiendil/meyeOS
devtools/qooxdoo-1.5-sdk/tool/bin/ecmalint.py
1
17133
#!/usr/bin/env python # encoding: utf-8 ################################################################################ # # qooxdoo - the new era of web development # # http://qooxdoo.org # # Copyright: # 2006-2010 1&1 Internet AG, Germany, http://www.1und1.de # # License: # LGPL: http://www.gnu.org/licenses/lgpl.html # EPL: http://www.eclipse.org/org/documents/epl-v10.php # See the LICENSE file in the project's top-level directory for details. # # Authors: # * Fabian Jakobs (fjakobs) # ################################################################################ import re import os import sys import qxenviron from optparse import OptionParser from ecmascript.frontend import treegenerator from ecmascript.frontend import tokenizer from ecmascript.frontend import treeutil from ecmascript.frontend import tree from ecmascript.frontend import lang from ecmascript.frontend import comment from ecmascript.frontend.Script import Script from ecmascript.frontend.Scope import Scope from misc import filetool class ConsoleLogger: def __init__(self): pass def log(self, filename, row, column, msg): print """%s (%s,%s): %s""" % (filename, row, column, msg.encode("ascii", "replace")) class Lint: def __init__(self, filename, logger=None): self.filename = filename content = filetool.read(filename) self.tree = treegenerator.createSyntaxTree(tokenizer.parseStream(content)) self.script = Script(self.tree, self.filename) if not logger: self.logger = ConsoleLogger() else: self.logger = logger def log(self, node, msg): (row, column) = treeutil.getLineAndColumnFromSyntaxItem(node) self.logger.log(self.filename, row, column, msg) def checkRequiredBlocks(self): for node in treeutil.nodeIterator(self.tree, "loop"): block = treeutil.selectNode(node, "statement/block") if not block: self.log(node, "The statement of loops and conditions should be enclosed by a block in braces '{}'") for node in treeutil.nodeIterator(self.tree, "elseStatement"): block = treeutil.selectNode(node, "block") if not block: block = treeutil.selectNode(node, "loop[@loopType='IF']") if not block: self.log(node, "The statement of loops and conditions should be enclosed by a block in braces '{}'") def checkMaps(self): for node in treeutil.nodeIterator(self.tree, "map"): knownkeys = {} if node.hasChildren(): for child in node.children: if child.type == "keyvalue": key = child.get("key") if key in knownkeys: self.log(child, "Map key '%s' redefined." % key) else: knownkeys[key] = child def checkFields(self): def getVariables(): # get all variable nodes from 'members' and (pot.) 'construct' variables = [] if "members" in classMap: variables.extend([node for node in treeutil.nodeIterator(classMap["members"], ["variable"])]) if "construct" in classMap: variables.extend([node for node in treeutil.nodeIterator(classMap["construct"], ["variable"])]) return variables def checkPrivate(allVars): privateElement = re.compile(r'\b__') def findPrivate(allVars): variables = [] for node in allVars: fullName, isComplete = treeutil.assembleVariable(node) if privateElement.search(fullName): variables.append(node) return variables def isLocalPrivate(var, fullName): allIdentifier = fullName.split('.') first = second = None if len(allIdentifier) > 0: first = allIdentifier[0] if len(allIdentifier) > 1: second = allIdentifier[1] return (first and (first == "this" or first == "that") and second and privateElement.match(second)) variables = findPrivate(allVars) for var in variables: fullName = treeutil.assembleVariable(var)[0] if isLocalPrivate(var, fullName) and fullName.split('.')[1] not in restricted: # local privates are ok, as long as they are declared self.log(var, "Undeclared private data field '%s'. You should list this field in the members section." % fullName) return def checkProtected(allVars): protectedElement = re.compile(r'\b_[^_]') def findProtected(allVars): variables = [] for node in allVars: # only check protected in lval position if (node.hasParent() and node.parent.type == "left" and node.parent.hasParent() and node.parent.parent.type == "assignment" and protectedElement.search(treeutil.assembleVariable(node)[0])): variables.append(node) return variables def protectedIsLastVarChild(var): lastChild = var.getLastChild(ignoreComments=True) # like "this.a.b" -> b if lastChild.type != "identifier": # rules out this.a._prot[0] which isn't a call anyway return False name = treeutil.selectNode(lastChild, "@name") if name and protectedElement.match(name): return True else: return False variables = findProtected(allVars) for var in variables: # check call with protected "..._protected()..." #if ( # protectedIsLastVarChild(var) and # like "this.a.b._protected()", not "this.a._protected.b()" # var.hasParent() and var.parent.type == "operand" and # parent is "operand" # var.parent.hasParent() and var.parent.parent.type == "call" # grandparent is "call" # ): # it's ok as method call # pass #else: #self.log(var, "Protected data field in '%s'. Protected data fields are deprecated. Better use private fields in combination with getter and setter methods." % treeutil.assembleVariable(var)[0]) pass # protected data fields are ok return def checkImplicit(allVars): def hasUndeclaredMember(fullName): allIdentifier = fullName.split('.') first = second = None if len(allIdentifier) > 0: first = allIdentifier[0] if len(allIdentifier) > 1: second = allIdentifier[1] return (first and (first == "this" or first == "that") and second and second not in restricted) # <- this is bogus, too narrow for var in allVars: fullName = treeutil.assembleVariable(var)[0] if hasUndeclaredMember(fullName): self.log(var, "Undeclared local data field in '%s'! You should list this field in the member section." % fullName) return def checkAll(): def findVariables(rootNode): variables = [] for node in treeutil.nodeIterator(rootNode, ["assignment", "call"]): if node.type == "assignment": variables.append(node.getChild("left")) elif node.type == "call": variables.append(node.getChild("operand")) return variables variables = findVariables(classMap["members"]) if "construct" in classMap: variables.extend(findVariables(classMap["construct"])) for node in variables: this = treeutil.selectNode(node, "variable/identifier[1]/@name") if this != "this": continue field = treeutil.selectNode(node, "variable/identifier[2]/@name") if field is None: continue if field[0] != "_": continue elif field[1] == "_": prot = "private" else: prot = "protected" if prot == "protected": #self.log(node, "Protected data field '%s'. Protected fields are deprecated. Better use private fields in combination with getter and setter methods." % field) pass # protected data fields are ok elif not field in restricted: self.log(node, "Implicit declaration of %s field '%s'. You should list this field in the members section." % (prot, field)) classMap = self._getClassMap() #print self.tree.toXml() if len(classMap) == 0: return restricted = [key for key in self._getMembersMap() if key.startswith("_")] allVars = getVariables() #checkImplicit(allVars) # this check is overgenerating, doesn't honor all members/statics, nor inherited checkPrivate(allVars) checkProtected(allVars) #checkAll() def checkReferenceFields(self): members = self._getMembersMap() for name in members: valueNode = members[name].children[0] if valueNode.type in ["map", "instantiation", "array"]: if self._shouldPrintReferenceFieldWarning(valueNode, name): self.log( valueNode, ("Data field '%s' has a reference value. " + "If data fields are initialized in the members map with " + "reference values like arrays or maps they will be shared " + "between all instances of the class. Usually it is better " + "to set the value to 'null' and initialize it in the constructor") % name ) def _getClassMap(self): define = treeutil.findQxDefine(self.tree) if not define: return {} classMapNode = treeutil.selectNode(define, "params/2") if classMapNode is None: return {} classMap = treeutil.mapNodeToMap(classMapNode) return classMap def _getMembersMap(self): classMap = self._getClassMap() if not "members" in classMap: return {} members = treeutil.mapNodeToMap(classMap["members"].children[0]) return members def checkUnusedVariables(self): for scope in self.script.iterScopes(): if scope.type != Scope.EXCEPTION: for var in scope.variables: if len(var.uses) == 0: for node in var.nodes: if self._shouldPrintUnusedWarning(node, var.name): self.log(node, "Unused identifier '%s'" % var.name) def checkMultiDefinedVariables(self): for scope in self.script.iterScopes(): if scope.type != Scope.EXCEPTION: for var in scope.variables: if len(var.nodes) > 1: for node in var.nodes: self.log(node, "Multiply declared identifier '%s'" % var.name) DEPRECATED_IDENTIFIER = set([ "alert", "confirm", "debugger", "eval" ]) def isBadGlobal(self, identifier): return identifier in Lint.DEPRECATED_IDENTIFIER KNOWN_IDENTIFIER = set(lang.GLOBALS) def isGoodGlobal(self, identifier): return identifier in Lint.KNOWN_IDENTIFIER def checkUndefinedVariables(self, globals): # check whether this is a qooxdoo class and extract the top level namespace define = treeutil.findQxDefine(self.tree) if define: className = treeutil.selectNode(define, "params/1").get("value") globals.append(className.split(".")[0]) globalScope = self.script.getGlobalScope() for scope in self.script.iterScopes(): for use in scope.uses: if use.name in globals: continue if not use.definition: if self.isBadGlobal(use.name) and self._shouldPrintDeprecatedWarning(use.node, use.name): self.log(use.node, "Use of deprecated global identifier '%s'" % use.name) elif not self.isBadGlobal(use.name) and not self.isGoodGlobal(use.name) and self._shouldPrintUndefinedWarning(use.node, use.name): self.log(use.node, "Use of undefined or global identifier '%s'" % use.name) elif use.definition.scope == globalScope and self._shouldPrintUndefinedWarning(use.node, use.name): self.log(use.node, "Use of global identifier '%s'" % use.name) def _shouldPrintDeprecatedWarning(self, node, name): return self._shouldPrintVariableWarning(node, "ignoreDeprecated", name) def _shouldPrintUndefinedWarning(self, node, name): return self._shouldPrintVariableWarning(node, "ignoreUndefined", name) def _shouldPrintUnusedWarning(self, node, name): return self._shouldPrintVariableWarning(node, "ignoreUnused", name) def _shouldPrintReferenceFieldWarning(self, node, name): return self._shouldPrintVariableWarning(node, "ignoreReferenceField", name) def _shouldPrintVariableWarning(self, node, docCommand, variableName): comments = comment.findComment(node) if comments is None: return True lintAttribs = [x for x in comments if x["category"] == "lint"] unused_re = re.compile("<p>\s*%s\s*\(\s*((?:[\w\$]+)\s*(?:,\s*(?:[\w\$]+)\s*)*)\)" % docCommand) for attrib in lintAttribs: match = unused_re.match(attrib["text"]) if match: variables = [var.strip() for var in match.group(1).split(",")] return not variableName in variables return True def main(argv=None): if argv is None: argv = sys.argv parser = OptionParser(description="Checks ECMAScript/JavaScript files for common errors.") parser.add_option( "--action", "-a", dest="actions", metavar="ACTION", choices=["ALL", "undefined_variables", "unused_variables", "multidefined_variables", "maps", "blocks", "fields"], action="append", default=[], help="""Performs the given checks on the input files. This parameter may be supplied multiple times. Valid arguments are: "ALL" (default): Perform all checks "undefined_variables": Look for identifier, which are referenced in the global scope. This action can find misspelled identifier and missing 'var' statements. You can use the '-g' flag to add valid global identifiers. "unused_variables": Look for identifier, which are defined but never used. "multidefined_variables": Look for identifier, which are defined multiple times. "blocks" : Look for single statments in bodies of if's and loops that are not enclosed by braces. "fields" : Look for class attributes, checking definedness, privates and protected fields. "maps": Look for duplicate keys in map declarations. """ ) parser.add_option( "-g", dest="globals", help="Add an allowed global identifier GLOBAL", metavar="GLOBAL", type="string", action="append" ) (options, args) = parser.parse_args(argv) if len(args) == 1: parser.print_help() sys.exit(1) if options.globals: globals = options.globals else: globals = [] checkAll = "ALL" in options.actions or len(options.actions) == 0 for filename in args[1:]: lint = Lint(filename) if checkAll or "undefined_variables" in options.actions: lint.checkUndefinedVariables(globals) if checkAll or "unused_variables" in options.actions: lint.checkUnusedVariables() if "multidefined_variables" in options.actions: lint.checkMultiDefinedVariables() if checkAll or "maps" in options.actions: lint.checkMaps() if checkAll or "blocks" in options.actions: lint.checkRequiredBlocks() if checkAll or "fields" in options.actions: lint.checkFields() lint.checkReferenceFields() if __name__ == "__main__": rc = main() sys.exit(rc)
agpl-3.0
jcai19/smm_gem5
util/minorview/view.py
55
18864
# Copyright (c) 2013 ARM Limited # All rights reserved # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Andrew Bardsley import pygtk pygtk.require('2.0') import gtk import gobject import cairo import re from point import Point import parse import colours import model from model import Id, BlobModel, BlobDataSelect, special_state_chars import blobs class BlobView(object): """The canvas view of the pipeline""" def __init__(self, model): # A unit blob will appear at size blobSize inside a space of # size pitch. self.blobSize = Point(45.0, 45.0) self.pitch = Point(60.0, 60.0) self.origin = Point(50.0, 50.0) # Some common line definitions to cut down on arbitrary # set_line_widths self.thickLineWidth = 10.0 self.thinLineWidth = 4.0 self.midLineWidth = 6.0 # The scale from the units of pitch to device units (nominally # pixels for 1.0 to 1.0 self.masterScale = Point(1.0,1.0) self.model = model self.fillColour = colours.emptySlotColour self.timeIndex = 0 self.time = 0 self.positions = [] self.controlbar = None # The sequence number selector state self.dataSelect = BlobDataSelect() # Offset of this view's time from self.time used for miniviews # This is actually an offset of the index into the array of times # seen in the event file) self.timeOffset = 0 # Maximum view size for initial window mapping self.initialHeight = 600.0 # Overlays are speech bubbles explaining blob data self.overlays = [] self.da = gtk.DrawingArea() def draw(arg1, arg2): self.redraw() self.da.connect('expose_event', draw) # Handy offsets from the blob size self.blobIndent = (self.pitch - self.blobSize).scale(0.5) self.blobIndentFactor = self.blobIndent / self.pitch def add_control_bar(self, controlbar): """Add a BlobController to this view""" self.controlbar = controlbar def draw_to_png(self, filename): """Draw the view to a PNG file""" surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, self.da.get_allocation().width, self.da.get_allocation().height) cr = gtk.gdk.CairoContext(cairo.Context(surface)) self.draw_to_cr(cr) surface.write_to_png(filename) def draw_to_cr(self, cr): """Draw to a given CairoContext""" cr.set_source_color(colours.backgroundColour) cr.set_line_width(self.thickLineWidth) cr.paint() cr.save() cr.scale(*self.masterScale.to_pair()) cr.translate(*self.origin.to_pair()) positions = [] # {} # Draw each blob for blob in self.model.blobs: blob_event = self.model.find_unit_event_by_time( blob.unit, self.time) cr.save() pos = blob.render(cr, self, blob_event, self.dataSelect, self.time) cr.restore() if pos is not None: (centre, size) = pos positions.append((blob, centre, size)) # Draw all the overlays over the top for overlay in self.overlays: overlay.show(cr) cr.restore() return positions def redraw(self): """Redraw the whole view""" buffer = cairo.ImageSurface( cairo.FORMAT_ARGB32, self.da.get_allocation().width, self.da.get_allocation().height) cr = gtk.gdk.CairoContext(cairo.Context(buffer)) positions = self.draw_to_cr(cr) # Assume that blobs are in order for depth so we want to # hit the frontmost blob first if we search by position positions.reverse() self.positions = positions # Paint the drawn buffer onto the DrawingArea dacr = self.da.window.cairo_create() dacr.set_source_surface(buffer, 0.0, 0.0) dacr.paint() buffer.finish() def set_time_index(self, time): """Set the time index for the view. A time index is an index into the model's times array of seen event times""" self.timeIndex = time + self.timeOffset if len(self.model.times) != 0: if self.timeIndex >= len(self.model.times): self.time = self.model.times[len(self.model.times) - 1] else: self.time = self.model.times[self.timeIndex] else: self.time = 0 def get_pic_size(self): """Return the size of ASCII-art picture of the pipeline scaled by the blob pitch""" return (self.origin + self.pitch * (self.model.picSize + Point(1.0,1.0))) def set_da_size(self): """Set the DrawingArea size after scaling""" self.da.set_size_request(10 , int(self.initialHeight)) class BlobController(object): """The controller bar for the viewer""" def __init__(self, model, view, defaultEventFile="", defaultPictureFile=""): self.model = model self.view = view self.playTimer = None self.filenameEntry = gtk.Entry() self.filenameEntry.set_text(defaultEventFile) self.pictureEntry = gtk.Entry() self.pictureEntry.set_text(defaultPictureFile) self.timeEntry = None self.defaultEventFile = defaultEventFile self.startTime = None self.endTime = None self.otherViews = [] def make_bar(elems): box = gtk.HBox(homogeneous=False, spacing=2) box.set_border_width(2) for widget, signal, handler in elems: if signal is not None: widget.connect(signal, handler) box.pack_start(widget, False, True, 0) return box self.timeEntry = gtk.Entry() t = gtk.ToggleButton('T') t.set_active(False) s = gtk.ToggleButton('S') s.set_active(True) p = gtk.ToggleButton('P') p.set_active(True) l = gtk.ToggleButton('L') l.set_active(True) f = gtk.ToggleButton('F') f.set_active(True) e = gtk.ToggleButton('E') e.set_active(True) # Should really generate this from above self.view.dataSelect.ids = set("SPLFE") self.bar = gtk.VBox() self.bar.set_homogeneous(False) row1 = make_bar([ (gtk.Button('Start'), 'clicked', self.time_start), (gtk.Button('End'), 'clicked', self.time_end), (gtk.Button('Back'), 'clicked', self.time_back), (gtk.Button('Forward'), 'clicked', self.time_forward), (gtk.Button('Play'), 'clicked', self.time_play), (gtk.Button('Stop'), 'clicked', self.time_stop), (self.timeEntry, 'activate', self.time_set), (gtk.Label('Visible ids:'), None, None), (t, 'clicked', self.toggle_id('T')), (gtk.Label('/'), None, None), (s, 'clicked', self.toggle_id('S')), (gtk.Label('.'), None, None), (p, 'clicked', self.toggle_id('P')), (gtk.Label('/'), None, None), (l, 'clicked', self.toggle_id('L')), (gtk.Label('/'), None, None), (f, 'clicked', self.toggle_id('F')), (gtk.Label('.'), None, None), (e, 'clicked', self.toggle_id('E')), (self.filenameEntry, 'activate', self.load_events), (gtk.Button('Reload'), 'clicked', self.load_events) ]) self.bar.pack_start(row1, False, True, 0) self.set_time_index(0) def toggle_id(self, id): """One of the sequence number selector buttons has been toggled""" def toggle(button): if button.get_active(): self.view.dataSelect.ids.add(id) else: self.view.dataSelect.ids.discard(id) # Always leave one thing visible if len(self.view.dataSelect.ids) == 0: self.view.dataSelect.ids.add(id) button.set_active(True) self.view.redraw() return toggle def set_time_index(self, time): """Set the time index in the view""" self.view.set_time_index(time) for view in self.otherViews: view.set_time_index(time) view.redraw() self.timeEntry.set_text(str(self.view.time)) def time_start(self, button): """Start pressed""" self.set_time_index(0) self.view.redraw() def time_end(self, button): """End pressed""" self.set_time_index(len(self.model.times) - 1) self.view.redraw() def time_forward(self, button): """Step forward pressed""" self.set_time_index(min(self.view.timeIndex + 1, len(self.model.times) - 1)) self.view.redraw() gtk.gdk.flush() def time_back(self, button): """Step back pressed""" self.set_time_index(max(self.view.timeIndex - 1, 0)) self.view.redraw() def time_set(self, entry): """Time dialogue changed. Need to find a suitable time <= the entry's time""" newTime = self.model.find_time_index(int(entry.get_text())) self.set_time_index(newTime) self.view.redraw() def time_step(self): """Time step while playing""" if not self.playTimer \ or self.view.timeIndex == len(self.model.times) - 1: self.time_stop(None) return False else: self.time_forward(None) return True def time_play(self, play): """Automatically advance time every 100 ms""" if not self.playTimer: self.playTimer = gobject.timeout_add(100, self.time_step) def time_stop(self, play): """Stop play pressed""" if self.playTimer: gobject.source_remove(self.playTimer) self.playTimer = None def load_events(self, button): """Reload events file""" self.model.load_events(self.filenameEntry.get_text(), startTime=self.startTime, endTime=self.endTime) self.set_time_index(min(len(self.model.times) - 1, self.view.timeIndex)) self.view.redraw() class Overlay(object): """An Overlay is a speech bubble explaining the data in a blob""" def __init__(self, model, view, point, blob): self.model = model self.view = view self.point = point self.blob = blob def find_event(self): """Find the event for a changing time and a fixed blob""" return self.model.find_unit_event_by_time(self.blob.unit, self.view.time) def show(self, cr): """Draw the overlay""" event = self.find_event() if event is None: return insts = event.find_ided_objects(self.model, self.blob.picChar, False) cr.set_line_width(self.view.thinLineWidth) cr.translate(*(Point(0.0,0.0) - self.view.origin).to_pair()) cr.scale(*(Point(1.0,1.0) / self.view.masterScale).to_pair()) # Get formatted data from the insts to format into a table lines = list(inst.table_line() for inst in insts) text_size = 10.0 cr.set_font_size(text_size) def text_width(str): xb, yb, width, height, dx, dy = cr.text_extents(str) return width # Find the maximum number of columns and the widths of each column num_columns = 0 for line in lines: num_columns = max(num_columns, len(line)) widths = [0] * num_columns for line in lines: for i in xrange(0, len(line)): widths[i] = max(widths[i], text_width(line[i])) # Calculate the size of the speech bubble column_gap = 1 * text_size id_width = 6 * text_size total_width = sum(widths) + id_width + column_gap * (num_columns + 1) gap_step = Point(1.0, 0.0).scale(column_gap) text_point = self.point text_step = Point(0.0, text_size) size = Point(total_width, text_size * len(insts)) # Draw the speech bubble blobs.speech_bubble(cr, self.point, size, text_size) cr.set_source_color(colours.backgroundColour) cr.fill_preserve() cr.set_source_color(colours.black) cr.stroke() text_point += Point(1.0,1.0).scale(2.0 * text_size) id_size = Point(id_width, text_size) # Draw the rows in the table for i in xrange(0, len(insts)): row_point = text_point inst = insts[i] line = lines[i] blobs.striped_box(cr, row_point + id_size.scale(0.5), id_size, inst.id.to_striped_block(self.view.dataSelect)) cr.set_source_color(colours.black) row_point += Point(1.0, 0.0).scale(id_width) row_point += text_step # Draw the columns of each row for j in xrange(0, len(line)): row_point += gap_step cr.move_to(*row_point.to_pair()) cr.show_text(line[j]) row_point += Point(1.0, 0.0).scale(widths[j]) text_point += text_step class BlobWindow(object): """The top-level window and its mouse control""" def __init__(self, model, view, controller): self.model = model self.view = view self.controller = controller self.controlbar = None self.window = None self.miniViewCount = 0 def add_control_bar(self, controlbar): self.controlbar = controlbar def show_window(self): self.window = gtk.Window() self.vbox = gtk.VBox() self.vbox.set_homogeneous(False) if self.controlbar: self.vbox.pack_start(self.controlbar, False, True, 0) self.vbox.add(self.view.da) if self.miniViewCount > 0: self.miniViews = [] self.miniViewHBox = gtk.HBox(homogeneous=True, spacing=2) # Draw mini views for i in xrange(1, self.miniViewCount + 1): miniView = BlobView(self.model) miniView.set_time_index(0) miniView.masterScale = Point(0.1, 0.1) miniView.set_da_size() miniView.timeOffset = i + 1 self.miniViews.append(miniView) self.miniViewHBox.pack_start(miniView.da, False, True, 0) self.controller.otherViews = self.miniViews self.vbox.add(self.miniViewHBox) self.window.add(self.vbox) def show_event(picChar, event): print '**** Comments for', event.unit, \ 'at time', self.view.time for name, value in event.pairs.iteritems(): print name, '=', value for comment in event.comments: print comment if picChar in event.visuals: # blocks = event.visuals[picChar].elems() print '**** Colour data' objs = event.find_ided_objects(self.model, picChar, True) for obj in objs: print ' '.join(obj.table_line()) def clicked_da(da, b): point = Point(b.x, b.y) overlay = None for blob, centre, size in self.view.positions: if point.is_within_box((centre, size)): event = self.model.find_unit_event_by_time(blob.unit, self.view.time) if event is not None: if overlay is None: overlay = Overlay(self.model, self.view, point, blob) show_event(blob.picChar, event) if overlay is not None: self.view.overlays = [overlay] else: self.view.overlays = [] self.view.redraw() # Set initial size and event callbacks self.view.set_da_size() self.view.da.add_events(gtk.gdk.BUTTON_PRESS_MASK) self.view.da.connect('button-press-event', clicked_da) self.window.connect('destroy', lambda(widget): gtk.main_quit()) def resize(window, event): """Resize DrawingArea to match new window size""" size = Point(float(event.width), float(event.height)) proportion = size / self.view.get_pic_size() # Preserve aspect ratio daScale = min(proportion.x, proportion.y) self.view.masterScale = Point(daScale, daScale) self.view.overlays = [] self.view.da.connect('configure-event', resize) self.window.show_all()
bsd-3-clause
davidcox/genson
genson/__init__.py
1
5996
from parser import GENSONParser from internal_ops import GenSONFunction from internal_ops import GenSONOperand from internal_ops import lazy from internal_ops import lazyinfo from internal_ops import LazyCall from internal_ops import literal from internal_ops import register_lazy from references import ref import functions from functions import ParameterGenerator from util import * import copy from collections import OrderedDict class JSONGenerator: def __init__(self, genson_dict): self.genson_dict = genson_dict self.generators = [] self.find_generators(genson_dict) self.first_run = True def find_generators(self, d): if isdict(d): vals = d.values() elif isiterable(d): vals = d else: raise TypeError('invalid generator document', d) for v in vals: if isinstance(v, ParameterGenerator): self.generators.append(v) if isdict(v) or isiterable(v): self.find_generators(v) def __iter__(self): return self def advance_generator_stack(self, cursor=0): if cursor >= len(self.generators): return False if self.generators[cursor].advance(): return True else: self.generators[cursor].reset() return self.advance_generator_stack(cursor + 1) def next(self): d = copy.deepcopy(self.genson_dict) if self.first_run: self.first_run = False return resolve(d) if self.advance_generator_stack(): return resolve(d) else: self.first_run = True raise StopIteration() def reset(self): for g in self.generators: g.reset() # dictionary support def __getitem__(self, key): return self.genson_dict[key] def keys(self): return self.genson_dict.keys() def load(io): s = "\n".join(io.readlines()) return loads(s) def loads(genson_string): parser = GENSONParser() genson_dict = parser.parse_string(genson_string) return JSONGenerator(genson_dict) def dumps(generator, pretty_print=False): if isdict(generator): return genson_dumps(generator, pretty_print) elif hasattr(generator, 'genson_dict'): return genson_dumps(generator.genson_dict, pretty_print) else: return genson_dumps(generator, pretty_print) # Currently not used def node_eval(obj, memo): # -- dictionary containers if isinstance(obj, (dict, OrderedDict)): # XXX: this will evaluate in undefined order for dicts waiting_on = [v for v in obj.values() if id(v) not in memo] if not waiting_on: memo[id(obj)] = dict([(k, memo[id(v)]) for k, v in obj.items()]) # -- callable nodes elif isinstance(obj, GenSONFunction): # XXX: this will evaluate in undefined order for kwargs inputs = list(obj.args) + obj.kwargs.values() waiting_on = [v for v in inputs if id(v) not in memo] if not waiting_on: args = [memo[id(v)] for v in obj.args] kwargs = dict([(k, memo[id(v)]) for k, v in obj.kwargs.items()]) memo[id(obj)] = obj.fun(*args, **kwargs) # -- iterable containers elif isinstance(obj, (list, tuple)): waiting_on = [v for v in obj if id(v) not in memo] if not waiting_on: memo[id(obj)] = type(obj)([memo[id(v)] for v in obj]) # -- types that pass-through elif isinstance(obj, (int, float, str, np.ndarray)): waiting_on = [] memo[id(obj)] = obj # -- literals that pass-through elif obj in (None,): waiting_on = [] memo[id(obj)] = obj # -- anything else else: raise NotImplementedError(obj) if waiting_on: return [obj] + waiting_on else: return waiting_on STACK_LIMIT = 10000 # Currently not used def rec_eval(todo, memo): """ Returns nodes required by this one. Updates the memo by side effect. Returning [] means this node has been computed and the value is available as memo[id(node)] """ while todo: if len(todo) > STACK_LIMIT: raise RuntimeError('Probably infinite loop in document') node = todo.pop() if id(node) not in memo: todo.extend(node_eval(node, memo)) ARGS_KEY = '__args__' KWARGS_KEY = '__kwargs__' ARGS_REF = 'root.%s' % ARGS_KEY KWARGS_REF = 'root.%s' % KWARGS_KEY class JSONFunction(object): ARGS = ref('root.__args__') KWARGS = ref('root.__kwargs__') def __init__(self, prog_son): self.prog_son = prog_son def __call__(self, *_args, **_kwargs): prog = copy.deepcopy(self.prog_son) prog['__args__'] = copy.deepcopy(_args) prog['__kwargs__'] = copy.deepcopy(_kwargs) rval = resolve(prog) rval.pop('__args__') rval.pop('__kwargs__') return rval # Currently not used class JAMES_JSONFunction(object): """Make a GenSON document into a callable function """ # TODO: make the treatment of args and kwargs in the document # more Python-like. The current implementation requires that # parameters (and hence arguments as well) be divided between # positional and keyword, which python does not require. # -- This construction allow ARGS and KWARGS to be lazily-indexed _ARGS = [] _KWARGS = {} ARGS = internal_ops.identity.lazy(_ARGS) KWARGS = internal_ops.identity.lazy(_KWARGS) def __init__(self, prog): self.prog = prog def __call__(self, *args, **kwargs): prog, ARGS, KWARGS = copy.deepcopy( (self.prog, self._ARGS, self._KWARGS)) ARGS[:] = [literal(a) for a in args] KWARGS.update(dict([(k, literal(v)) for k, v in kwargs.items()])) memo = {} rec_eval([prog], memo) rval = memo[id(prog)] return rval
mit
kzvyahin/cfme_tests
cfme/tests/intelligence/reports/test_validate_chargeback_report.py
1
18742
# -*- coding: utf-8 -*- import cfme.configure.access_control as ac import cfme.intelligence.chargeback as cb import fauxfactory import pytest import re from cfme import Credential from cfme import test_requirements from cfme.common.vm import VM from cfme.configure.configuration import get_server_roles, set_server_roles, candu from cfme.intelligence.reports.reports import CustomReport from datetime import date from utils.log import logger from utils import testgen, version from utils.wait import wait_for pytestmark = [ pytest.mark.tier(2), test_requirements.chargeback ] def pytest_generate_tests(metafunc): # Filter out providers not meant for Chargeback Testing argnames, argvalues, idlist = testgen.provider_by_type(metafunc, ['virtualcenter', 'rhevm'], required_fields=[(['cap_and_util', 'test_chargeback'], True)] ) new_argvalues = [] new_idlist = [] for i, argvalue_tuple in enumerate(argvalues): args = dict(zip(argnames, argvalue_tuple)) capandu_data = args['provider'].data['cap_and_util'] stream = capandu_data.get('chargeback_runs_on_stream', '') if not version.current_version().is_in_series(str(stream)): continue new_idlist.append(idlist[i]) new_argvalues.append(argvalues[i]) testgen.parametrize(metafunc, argnames, new_argvalues, ids=new_idlist, scope="module") def new_credential(): return Credential(principal='uid' + fauxfactory.gen_alphanumeric(), secret='secret') @pytest.yield_fixture(scope="module") def vm_ownership(enable_candu, setup_provider_modscope, provider): # In these tests, chargeback reports are filtered on VM owner.So,VMs have to be # assigned ownership. try: vm_name = provider.data['cap_and_util']['chargeback_vm'] vm = VM.factory(vm_name, provider) cb_group = ac.Group(description='EvmGroup-super_administrator') user = ac.User(name=provider.name + fauxfactory.gen_alphanumeric(), credential=new_credential(), email='abc@example.com', group=cb_group, cost_center='Workload', value_assign='Database') user.create() vm.set_ownership(user=user.name) logger.info('ASSIGNED VM OWNERSHIP FOR {} RUNNING ON {}'.format(vm_name, provider.name)) yield user.name finally: vm.unset_ownership() user.delete() @pytest.yield_fixture(scope="module") def enable_candu(db): # C&U data collection consumes a lot of memory and CPU.So, we are disabling some server roles # that are not needed for Chargeback reporting. original_roles = get_server_roles() new_roles = original_roles.copy() new_roles.update({ 'ems_metrics_coordinator': True, 'ems_metrics_collector': True, 'ems_metrics_processor': True, 'automate': False, 'smartstate': False}) set_server_roles(**new_roles) candu.enable_all() yield candu.disable_all() set_server_roles(**original_roles) @pytest.fixture(scope="module") def assign_compute_default_rate(provider): # Assign default Compute rate to the Enterprise and then queue the Chargeback report. enterprise = cb.Assign( assign_to="The Enterprise", selections={ "Enterprise": "Default" }) enterprise.computeassign() logger.info('ASSIGNING DEFAULT COMPUTE RATE') @pytest.yield_fixture(scope="module") def assign_compute_custom_rate(new_compute_rate, provider): # Assign custom Compute rate to the Enterprise and then queue the Chargeback report. description = new_compute_rate enterprise = cb.Assign( assign_to="The Enterprise", selections={ "Enterprise": description }) enterprise.computeassign() logger.info('ASSIGNING CUSTOM COMPUTE RATE') yield enterprise = cb.Assign( assign_to="The Enterprise", selections={ "Enterprise": "Default" }) enterprise.computeassign() def count_records_rollups_table(db, provider): vm_name = provider.data['cap_and_util']['chargeback_vm'] ems = db['ext_management_systems'] provider_id = db.session.query(ems).filter(ems.name == provider.name).first().id rollups = db['metric_rollups'] count = db.session.query(rollups).filter(rollups.parent_ems_id == provider_id, rollups.resource_name == vm_name).count() if count > 0: return count return 0 @pytest.fixture(scope="module") def resource_usage(vm_ownership, db, provider, ssh_client_modscope): # Retrieve resource usage values from metric_rollups table. average_cpu_used_in_mhz = 0 average_memory_used_in_mb = 0 average_network_io = 0 average_disk_io = 0 vm_name = provider.data['cap_and_util']['chargeback_vm'] metrics = db['metrics'] rollups = db['metric_rollups'] ems = db['ext_management_systems'] logger.info('DELETING METRICS DATA FROM METRICS AND METRIC_ROLLUPS tables') db.session.query(metrics).delete() db.session.query(rollups).delete() provider_id = db.session.query(ems).filter(ems.name == provider.name).first().id # Chargeback reporting is not done on real-time values.So, we are capturing C&U data # and forcing hourly rollups by running these commands through the Rails console. logger.info('CAPTURING PERF DATA FOR VM {} running on {}'.format(vm_name, provider.name)) ssh_client_modscope.run_rails_command( "\"vm = Vm.where(:ems_id => {}).where(:name => {})[0];\ vm.perf_capture('realtime',1.hour.ago.utc, Time.now.utc);\ vm.perf_rollup_range('realtime',1.hour.ago.utc, Time.now.utc)\"". format(provider_id, repr(vm_name))) wait_for(count_records_rollups_table, [db, provider], timeout=60, fail_condition=0, message="rollups") # Since we are collecting C&U data for > 1 hour, there will be multiple hourly records per VM # in the metric_rollups DB table.The values from these hourly records are summed up. with db.transaction: providers = ( db.session.query(rollups.id) .join(ems, rollups.parent_ems_id == ems.id) .filter(rollups.capture_interval_name == 'hourly', rollups.resource_name == vm_name, ems.name == provider.name, rollups.timestamp >= date.today()) ) for record in db.session.query(rollups).filter(rollups.id.in_(providers.subquery())): if record.cpu_usagemhz_rate_average is None: pass else: average_cpu_used_in_mhz = average_cpu_used_in_mhz + record.cpu_usagemhz_rate_average average_memory_used_in_mb = average_memory_used_in_mb + record.derived_memory_used average_network_io = average_network_io + record.net_usage_rate_average average_disk_io = average_disk_io + record.disk_usage_rate_average return {"average_cpu_used_in_mhz": average_cpu_used_in_mhz, "average_memory_used_in_mb": average_memory_used_in_mb, "average_network_io": average_network_io, "average_disk_io": average_disk_io} def query_rate(db, provider, metric, description, rate_type): # Query the DB for Chargeback rates details = db['chargeback_rate_details'] rates = db['chargeback_rates'] with db.transaction: providers = ( db.session.query(details.id) .join(rates, details.chargeback_rate_id == rates.id) .filter(details.metric == metric, rates.description == description, rates.rate_type == rate_type) ) rate = db.session.query(details).filter(details.id.in_( providers.subquery())).first().rate return rate @pytest.fixture(scope="module") def chargeback_costs_default(resource_usage, db, provider): # Estimate Chargeback costs using default Chargeback rate and resource usage from the DB. average_cpu_used_in_mhz = resource_usage['average_cpu_used_in_mhz'] average_memory_used_in_mb = resource_usage['average_memory_used_in_mb'] average_network_io = resource_usage['average_network_io'] average_disk_io = resource_usage['average_disk_io'] cpu_rate = query_rate(db, provider, 'cpu_usagemhz_rate_average', 'Default', 'Compute') cpu_used_cost = average_cpu_used_in_mhz * float(cpu_rate) / 24 memory_rate = query_rate(db, provider, 'derived_memory_used', 'Default', 'Compute') memory_used_cost = average_memory_used_in_mb * float(memory_rate) / 24 network_rate = query_rate(db, provider, 'net_usage_rate_average', 'Default', 'Compute') network_used_cost = average_network_io * float(network_rate) disk_rate = query_rate(db, provider, 'disk_usage_rate_average', 'Default', 'Compute') disk_used_cost = average_disk_io * float(disk_rate) return {"cpu_used_cost": cpu_used_cost, "memory_used_cost": memory_used_cost, "network_used_cost": network_used_cost, "disk_used_cost": disk_used_cost} @pytest.fixture(scope="module") def chargeback_costs_custom(resource_usage, new_compute_rate, db, provider): # Estimate Chargeback costs using custom Chargeback rate and resource usage from the DB. description = new_compute_rate average_cpu_used_in_mhz = resource_usage['average_cpu_used_in_mhz'] average_memory_used_in_mb = resource_usage['average_memory_used_in_mb'] average_network_io = resource_usage['average_network_io'] average_disk_io = resource_usage['average_disk_io'] cpu_rate = query_rate(db, provider, 'cpu_usagemhz_rate_average', description, 'Compute') cpu_used_cost = average_cpu_used_in_mhz * float(cpu_rate) / 24 memory_rate = query_rate(db, provider, 'derived_memory_used', description, 'Compute') memory_used_cost = average_memory_used_in_mb * float(memory_rate) / 24 network_rate = query_rate(db, provider, 'net_usage_rate_average', description, 'Compute') network_used_cost = average_network_io * float(network_rate) disk_rate = query_rate(db, provider, 'disk_usage_rate_average', description, 'Compute') disk_used_cost = average_disk_io * float(disk_rate) return {"cpu_used_cost": cpu_used_cost, "memory_used_cost": memory_used_cost, "network_used_cost": network_used_cost, "disk_used_cost": disk_used_cost} @pytest.yield_fixture(scope="module") def chargeback_report_default(vm_ownership, assign_compute_default_rate, provider): # Create a Chargeback report based on the default Compute rate; Queue the report owner = vm_ownership data = {'menu_name': 'cb_' + provider.name, 'title': 'cb_' + provider.name, 'base_report_on': 'Chargebacks', 'report_fields': ['Memory Used', 'Memory Used Cost', 'Owner', 'CPU Used', 'CPU Used Cost', 'Disk I/O Used', 'Disk I/O Used Cost', 'Network I/O Used', 'Network I/O Used Cost'], 'filter_show_costs': 'Owner', 'filter_owner': owner, 'interval_end': 'Today (partial)'} report = CustomReport(is_candu=True, **data) report.create() logger.info('QUEUING DEFAULT CHARGEBACK REPORT FOR {} PROVIDER'.format(provider.name)) report.queue(wait_for_finish=True) yield list(report.get_saved_reports()[0].data[0].rows) report.delete() @pytest.yield_fixture(scope="module") def chargeback_report_custom(vm_ownership, assign_compute_custom_rate, provider): # Create a Chargeback report based on a custom Compute rate; Queue the report owner = vm_ownership data = {'menu_name': 'cb_custom_' + provider.name, 'title': 'cb_custom' + provider.name, 'base_report_on': 'Chargebacks', 'report_fields': ['Memory Used', 'Memory Used Cost', 'Owner', 'CPU Used', 'CPU Used Cost', 'Disk I/O Used', 'Disk I/O Used Cost', 'Network I/O Used', 'Network I/O Used Cost'], 'filter_show_costs': 'Owner', 'filter_owner': owner, 'interval_end': 'Today (partial)'} report = CustomReport(is_candu=True, **data) report.create() logger.info('QUEUING CUSTOM CHARGEBACK REPORT FOR {} PROVIDER'.format(provider.name)) report.queue(wait_for_finish=True) yield list(report.get_saved_reports()[0].data[0].rows) report.delete() @pytest.yield_fixture(scope="module") def new_compute_rate(): # Create a new Chargeback compute rate try: desc = 'custom_' + fauxfactory.gen_alphanumeric() ccb = cb.ComputeRate(description=desc, cpu_used=(3, cb.DAILY), disk_io=(1, cb.HOURLY), compute_fixed_1=(0, cb.DAILY), compute_fixed_2=(0, cb.MONTHLY), mem_alloc=(0, cb.DAILY), mem_used=(2, cb.DAILY), net_io=(2, cb.HOURLY)) ccb.create() yield desc finally: ccb.delete() # Tests to validate costs reported in the Chargeback report for various metrics. # The costs reported in the Chargeback report should be approximately equal to the # costs estimated in the chargeback_costs_default/chargeback_costs_custom fixtures. def test_validate_default_rate_cpu_usage_cost(chargeback_costs_default, chargeback_report_default): """Test to validate CPU usage cost. Calculation is based on default Chargeback rate. """ for groups in chargeback_report_default: if groups["CPU Used Cost"]: estimated_cpu_usage_cost = chargeback_costs_default['cpu_used_cost'] cost_from_report = groups["CPU Used Cost"] cost = re.sub(r'[$,]', r'', cost_from_report) assert estimated_cpu_usage_cost - 1.0 <= float(cost) \ <= estimated_cpu_usage_cost + 1.0, 'Estimated cost and report cost do not match' break def test_validate_default_rate_memory_usage_cost(chargeback_costs_default, chargeback_report_default): """Test to validate memory usage cost. Calculation is based on default Chargeback rate. """ for groups in chargeback_report_default: if groups["Memory Used Cost"]: estimated_memory_usage_cost = chargeback_costs_default['memory_used_cost'] cost_from_report = groups["Memory Used Cost"] cost = re.sub(r'[$,]', r'', cost_from_report) assert estimated_memory_usage_cost - 1.0 <= float(cost) \ <= estimated_memory_usage_cost + 1.0, 'Estimated cost and report cost do not match' break def test_validate_default_rate_network_usage_cost(chargeback_costs_default, chargeback_report_default): """Test to validate network usage cost. Calculation is based on default Chargeback rate. """ for groups in chargeback_report_default: if groups["Network I/O Used Cost"]: estimated_network_usage_cost = chargeback_costs_default['network_used_cost'] cost_from_report = groups["Network I/O Used Cost"] cost = re.sub(r'[$,]', r'', cost_from_report) assert estimated_network_usage_cost - 1.0 <= float(cost) \ <= estimated_network_usage_cost + 1.0, 'Estimated cost and report cost do not match' break def test_validate_default_rate_disk_usage_cost(chargeback_costs_default, chargeback_report_default): """Test to validate disk usage cost. Calculation is based on default Chargeback rate. """ for groups in chargeback_report_default: if groups["Disk I/O Used Cost"]: estimated_disk_usage_cost = chargeback_costs_default['disk_used_cost'] cost_from_report = groups["Disk I/O Used Cost"] cost = re.sub(r'[$,]', r'', cost_from_report) assert estimated_disk_usage_cost - 1.0 <= float(cost) \ <= estimated_disk_usage_cost + 1.0, 'Estimated cost and report cost do not match' break def test_validate_custom_rate_cpu_usage_cost(chargeback_costs_custom, chargeback_report_custom): """Test to validate CPU usage cost. Calculation is based on custom Chargeback rate. """ for groups in chargeback_report_custom: if groups["CPU Used Cost"]: estimated_cpu_usage_cost = chargeback_costs_custom['cpu_used_cost'] cost_from_report = groups["CPU Used Cost"] cost = re.sub(r'[$,]', r'', cost_from_report) assert estimated_cpu_usage_cost - 1.0 <= float(cost) \ <= estimated_cpu_usage_cost + 1.0, 'Estimated cost and report cost do not match' break def test_validate_custom_rate_memory_usage_cost(chargeback_costs_custom, chargeback_report_custom): """Test to validate memory usage cost. Calculation is based on custom Chargeback rate. """ for groups in chargeback_report_custom: if groups["Memory Used Cost"]: estimated_memory_usage_cost = chargeback_costs_custom['memory_used_cost'] cost_from_report = groups["Memory Used Cost"] cost = re.sub(r'[$,]', r'', cost_from_report) assert estimated_memory_usage_cost - 1.0 <= float(cost) \ <= estimated_memory_usage_cost + 1.0, 'Estimated cost and report cost do not match' break def test_validate_custom_rate_network_usage_cost(chargeback_costs_custom, chargeback_report_custom): """Test to validate network usage cost. Calculation is based on custom Chargeback rate. """ for groups in chargeback_report_custom: if groups["Network I/O Used Cost"]: estimated_network_usage_cost = chargeback_costs_custom['network_used_cost'] cost_from_report = groups["Network I/O Used Cost"] cost = re.sub(r'[$,]', r'', cost_from_report) assert estimated_network_usage_cost - 1.0 <= float(cost) \ <= estimated_network_usage_cost + 1.0, 'Estimated cost and report cost do not match' break def test_validate_custom_rate_disk_usage_cost(chargeback_costs_custom, chargeback_report_custom): """Test to validate disk usage cost. Calculation is based on custom Chargeback rate. """ for groups in chargeback_report_custom: if groups["Disk I/O Used Cost"]: estimated_disk_usage_cost = chargeback_costs_custom['disk_used_cost'] cost_from_report = groups["Disk I/O Used Cost"] cost = re.sub(r'[$,]', r'', cost_from_report) assert estimated_disk_usage_cost - 1.0 <= float(cost) \ <= estimated_disk_usage_cost + 1.0, 'Estimated cost and report cost do not match' break
gpl-2.0
alshedivat/tensorflow
tensorflow/contrib/tensor_forest/hybrid/python/layers/fully_connected.py
39
2892
# 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. # ============================================================================== """Neural network components for hybrid models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib import layers from tensorflow.contrib.tensor_forest.hybrid.python import hybrid_layer from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops class FullyConnectedLayer(hybrid_layer.HybridLayer): """A stacked, fully-connected feed-forward neural network layer.""" def _define_vars(self, params): pass def inference_graph(self, data): with ops.device(self.device_assigner): # Compute activations for the neural network. nn_activations = layers.fully_connected(data, self.params.layer_size) for _ in range(1, self.params.num_layers): # pylint: disable=W0106 nn_activations = layers.fully_connected(nn_activations, self.params.layer_size) return nn_activations class ManyToOneLayer(hybrid_layer.HybridLayer): def _define_vars(self, params): pass def inference_graph(self, data): with ops.device(self.device_assigner): # Compute activations for the neural network. nn_activations = layers.fully_connected(data, 1) # There is always one activation per instance by definition, so squeeze # away the extra dimension. return array_ops.squeeze(nn_activations, axis=[1]) class FlattenedFullyConnectedLayer(hybrid_layer.HybridLayer): """A stacked, fully-connected flattened feed-forward neural network layer.""" def _define_vars(self, params): pass def inference_graph(self, data): with ops.device(self.device_assigner): # Compute activations for the neural network. nn_activations = [layers.fully_connected(data, self.params.layer_size)] for _ in range(1, self.params.num_layers): # pylint: disable=W0106 nn_activations.append( layers.fully_connected( nn_activations[-1], self.params.layer_size)) nn_activations_tensor = array_ops.concat( nn_activations, 1, name="flattened_nn_activations") return nn_activations_tensor
apache-2.0
jcpowermac/ansible
test/units/modules/network/eos/test_eos_system.py
57
4651
# (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.tests.mock import patch from ansible.modules.network.eos import eos_system from units.modules.utils import set_module_args from .eos_module import TestEosModule, load_fixture class TestEosSystemModule(TestEosModule): module = eos_system def setUp(self): super(TestEosSystemModule, self).setUp() self.mock_get_config = patch('ansible.modules.network.eos.eos_system.get_config') self.get_config = self.mock_get_config.start() self.mock_load_config = patch('ansible.modules.network.eos.eos_system.load_config') self.load_config = self.mock_load_config.start() def tearDown(self): super(TestEosSystemModule, self).tearDown() self.mock_get_config.stop() self.mock_load_config.stop() def load_fixtures(self, commands=None, transport='cli'): self.get_config.return_value = load_fixture('eos_system_config.cfg') self.load_config.return_value = dict(diff=None, session='session') def test_eos_system_hostname_changed(self): set_module_args(dict(hostname='foo')) commands = ['hostname foo'] self.execute_module(changed=True, commands=commands) def test_eos_system_domain_name(self): set_module_args(dict(domain_name='test.com')) commands = ['ip domain-name test.com'] self.execute_module(changed=True, commands=commands) def test_eos_system_domain_list(self): set_module_args(dict(domain_list=['ansible.com', 'redhat.com'])) commands = ['no ip domain-list ops.ansible.com', 'ip domain-list redhat.com'] self.execute_module(changed=True, commands=commands) def test_eos_system_lookup_source(self): set_module_args(dict(lookup_source=['Ethernet1'])) commands = ['no ip domain lookup source-interface Management1', 'ip domain lookup source-interface Ethernet1'] self.execute_module(changed=True, commands=commands) def test_eos_system_lookup_source_complex(self): lookup_source = [{'interface': 'Management1', 'vrf': 'mgmt'}, {'interface': 'Ethernet1'}] set_module_args(dict(lookup_source=lookup_source)) commands = ['no ip domain lookup source-interface Management1', 'ip domain lookup vrf mgmt source-interface Management1', 'ip domain lookup source-interface Ethernet1'] self.execute_module(changed=True, commands=commands) # def test_eos_system_name_servers(self): # name_servers = ['8.8.8.8', '8.8.4.4'] # set_module_args(dict(name_servers=name_servers)) # commands = ['ip name-server 8.8.4.4', # 'no ip name-server vrf mgmt 8.8.4.4'] # self.execute_module(changed=True, commands=commands) # def rest_eos_system_name_servers_complex(self): # name_servers = dict(server='8.8.8.8', vrf='test') # set_module_args(dict(name_servers=name_servers)) # commands = ['ip name-server vrf test 8.8.8.8', # 'no ip name-server vrf default 8.8.8.8', # 'no ip name-server vrf mgmt 8.8.4.4'] # self.execute_module(changed=True, commands=commands) def test_eos_system_state_absent(self): set_module_args(dict(state='absent')) commands = ['no ip domain-name', 'no hostname'] self.execute_module(changed=True, commands=commands) def test_eos_system_no_change(self): set_module_args(dict(hostname='switch01', domain_name='eng.ansible.com')) commands = [] self.execute_module(commands=commands) def test_eos_system_missing_vrf(self): name_servers = dict(server='8.8.8.8', vrf='missing') set_module_args(dict(name_servers=name_servers)) result = self.execute_module(failed=True)
gpl-3.0
rbruyere/appengine-mapreduce
python/test/mapreduce/main_test.py
22
2326
#!/usr/bin/env python # # 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. import re import unittest from mapreduce import main class MainTest(unittest.TestCase): """Tests for main module.""" def testCreateApplication(self): """Test create_application function. Verify that it gets all import right. """ main.create_application() def testRedirectRegularExpression(self): """Verify that depth of mapped path does not impact static RE matching.""" basepath = '/mapreduce' extensions = {'': False, '/': False, '/resource.css': True, '/status': True, '/detail': True} self.staticMatchesExtensions(basepath, extensions) basepath = '/_ah/mapper' self.staticMatchesExtensions(basepath, extensions) basepath = '/contains/status/but/does/not/end/in/it' self.staticMatchesExtensions(basepath, extensions) def staticMatchesExtensions(self, basepath, extensions): """Iterates over extensions to assert whether or not regex should match.""" for ext, should_match in extensions.iteritems(): if should_match: self.assertMatches(basepath+ext, main.STATIC_RE) else: self.assertNotMatches(basepath+ext, main.STATIC_RE) def assertMatches(self, text, regex): """Corresponding re.match version of assertRegexpMatches.""" m = re.match(regex, text) if not m: self.fail('Text %s was not matched by pattern %s.' % (text, regex)) def assertNotMatches(self, text, regex): """Corresponding re.match version of assertNotRegexpMatches.""" m = re.match(regex, text) if m: self.fail('Text %s was matched by pattern %s as %s.' % (text, regex, m.group(0))) if __name__ == '__main__': unittest.main()
apache-2.0
ttfseiko/openerp-trunk
openerp/addons/project_gtd/wizard/project_gtd_empty.py
4
2453
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class project_timebox_empty(osv.osv_memory): _name = 'project.timebox.empty' _description = 'Project Timebox Empty' _columns = { 'name': fields.char('Name', size=32) } def view_init(self, cr, uid, fields_list, context=None): if context is None: context = {} self._empty(cr, uid, context=context) pass def _empty(self, cr, uid, context=None): close = [] up = [] obj_tb = self.pool.get('project.gtd.timebox') obj_task = self.pool.get('project.task') if context is None: context = {} if not 'active_id' in context: return {} ids = obj_tb.search(cr, uid, [], context=context) if not len(ids): raise osv.except_osv(_('Error!'), _('No timebox child of this one!')) tids = obj_task.search(cr, uid, [('timebox_id', '=', context['active_id'])]) for task in obj_task.browse(cr, uid, tids, context): if (task.stage_id and task.stage_id.fold) or (task.user_id.id <> uid): close.append(task.id) else: up.append(task.id) if up: obj_task.write(cr, uid, up, {'timebox_id':ids[0]}) if close: obj_task.write(cr, uid, close, {'timebox_id':False}) return {} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
simone-campagna/py-structparser
structparser/editor/qt_editor.py
1
25136
#!/usr/bin/env python # # Copyright 2013 Simone Campagna # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # __author__ = 'Simone Campagna' import abc import sys import StringIO from .base_editor import * from ..scalar import * from ..const import * from ..bool import * from ..enum import * #from ..free_list import * #from ..array import * from ..list import * from ..option import * from ..struct import * from ..subfile import * from PyQt4 import Qt from PyQt4 import QtGui from PyQt4 import QtCore class WMessage(QtGui.QMessageBox): def __init__(self, title, message): super(WMessage, self).__init__() self.information(self, title, message, QtGui.QMessageBox.Ok) class WAlert(QtGui.QMessageBox): def __init__(self, message, exc=None): if exc is not None: if isinstance(exc, InputError): text = exc.show() else: text = "{0}: {1}".format(exc.__class__.__name__, exc) super(WAlert, self).__init__() self.warning(self, message, text, QtGui.QMessageBox.Ok) class WBase(object): def __init__(self, editor, owner, field, name=None): self._editor = editor self._owner = owner self.field = field assert isinstance(field, Field) if name is None: name = field.get_full_name() self.name = name pname = field.get_name() self.pname = pname self.wlabels = set() #subcontrol-origin: content; self.initUI() self.populateUI() self.initStyle() field_description = self.field.get_description() tooltip_lines = ["<{0}>".format(self.field.class_description())] if field_description: tooltip_lines.append(field_description) tooltip = '\n'.join(tooltip_lines) self.setToolTip(tooltip) self._editor.register_widget(self.field, self) @abc.abstractmethod def initUI(self): pass @abc.abstractmethod def populateUI(self): pass def initStyle(self): pass def init_wlabels(self): self.wlabels = set() def register_wlabel(self, wlabel): self.wlabels.add(wlabel) def update_wlabels(self): if self.wlabels: wmax = max(wlabel.sizeHint().width() for wlabel in self.wlabels) for wlabel in self.wlabels: wlabel.setMinimumWidth(wmax) @classmethod def create(cls, editor, owner, field): if isinstance(field, Enum): return WEnum(editor, owner, field) elif isinstance(field, Switch): return WSwitch(editor, owner, field) elif isinstance(field, Bool): return WBool(editor, owner, field) elif isinstance(field, Size): return WSize(editor, owner, field) elif isinstance(field, NonNegativeInt): return WNonNegativeInt(editor, owner, field) elif isinstance(field, PositiveInt): return WPositiveInt(editor, owner, field) elif isinstance(field, BaseConst): return WConst(editor, owner, field) elif isinstance(field, BaseSubFile): return WSubFile(editor, owner, field) elif isinstance(field, Path): return WPath(editor, owner, field) elif isinstance(field, Int): return WInt(editor, owner, field) elif isinstance(field, Float): return WFloat(editor, owner, field) elif isinstance(field, Scalar): return WScalar(editor, owner, field) elif isinstance(field, BaseList): return WList(editor, owner, field) # elif isinstance(field, FreeList): # return WFreeList(editor, owner, field) # elif isinstance(field, BaseArray): # return WArray(editor, owner, field) elif isinstance(field, BaseOption): return WOption(editor, owner, field) elif isinstance(field, Struct): return WStruct(editor, owner, field) else: raise TypeError("invalid type {0}".format(type(field).__name__)) def clearUI(self): for i in reversed(range(self.layout.count())): layout_item = self.layout.itemAt(i) widget = layout_item.widget() if widget: widget.close() self.layout.removeItem(layout_item) def updateUI(self): self.clearUI() self.populateUI() class WNode(WBase, QtGui.QWidget): def __init__(self, editor, owner, field, name=None): QtGui.QWidget.__init__(self) WBase.__init__(self, editor, owner, field, name=name) class WOption(WNode): def __init__(self, editor, owner, field, name=None): self._actual_node = self.create(editor, owner, field.get_field()) super(WOption, self).__init__(editor, owner, field, name=name) def initUI(self): self.layout = QtGui.QVBoxLayout() self.setLayout(self.layout) def populateUI(self): self.layout.addWidget(self._actual_node) self.set_visibility() def set_visibility(self): self._actual_node.setVisible(self.field.is_on()) class WGroup(WBase, QtGui.QGroupBox): def __init__(self, editor, owner, field, name=None): QtGui.QGroupBox.__init__(self) WBase.__init__(self, editor, owner, field, name=name) def initStyle(self): self.setTitle(self.name) self.setStyleSheet("""\ QGroupBox { border: 1px solid gray; border-radius: 10px; padding:10 20px; } QGroupBox::title { background-color: transparent; color: black; font-weight: bold; subcontrol-origin: margin; subcontrol-position: top left; /* position at the top left*/ padding:2 10px; } """) class WLineEdit(QtGui.QLineEdit): def __init__(self, text): super(WLineEdit, self).__init__(text) self.setAlignment(QtCore.Qt.AlignLeft) class WIntSpinBox(QtGui.QSpinBox): def __init__(self, value=None): super(WIntSpinBox, self).__init__() if value is not None: self.setValue(value) self.setAlignment(QtCore.Qt.AlignLeft) self.setButtonSymbols(self.NoButtons) def wheelEvent(self, event): pass class WFloatSpinBox(QtGui.QDoubleSpinBox): def __init__(self, value=None): super(WFloatSpinBox, self).__init__() if value is not None: self.setValue(value) self.setAlignment(QtCore.Qt.AlignLeft) self.setButtonSymbols(self.NoButtons) def wheelEvent(self, event): pass class WScalarEntry(WLineEdit): def __init__(self, editor, owner, field, init): super(WScalarEntry, self).__init__(str(init)) self._editor = editor self._owner = owner self._field = field self.editingFinished.connect(self.notify_parent) def notify_parent(self): t = self.text() try: self.parent().set_current_value(t) #self.text()) except Exception as e: import traceback traceback.print_exc() WAlert("Invalid value", e) self.setText(str(self.parent().get_current_value())) class WBaseSpinBoxEntry(object): MAX = None MIN = None def __init__(self, editor, owner, field, init): self._editor = editor self._owner = owner self._field = field if self._field.__min__ is None: minint = self.MIN else: minint = self._field.__min__ if self._field.__max__ is None: maxint = self.MAX else: maxint = self._field.__min__ self.setRange(minint, maxint) self.setValue(init) #self.valueChanged.connect(self.notify_parent) self.editingFinished.connect(self.notify_parent) def notify_parent(self): value = self.value() try: self.parent().set_current_value(value) except Exception as e: import traceback traceback.print_exc() WAlert("Invalid value", e) self.setValue(self.parent().get_current_value()) class WIntSpinBoxEntry(WBaseSpinBoxEntry, WIntSpinBox): MAX = 2**30 MIN = -MAX def __init__(self, editor, owner, field, init): WIntSpinBox.__init__(self) super(WIntSpinBoxEntry, self).__init__(editor, owner, field, init) class WSizeSpinBoxEntry(WIntSpinBoxEntry): def __init__(self, editor, owner, field, init): super(WSizeSpinBoxEntry, self).__init__(editor, owner, field, init) self.setButtonSymbols(self.PlusMinus) class WFloatSpinBoxEntry(WBaseSpinBoxEntry, WFloatSpinBox): MAX = sys.float_info.max MIN = sys.float_info.min DIGITS = sys.float_info.dig def __init__(self, editor, owner, field, init): WFloatSpinBox.__init__(self) self.setDecimals(self.DIGITS) super(WFloatSpinBoxEntry, self).__init__(editor, owner, field, init) self.editingFinished.connect(self.remove_zeros) def changeEvent(self, event): WFloatSpinBox.changeEvent(self, event) self.remove_zeros() def remove_zeros(self): line_edit = self.lineEdit() text = str(line_edit.text()) mod_text = text.rstrip('0') if mod_text and mod_text[-1] == '.': mod_text += '0' #print text, '->', mod_text line_edit.setText(mod_text) class WLabel(QtGui.QLabel): def __init__(self, text): super(WLabel, self).__init__(text) class WScalar(WNode): VALUE_WIDGET_CLASS = WScalarEntry def __init__(self, editor, owner, field, name=None): self._num_widgets = 0 super(WScalar, self).__init__(editor, owner, field, name=name) def get_new_wid(self): i = self._num_widgets self._num_widgets += 1 return i def get_current_value(self): return self.field.value def notify_connections(self): for connection in self.field.iterparentconnections(): target = connection.get_target() #print "!!!!!!!!!!!!!!", self.field.get_full_name(), target, target.get_full_name() wtarget = self._editor.get_widget(target) wtarget.updateUI() #parent = field.get_parent() #if parent: # self.notify_field_connections(parent) def set_current_value(self, value): self.field.fromstr(value) self.notify_connections() def update_current_value(self, value): self.set_current_value(value) self.w_value.setText(str(self.get_current_value())) def initUI(self): self.layout = QtGui.QGridLayout() self.setLayout(self.layout) def populateUI(self): #self.layout.addWidget(QtGui.QLabel(self.field.description()), 0, 1) self.w_key = self.keyWidget() self.layout.addWidget(self.w_key, 0, self.get_new_wid()) self._owner.register_wlabel(self.w_key) self.w_value = self.valueWidget() self.layout.addWidget(self.w_value, 0, self.get_new_wid()) #REM self.show() def keyWidget(self): return WLabel(self.name) def valueWidget(self): return self.VALUE_WIDGET_CLASS(self._editor, self._owner, self.field, self.get_current_value()) class WPositiveInt(WScalar): VALUE_WIDGET_CLASS = WIntSpinBoxEntry def valueWidget(self): return self.VALUE_WIDGET_CLASS(self._editor, self._owner, self.field, self.get_current_value()) def set_current_value(self, value): self.field.value = value self.notify_connections() class WNonNegativeInt(WScalar): VALUE_WIDGET_CLASS = WIntSpinBoxEntry def valueWidget(self): return self.VALUE_WIDGET_CLASS(self._editor, self._owner, self.field, self.get_current_value()) def set_current_value(self, value): self.field.value = value self.notify_connections() class WNumeric(WScalar): def set_current_value(self, value): self.field.value = value self.notify_connections() class WInt(WNumeric): VALUE_WIDGET_CLASS = WIntSpinBoxEntry class WFloat(WNumeric): VALUE_WIDGET_CLASS = WFloatSpinBoxEntry class WSize(WNonNegativeInt): VALUE_WIDGET_CLASS = WSizeSpinBoxEntry class WPath(WScalar): def populateUI(self): super(WPath, self).populateUI() self.browse_button = QtGui.QPushButton('Browse', self) self.browse_button.clicked.connect(self.browse) self.layout.addWidget(self.browse_button, 0, self.get_new_wid()) def browse(self): pathname = self.get_current_value() file_dialog = QtGui.QFileDialog(self) file_dialog.setFileMode(QtGui.QFileDialog.AnyFile); if pathname and os.path.lexists(pathname): if os.path.isdir(pathname): file_dialog.setDirectory(pathname) else: dirname, filename = os.path.split(pathname) file_dialog.setDirectory(dirname) file_dialog.selectFile(filename) else: file_dialog.selectFile(pathname) if file_dialog.exec_(): filenames = file_dialog.selectedFiles() if filenames: self.update_current_value(str(filenames[0])) class WSubFile(WPath): def populateUI(self): super(WSubFile, self).populateUI() self.edit_button = QtGui.QPushButton('Edit', self) self.edit_button.clicked.connect(self.edit) self.layout.addWidget(self.edit_button, 0, self.get_new_wid()) def edit(self): filename = self.field.get_filename() try: if os.path.lexists(filename) and os.path.isfile(filename): field = self.field.load() else: field = self.field.new() except InputError as e: e.dump() WAlert("Invalid input file {0} for {1}:".format(filename, self.field.__class__.__name__), e) except Exception as e: sys.stderr.write("ERR: {0}: {1}\n".format(e.__class__.__name__, e)) else: WEditor(field, output_filename=filename, name=self.field.name) class WConst(WScalar): def valueWidget(self): w = WLineEdit(str(self.get_current_value())) d = self.field.get_description() w.setReadOnly(True) return w class WComboBox(QtGui.QComboBox): def wheelEvent(self, event): pass class WBool(WScalar): LABELS = ('True', 'False') VALUES = (True, False) @classmethod def _dct(cls): d = OrderedDict() for l, b in zip(cls.LABELS, cls.VALUES): d[l] = b return d def valueWidget(self): self.combobox = WComboBox() #QtGui.QComboBox() d = self._dct() keys = [] for index, (l, b) in enumerate(d.iteritems()): keys.append(l) if b == self.field.value: selected_index = index self.combobox.addItems(keys) self.combobox.activated[str].connect(self.onActivated) self.combobox.setCurrentIndex(selected_index) return self.combobox def onActivated(self, text): d = self._dct() b = d[str(text)] if b: s = '1' else: s = '0' self.set_current_value(s) @classmethod def enum_label(cls, enum_instance): return "{0}[{1}]".format(enum_instance.label, enum_instance.value) class WSwitch(WBool): LABELS = ('On', 'Off') def __init__(self, editor, owner, field, name=None): super(WSwitch, self).__init__(editor, owner, field, name) class WEnum(WScalar): def valueWidget(self): self.combobox = WComboBox() #QtGui.QComboBox() self.enums = OrderedDict() for enum_index, enum_instance in enumerate(self.field.__type__): enum_label = self.enum_label(enum_instance) self.enums[enum_label] = enum_instance if enum_instance is self.field.value: selected_index = enum_index self.combobox.addItems(self.enums.keys()) self.combobox.activated[str].connect(self.onActivated) self.combobox.setCurrentIndex(selected_index) return self.combobox def set_current_value(self, value): self.field.value = value self.notify_connections() def onActivated(self, text): enum_label = str(text) enum_instance = self.enums[enum_label] self.set_current_value(enum_instance) @classmethod def enum_label(cls, enum_instance): return "{0}[{1}]".format(enum_instance.label, enum_instance.value) class WStruct(WGroup): def initUI(self): self.layout = QtGui.QVBoxLayout() self.setLayout(self.layout) def populateUI(self): #l = QtGui.QLabel("Struct {0}".format(self.field.__class__.__name__)) #l.setStyleSheet("QLabel { background-color: rgb(255, 255, 230); color: rgb(0, 0, 255) };") #self.layout.addWidget(l) self.init_wlabels() for field_type in self.field.__fields__: field_name = field_type.field_name attr_name = field_type.attr_name field = getattr(self.field, attr_name) self.layout.addWidget(self.create(self._editor, self, field)) self.update_wlabels() #REM self.show() class WSequenceMenu(QtGui.QWidget): __list_type__ = "Sequence" def __init__(self, editor, owner): super(WSequenceMenu, self).__init__(editor) self._editor = editor self._owner = owner self.initUI() self.populateUI() def initUI(self): self.layout = QtGui.QHBoxLayout() self.setLayout(self.layout) def populateUI(self): self.layout.addSpacerItem(QtGui.QSpacerItem(0, 0, hPolicy = QtGui.QSizePolicy.Expanding)) #l = QtGui.QLabel("{0} {1}".format(self.list_type(), self.parent().name)) self.setStyleSheet("QLabel{ background-color: rgb(230, 230, 230); color: rgb(255, 0, 0) };") #self.layout.addWidget(l) #REM self.show() def list_type(self): return self.__list_type__ class WFreeListMenu(WSequenceMenu): __list_type__ = "FreeList" def populateUI(self): super(WFreeListMenu, self).populateUI() new_button = QtGui.QPushButton('Append new item', self) del_button = QtGui.QPushButton('Delete selected', self) new_button.clicked.connect(self.new_item) del_button.clicked.connect(self.del_items) self.layout.addSpacerItem(QtGui.QSpacerItem(0, 0, hPolicy = QtGui.QSizePolicy.Expanding)) self.layout.addWidget(new_button) self.layout.addWidget(del_button) #self.layout.addSpacerItem(QtGui.QSpacerItem(0, 0, hPolicy = QtGui.QSizePolicy.Expanding)) def new_item(self): self.parent().new_item() def del_items(self): self.parent().del_selected_items() class WArrayMenu(WSequenceMenu): __list_type__ = "Array" def list_type(self): return "{0}({1})".format(self.__list_type__, self.parent().field.__size__) class WListMenu(WSequenceMenu): __list_type__ = "List" def list_type(self): return "{0}({1})".format(self.__list_type__, self.parent().field.__connect__) class WLabel(QtGui.QLabel): def __init__(self, text): super(WLabel, self).__init__(text) class WSequence(WGroup): __menu_class__ = WSequenceMenu def initUI(self): self.layout = QtGui.QGridLayout() self.setLayout(self.layout) def populateUI(self): self.layout.addWidget(self.__menu_class__(self, self), 0, 1) for index, element in enumerate(self.field.iterelements()): self.createListElement(index, element) def createListElement(self, index, element): w = self.create(self._editor, self, element) self.layout.addWidget(w, index + 1, 1) class WFreeList(WSequence): __menu_class__ = WFreeListMenu def createListElement(self, index, element): r = index + 1 c = QtGui.QCheckBox() w = self.create(self._editor, self, element) self.layout.addWidget(c, r, 0) self.layout.addWidget(w, r, 1) def new_item(self): n = self.field.new_item() self.updateUI() def del_selected_items(self): indices = [] for index in xrange(0, len(self.field)): r = index + 1 c = self.layout.itemAtPosition(r, 0).widget() w = self.layout.itemAtPosition(r, 1).widget() if c.isChecked(): indices.append(index) if indices: self.del_indices(indices) #self.parent().setFocus() def del_indices(self, indices): for i_offset, i in enumerate(indices): self.field.delete(i - i_offset) self.updateUI() class WList(WSequence): __menu_class__ = WListMenu def __init__(self, editor, owner, field, name=None): super(WSequence, self).__init__(editor, owner, field, name) class WArray(WSequence): __menu_class__ = WArrayMenu class WMenu(QtGui.QWidget): def __init__(self, editor, owner): super(WMenu, self).__init__() self.initUI() self.populateUI() self._editor = editor self._owner = owner def initUI(self): self.layout = QtGui.QHBoxLayout() self.setLayout(self.layout) def populateUI(self): self.save_button = QtGui.QPushButton('Save', self) self.save_button.clicked.connect(self.save_and_quit) self.quit_button = QtGui.QPushButton('Quit', self) self.quit_button.clicked.connect(self.quit) self.layout.addSpacerItem(QtGui.QSpacerItem(0, 0, hPolicy = QtGui.QSizePolicy.Expanding)) self.layout.addWidget(self.save_button) self.layout.addWidget(self.quit_button) self.layout.addSpacerItem(QtGui.QSpacerItem(0, 0, hPolicy = QtGui.QSizePolicy.Expanding)) QtGui.QShortcut(QtGui.QKeySequence("Ctrl+q"), self, self.quit) QtGui.QShortcut(QtGui.QKeySequence("Ctrl+s"), self, self.save_and_quit) QtGui.QShortcut(QtGui.QKeySequence("Ctrl+w"), self, self.write) QtGui.QShortcut(QtGui.QKeySequence("Ctrl+h"), self, self.show_help) #REM self.show() def show_help(self): WMessage("Help", """\ Ctrl+s: Save and quit Ctrl+q: Quit (without saving) Ctrl+w: Write (save and continue)""") def write(self): self.setFocus() self._editor.save() def save_and_quit(self): # quit before to save: completes all events and dumps all edited fields self.setFocus() self._editor.save() self.quit() def quit(self): #self._editor.field.dump() #QtCore.QCoreApplication.instance().quit() #self.quit() self._editor.close() class WEditor(WBase, QtGui.QWidget): def __init__(self, field, output_filename=None, name=None): QtGui.QWidget.__init__(self) self.output_field = field.clone() self.output_filename = output_filename self._widget = {} WBase.__init__(self, self, None, field, name) def register_widget(self, field, widget): self._widget[field] = widget def get_widget(self, field): return self._widget[field] def save(self): self.output_field = self.field if self.output_filename is not None: self.output_field.tofile(self.output_filename) def initStyle(self): self.setStyleSheet("""\ QScrollArea { border: 0px solid gray; } """) def initUI(self): self.layout = QtGui.QVBoxLayout(self) self.layout.setMargin(0) self.layout.setContentsMargins(0, 0, 0, 0) scrolling_layout = QtGui.QVBoxLayout() scrolling_widget = QtGui.QWidget(self) scrolling_widget.setLayout(scrolling_layout) scroll_area = QtGui.QScrollArea(self) scroll_area.setEnabled(True) scroll_area.setWidgetResizable(True) scroll_area.setWidget(scrolling_widget) self.layout.addWidget(scroll_area) field_widget = self.create(self, self, self.field) scrolling_layout.addWidget(field_widget) scrolling_layout.addWidget(WMenu(self, self)) self.show() scroll_area.setMinimumSize(800, 500) def populateUI(self): pass class QtEditor(BaseEditor): def edit(self, field, output_filename=None, name=None): qt_app = QtGui.QApplication(sys.argv) if name is None: name = "" editor = WEditor(field, output_filename=output_filename, name=name) qt_app.exec_()
apache-2.0
utunga/hashmapd
lib/mock-0.7.0/tests/testmagicmethods.py
2
9991
# Copyright (C) 2007-2011 Michael Foord & the mock team # E-mail: fuzzyman AT voidspace DOT org DOT uk # http://www.voidspace.org.uk/python/mock/ from tests.support import unittest2, inPy3k try: unicode except NameError: # Python 3 unicode = str long = int import inspect from mock import Mock, MagicMock, _magics class TestMockingMagicMethods(unittest2.TestCase): def testDeletingMagicMethods(self): mock = Mock() self.assertFalse(hasattr(mock, '__getitem__')) mock.__getitem__ = Mock() self.assertTrue(hasattr(mock, '__getitem__')) del mock.__getitem__ self.assertFalse(hasattr(mock, '__getitem__')) def testMagicMethodWrapping(self): mock = Mock() def f(self, name): return self, 'fish' mock.__getitem__ = f self.assertFalse(mock.__getitem__ is f) self.assertEqual(mock['foo'], (mock, 'fish')) # When you pull the function back of the *instance* # the first argument (self) is removed def instance_f(name): pass self.assertEqual(inspect.getargspec(mock.__getitem__), inspect.getargspec(instance_f)) mock.__getitem__ = mock self.assertTrue(mock.__getitem__ is mock) def testMagicMethodsIsolatedBetweenMocks(self): mock1 = Mock() mock2 = Mock() mock1.__iter__ = Mock(return_value=iter([])) self.assertEqual(list(mock1), []) self.assertRaises(TypeError, lambda: list(mock2)) def testRepr(self): mock = Mock() self.assertEqual(repr(mock), object.__repr__(mock)) mock.__repr__ = lambda s: 'foo' self.assertEqual(repr(mock), 'foo') def testStr(self): mock = Mock() self.assertEqual(str(mock), object.__str__(mock)) mock.__str__ = lambda s: 'foo' self.assertEqual(str(mock), 'foo') @unittest2.skipIf(inPy3k, "no unicode in Python 3") def testUnicode(self): mock = Mock() self.assertEqual(unicode(mock), unicode(str(mock))) mock.__unicode__ = lambda s: unicode('foo') self.assertEqual(unicode(mock), unicode('foo')) def testDictMethods(self): mock = Mock() self.assertRaises(TypeError, lambda: mock['foo']) def _del(): del mock['foo'] def _set(): mock['foo'] = 3 self.assertRaises(TypeError, _del) self.assertRaises(TypeError, _set) _dict = {} def getitem(s, name): return _dict[name] def setitem(s, name, value): _dict[name] = value def delitem(s, name): del _dict[name] mock.__setitem__ = setitem mock.__getitem__ = getitem mock.__delitem__ = delitem self.assertRaises(KeyError, lambda: mock['foo']) mock['foo'] = 'bar' self.assertEqual(_dict, {'foo': 'bar'}) self.assertEqual(mock['foo'], 'bar') del mock['foo'] self.assertEqual(_dict, {}) def testNumeric(self): original = mock = Mock() mock.value = 0 self.assertRaises(TypeError, lambda: mock + 3) def add(self, other): mock.value += other return self mock.__add__ = add self.assertEqual(mock + 3, mock) self.assertEqual(mock.value, 3) del mock.__add__ def iadd(mock): mock += 3 self.assertRaises(TypeError, iadd, mock) mock.__iadd__ = add mock += 6 self.assertEqual(mock, original) self.assertEqual(mock.value, 9) self.assertRaises(TypeError, lambda: 3 + mock) mock.__radd__ = add self.assertEqual(7 + mock, mock) self.assertEqual(mock.value, 16) def testHash(self): mock = Mock() # test delegation self.assertEqual(hash(mock), Mock.__hash__(mock)) def _hash(s): return 3 mock.__hash__ = _hash self.assertEqual(hash(mock), 3) def testNonZero(self): m = Mock() self.assertTrue(bool(m)) nonzero = lambda s: False if not inPy3k: m.__nonzero__ = nonzero else: m.__bool__ = nonzero self.assertFalse(bool(m)) def testComparison(self): if not inPy3k: # incomparable in Python 3 self. assertEqual(Mock() < 3, object() < 3) self. assertEqual(Mock() > 3, object() > 3) self. assertEqual(Mock() <= 3, object() <= 3) self. assertEqual(Mock() >= 3, object() >= 3) mock = Mock() def comp(s, o): return True mock.__lt__ = mock.__gt__ = mock.__le__ = mock.__ge__ = comp self. assertTrue(mock < 3) self. assertTrue(mock > 3) self. assertTrue(mock <= 3) self. assertTrue(mock >= 3) def testEquality(self): mock = Mock() self.assertEqual(mock, mock) self.assertNotEqual(mock, Mock()) self.assertNotEqual(mock, 3) def eq(self, other): return other == 3 mock.__eq__ = eq self.assertTrue(mock == 3) self.assertFalse(mock == 4) def ne(self, other): return other == 3 mock.__ne__ = ne self.assertTrue(mock != 3) self.assertFalse(mock != 4) def testLenContainsIter(self): mock = Mock() self.assertRaises(TypeError, len, mock) self.assertRaises(TypeError, iter, mock) self.assertRaises(TypeError, lambda: 'foo' in mock) mock.__len__ = lambda s: 6 self.assertEqual(len(mock), 6) mock.__contains__ = lambda s, o: o == 3 self.assertTrue(3 in mock) self.assertFalse(6 in mock) mock.__iter__ = lambda s: iter('foobarbaz') self.assertEqual(list(mock), list('foobarbaz')) def testMagicMock(self): mock = MagicMock() mock.__iter__.return_value = iter([1, 2, 3]) self.assertEqual(list(mock), [1, 2, 3]) if inPy3k: mock.__bool__.return_value = False self.assertFalse(hasattr(mock, '__nonzero__')) else: mock.__nonzero__.return_value = False self.assertFalse(hasattr(mock, '__bool__')) self.assertFalse(bool(mock)) for entry in _magics: self.assertTrue(hasattr(mock, entry)) self.assertFalse(hasattr(mock, '__imaginery__')) def testMagicMockDefaults(self): mock = MagicMock() self.assertEqual(int(mock), 1) self.assertEqual(complex(mock), 1j) self.assertEqual(float(mock), 1.0) self.assertEqual(long(mock), long(1)) self.assertNotIn(object(), mock) self.assertEqual(len(mock), 0) self.assertEqual(list(mock), []) self.assertEqual(hash(mock), object.__hash__(mock)) self.assertEqual(str(mock), object.__str__(mock)) self.assertEqual(unicode(mock), object.__str__(mock)) self.assertIsInstance(unicode(mock), unicode) self.assertTrue(bool(mock)) if not inPy3k: self.assertEqual(oct(mock), '1') else: # in Python 3 oct and hex use __index__ # so these tests are for __index__ in py3k self.assertEqual(oct(mock), '0o1') self.assertEqual(hex(mock), '0x1') # how to test __sizeof__ ? @unittest2.skipIf(inPy3k, "no __cmp__ in Python 3") def testNonDefaultMagicMethods(self): mock = MagicMock() self.assertRaises(AttributeError, lambda: mock.__cmp__) mock = Mock() mock.__cmp__ = lambda s, o: 0 self.assertEqual(mock, object()) def testMagicMethodsAndSpec(self): class Iterable(object): def __iter__(self): pass mock = Mock(spec=Iterable) self.assertRaises(AttributeError, lambda: mock.__iter__) mock.__iter__ = Mock(return_value=iter([])) self.assertEqual(list(mock), []) class NonIterable(object): pass mock = Mock(spec=NonIterable) self.assertRaises(AttributeError, lambda: mock.__iter__) def set_int(): mock.__int__ = Mock(return_value=iter([])) self.assertRaises(AttributeError, set_int) mock = MagicMock(spec=Iterable) self.assertEqual(list(mock), []) self.assertRaises(AttributeError, set_int) def testMagicMethodsAndSpecSet(self): class Iterable(object): def __iter__(self): pass mock = Mock(spec_set=Iterable) self.assertRaises(AttributeError, lambda: mock.__iter__) mock.__iter__ = Mock(return_value=iter([])) self.assertEqual(list(mock), []) class NonIterable(object): pass mock = Mock(spec_set=NonIterable) self.assertRaises(AttributeError, lambda: mock.__iter__) def set_int(): mock.__int__ = Mock(return_value=iter([])) self.assertRaises(AttributeError, set_int) mock = MagicMock(spec_set=Iterable) self.assertEqual(list(mock), []) self.assertRaises(AttributeError, set_int) def testSettingUnsupportedMagicMethod(self): mock = MagicMock() def set_setattr(): mock.__setattr__ = lambda self, name: None self.assertRaisesRegexp(AttributeError, "Attempting to set unsupported magic method '__setattr__'.", set_setattr ) def testAttributesAndReturnValue(self): mock = MagicMock() attr = mock.foo def _get_type(obj): # the type of every mock (or magicmock) is a custom subclass # so the real type is the second in the mro return type(obj).__mro__[1] self.assertEqual(_get_type(attr), MagicMock) returned = mock() self.assertEqual(_get_type(returned), MagicMock) if __name__ == '__main__': unittest2.main()
agpl-3.0
jamesblunt/edx-platform
lms/djangoapps/instructor/management/tests/test_openended_commands.py
106
8584
"""Test the openended_post management command.""" from datetime import datetime import json from mock import patch from pytz import UTC from django.conf import settings from opaque_keys.edx.locations import Location import capa.xqueue_interface as xqueue_interface from courseware.courses import get_course_with_access from courseware.tests.factories import StudentModuleFactory, UserFactory from xmodule.modulestore.django import modulestore from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.xml_importer import import_course_from_xml from xmodule.open_ended_grading_classes.openendedchild import OpenEndedChild from xmodule.tests.test_util_open_ended import ( STATE_INITIAL, STATE_ACCESSING, STATE_POST_ASSESSMENT ) from student.models import anonymous_id_for_user from instructor.management.commands.openended_post import post_submission_for_student from instructor.management.commands.openended_stats import calculate_task_statistics from instructor.utils import get_module_for_student TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT class OpenEndedPostTest(ModuleStoreTestCase): """Test the openended_post management command.""" def setUp(self): super(OpenEndedPostTest, self).setUp() self.user = UserFactory() store = modulestore() course_items = import_course_from_xml(store, self.user.id, TEST_DATA_DIR, ['open_ended']) # pylint: disable=maybe-no-member self.course = course_items[0] self.course_id = self.course.id self.problem_location = Location("edX", "open_ended", "2012_Fall", "combinedopenended", "SampleQuestion") self.self_assessment_task_number = 0 self.open_ended_task_number = 1 self.student_on_initial = UserFactory() self.student_on_accessing = UserFactory() self.student_on_post_assessment = UserFactory() StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_initial, grade=0, max_grade=1, state=STATE_INITIAL ) StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_accessing, grade=0, max_grade=1, state=STATE_ACCESSING ) StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_post_assessment, grade=0, max_grade=1, state=STATE_POST_ASSESSMENT ) def test_post_submission_for_student_on_initial(self): course = get_course_with_access(self.student_on_initial, 'load', self.course_id) dry_run_result = post_submission_for_student(self.student_on_initial, course, self.problem_location, self.open_ended_task_number, dry_run=True) self.assertFalse(dry_run_result) result = post_submission_for_student(self.student_on_initial, course, self.problem_location, self.open_ended_task_number, dry_run=False) self.assertFalse(result) def test_post_submission_for_student_on_accessing(self): course = get_course_with_access(self.student_on_accessing, 'load', self.course_id) dry_run_result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, self.open_ended_task_number, dry_run=True) self.assertFalse(dry_run_result) with patch('capa.xqueue_interface.XQueueInterface.send_to_queue') as mock_send_to_queue: mock_send_to_queue.return_value = (0, "Successfully queued") module = get_module_for_student(self.student_on_accessing, self.problem_location) module.child_module.get_task_number(self.open_ended_task_number) student_response = "Here is an answer." student_anonymous_id = anonymous_id_for_user(self.student_on_accessing, None) submission_time = datetime.strftime(datetime.now(UTC), xqueue_interface.dateformat) result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, self.open_ended_task_number, dry_run=False) self.assertTrue(result) mock_send_to_queue_body_arg = json.loads(mock_send_to_queue.call_args[1]['body']) self.assertEqual(mock_send_to_queue_body_arg['max_score'], 2) self.assertEqual(mock_send_to_queue_body_arg['student_response'], student_response) body_arg_student_info = json.loads(mock_send_to_queue_body_arg['student_info']) self.assertEqual(body_arg_student_info['anonymous_student_id'], student_anonymous_id) self.assertGreaterEqual(body_arg_student_info['submission_time'], submission_time) def test_post_submission_for_student_on_post_assessment(self): course = get_course_with_access(self.student_on_post_assessment, 'load', self.course_id) dry_run_result = post_submission_for_student(self.student_on_post_assessment, course, self.problem_location, self.open_ended_task_number, dry_run=True) self.assertFalse(dry_run_result) result = post_submission_for_student(self.student_on_post_assessment, course, self.problem_location, self.open_ended_task_number, dry_run=False) self.assertFalse(result) def test_post_submission_for_student_invalid_task(self): course = get_course_with_access(self.student_on_accessing, 'load', self.course_id) result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, self.self_assessment_task_number, dry_run=False) self.assertFalse(result) out_of_bounds_task_number = 3 result = post_submission_for_student(self.student_on_accessing, course, self.problem_location, out_of_bounds_task_number, dry_run=False) self.assertFalse(result) class OpenEndedStatsTest(ModuleStoreTestCase): """Test the openended_stats management command.""" def setUp(self): super(OpenEndedStatsTest, self).setUp() self.user = UserFactory() store = modulestore() course_items = import_course_from_xml(store, self.user.id, TEST_DATA_DIR, ['open_ended']) # pylint: disable=maybe-no-member self.course = course_items[0] self.course_id = self.course.id self.problem_location = Location("edX", "open_ended", "2012_Fall", "combinedopenended", "SampleQuestion") self.task_number = 1 self.invalid_task_number = 3 self.student_on_initial = UserFactory() self.student_on_accessing = UserFactory() self.student_on_post_assessment = UserFactory() StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_initial, grade=0, max_grade=1, state=STATE_INITIAL ) StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_accessing, grade=0, max_grade=1, state=STATE_ACCESSING ) StudentModuleFactory.create( course_id=self.course_id, module_state_key=self.problem_location, student=self.student_on_post_assessment, grade=0, max_grade=1, state=STATE_POST_ASSESSMENT ) self.students = [self.student_on_initial, self.student_on_accessing, self.student_on_post_assessment] def test_calculate_task_statistics(self): course = get_course_with_access(self.student_on_accessing, 'load', self.course_id) stats = calculate_task_statistics(self.students, course, self.problem_location, self.task_number, write_to_file=False) self.assertEqual(stats[OpenEndedChild.INITIAL], 1) self.assertEqual(stats[OpenEndedChild.ASSESSING], 1) self.assertEqual(stats[OpenEndedChild.POST_ASSESSMENT], 1) self.assertEqual(stats[OpenEndedChild.DONE], 0) stats = calculate_task_statistics(self.students, course, self.problem_location, self.invalid_task_number, write_to_file=False) self.assertEqual(stats[OpenEndedChild.INITIAL], 0) self.assertEqual(stats[OpenEndedChild.ASSESSING], 0) self.assertEqual(stats[OpenEndedChild.POST_ASSESSMENT], 0) self.assertEqual(stats[OpenEndedChild.DONE], 0)
agpl-3.0
azavea/nyc-trees
src/nyc_trees/apps/users/migrations/0007_auto_20150505_1155.py
3
4985
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import apps.users.models class Migration(migrations.Migration): dependencies = [ ('users', '0006_auto_20150422_1649'), ] operations = [ migrations.AlterField( model_name='achievement', name='achievement_id', field=models.IntegerField(help_text=apps.users.models.achievement_help_text, choices=[(1, 'In Pursuit of Mappiness'), (0, 'Ready, Set, Roll'), (2, 'Treerifically Trained'), (3, 'Counter Cultured'), (4, 'Rolling Revolutionary'), (5, 'Mapping Machine'), (6, 'Sprout Mapper'), (7, 'Seedling Mapper'), (8, 'Sapling Mapper'), (9, 'Mayoral Mapper')]), preserve_default=True, ), migrations.AlterField( model_name='achievement', name='created_at', field=models.DateTimeField(help_text='Time when row was created', auto_now_add=True), preserve_default=True, ), migrations.AlterField( model_name='achievement', name='updated_at', field=models.DateTimeField(help_text='Time when row was last updated', auto_now=True), preserve_default=True, ), migrations.AlterField( model_name='achievement', name='user', field=models.ForeignKey(help_text='ID of user who achieved the achievement', to=settings.AUTH_USER_MODEL), preserve_default=True, ), migrations.AlterField( model_name='follow', name='created_at', field=models.DateTimeField(help_text='Time when row was created', auto_now_add=True), preserve_default=True, ), migrations.AlterField( model_name='follow', name='group', field=models.ForeignKey(help_text='ID of group being followed', to='core.Group'), preserve_default=True, ), migrations.AlterField( model_name='follow', name='updated_at', field=models.DateTimeField(help_text='Time when row was last updated', auto_now=True), preserve_default=True, ), migrations.AlterField( model_name='follow', name='user', field=models.ForeignKey(help_text='ID of user following group', to=settings.AUTH_USER_MODEL), preserve_default=True, ), migrations.AlterField( model_name='trainingresult', name='created_at', field=models.DateTimeField(help_text='Time when row was created', auto_now_add=True), preserve_default=True, ), migrations.AlterField( model_name='trainingresult', name='module_name', field=models.CharField(help_text='Name of quiz', max_length=255), preserve_default=True, ), migrations.AlterField( model_name='trainingresult', name='score', field=models.IntegerField(help_text='Number of questions answered correctly', null=True), preserve_default=True, ), migrations.AlterField( model_name='trainingresult', name='updated_at', field=models.DateTimeField(help_text='Time when row was last updated', auto_now=True), preserve_default=True, ), migrations.AlterField( model_name='trainingresult', name='user', field=models.ForeignKey(help_text='ID of user answering quiz questions', to=settings.AUTH_USER_MODEL), preserve_default=True, ), migrations.AlterField( model_name='trustedmapper', name='created_at', field=models.DateTimeField(help_text='Time when row was created', auto_now_add=True), preserve_default=True, ), migrations.AlterField( model_name='trustedmapper', name='group', field=models.ForeignKey(help_text='ID of group granting mapping permission', to='core.Group'), preserve_default=True, ), migrations.AlterField( model_name='trustedmapper', name='is_approved', field=models.NullBooleanField(help_text='Has mapping permission been granted?'), preserve_default=True, ), migrations.AlterField( model_name='trustedmapper', name='updated_at', field=models.DateTimeField(help_text='Time when row was last updated', auto_now=True), preserve_default=True, ), migrations.AlterField( model_name='trustedmapper', name='user', field=models.ForeignKey(help_text='ID of user requesting mapping permission', to=settings.AUTH_USER_MODEL), preserve_default=True, ), ]
agpl-3.0
rex-xxx/mt6572_x201
external/v8/tools/status-file-converter.py
21
1872
#!/usr/bin/env python # # Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys from testrunner.local import old_statusfile if len(sys.argv) != 2: print "Usage: %s foo.status" % sys.argv[0] print "Will read foo.status and print the converted version to stdout." sys.exit(1) print old_statusfile.ConvertNotation(sys.argv[1]).GetOutput()
gpl-2.0
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.4/Lib/lib-old/grep.py
9
2177
# 'grep' import regex from regex_syntax import * opt_show_where = 0 opt_show_filename = 0 opt_show_lineno = 1 def grep(pat, *files): return ggrep(RE_SYNTAX_GREP, pat, files) def egrep(pat, *files): return ggrep(RE_SYNTAX_EGREP, pat, files) def emgrep(pat, *files): return ggrep(RE_SYNTAX_EMACS, pat, files) def ggrep(syntax, pat, files): if len(files) == 1 and type(files[0]) == type([]): files = files[0] global opt_show_filename opt_show_filename = (len(files) != 1) syntax = regex.set_syntax(syntax) try: prog = regex.compile(pat) finally: syntax = regex.set_syntax(syntax) for filename in files: fp = open(filename, 'r') lineno = 0 while 1: line = fp.readline() if not line: break lineno = lineno + 1 if prog.search(line) >= 0: showline(filename, lineno, line, prog) fp.close() def pgrep(pat, *files): if len(files) == 1 and type(files[0]) == type([]): files = files[0] global opt_show_filename opt_show_filename = (len(files) != 1) import re prog = re.compile(pat) for filename in files: fp = open(filename, 'r') lineno = 0 while 1: line = fp.readline() if not line: break lineno = lineno + 1 if prog.search(line): showline(filename, lineno, line, prog) fp.close() def showline(filename, lineno, line, prog): if line[-1:] == '\n': line = line[:-1] if opt_show_lineno: prefix = `lineno`.rjust(3) + ': ' else: prefix = '' if opt_show_filename: prefix = filename + ': ' + prefix print prefix + line if opt_show_where: start, end = prog.regs()[0] line = line[:start] if '\t' not in line: prefix = ' ' * (len(prefix) + start) else: prefix = ' ' * len(prefix) for c in line: if c != '\t': c = ' ' prefix = prefix + c if start == end: prefix = prefix + '\\' else: prefix = prefix + '^'*(end-start) print prefix
mit
vianuevm/Webparser
ENV/Lib/site-packages/sqlalchemy/orm/session.py
17
83215
# orm/session.py # Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Provides the Session class and related utilities.""" import weakref from itertools import chain from sqlalchemy import util, sql, engine, log, exc as sa_exc from sqlalchemy.sql import util as sql_util, expression from sqlalchemy.orm import ( SessionExtension, attributes, exc, query, unitofwork, util as mapperutil, state ) from sqlalchemy.orm.util import object_mapper as _object_mapper from sqlalchemy.orm.util import class_mapper as _class_mapper from sqlalchemy.orm.util import ( _class_to_mapper, _state_mapper, ) from sqlalchemy.orm.mapper import Mapper, _none_set from sqlalchemy.orm.unitofwork import UOWTransaction from sqlalchemy.orm import identity from sqlalchemy import event from sqlalchemy.orm.events import SessionEvents import sys __all__ = ['Session', 'SessionTransaction', 'SessionExtension'] def sessionmaker(bind=None, class_=None, autoflush=True, autocommit=False, expire_on_commit=True, **kwargs): """Generate a custom-configured :class:`.Session` class. The returned object is a subclass of :class:`.Session`, which, when instantiated with no arguments, uses the keyword arguments configured here as its constructor arguments. It is intended that the :func:`.sessionmaker()` function be called within the global scope of an application, and the returned class be made available to the rest of the application as the single class used to instantiate sessions. e.g.:: # global scope Session = sessionmaker(autoflush=False) # later, in a local scope, create and use a session: sess = Session() Any keyword arguments sent to the constructor itself will override the "configured" keywords:: Session = sessionmaker() # bind an individual session to a connection sess = Session(bind=connection) The class also includes a special classmethod ``configure()``, which allows additional configurational options to take place after the custom ``Session`` class has been generated. This is useful particularly for defining the specific ``Engine`` (or engines) to which new instances of ``Session`` should be bound:: Session = sessionmaker() Session.configure(bind=create_engine('sqlite:///foo.db')) sess = Session() For options, see the constructor options for :class:`.Session`. """ kwargs['bind'] = bind kwargs['autoflush'] = autoflush kwargs['autocommit'] = autocommit kwargs['expire_on_commit'] = expire_on_commit if class_ is None: class_ = Session class Sess(object): def __init__(self, **local_kwargs): for k in kwargs: local_kwargs.setdefault(k, kwargs[k]) super(Sess, self).__init__(**local_kwargs) @classmethod def configure(self, **new_kwargs): """(Re)configure the arguments for this sessionmaker. e.g.:: Session = sessionmaker() Session.configure(bind=create_engine('sqlite://')) """ kwargs.update(new_kwargs) return type("SessionMaker", (Sess, class_), {}) class SessionTransaction(object): """A :class:`.Session`-level transaction. :class:`.SessionTransaction` is a mostly behind-the-scenes object not normally referenced directly by application code. It coordinates among multiple :class:`.Connection` objects, maintaining a database transaction for each one individually, committing or rolling them back all at once. It also provides optional two-phase commit behavior which can augment this coordination operation. The :attr:`.Session.transaction` attribute of :class:`.Session` refers to the current :class:`.SessionTransaction` object in use, if any. A :class:`.SessionTransaction` is associated with a :class:`.Session` in its default mode of ``autocommit=False`` immediately, associated with no database connections. As the :class:`.Session` is called upon to emit SQL on behalf of various :class:`.Engine` or :class:`.Connection` objects, a corresponding :class:`.Connection` and associated :class:`.Transaction` is added to a collection within the :class:`.SessionTransaction` object, becoming one of the connection/transaction pairs maintained by the :class:`.SessionTransaction`. The lifespan of the :class:`.SessionTransaction` ends when the :meth:`.Session.commit`, :meth:`.Session.rollback` or :meth:`.Session.close` methods are called. At this point, the :class:`.SessionTransaction` removes its association with its parent :class:`.Session`. A :class:`.Session` that is in ``autocommit=False`` mode will create a new :class:`.SessionTransaction` to replace it immediately, whereas a :class:`.Session` that's in ``autocommit=True`` mode will remain without a :class:`.SessionTransaction` until the :meth:`.Session.begin` method is called. Another detail of :class:`.SessionTransaction` behavior is that it is capable of "nesting". This means that the :meth:`.begin` method can be called while an existing :class:`.SessionTransaction` is already present, producing a new :class:`.SessionTransaction` that temporarily replaces the parent :class:`.SessionTransaction`. When a :class:`.SessionTransaction` is produced as nested, it assigns itself to the :attr:`.Session.transaction` attribute. When it is ended via :meth:`.Session.commit` or :meth:`.Session.rollback`, it restores its parent :class:`.SessionTransaction` back onto the :attr:`.Session.transaction` attribute. The behavior is effectively a stack, where :attr:`.Session.transaction` refers to the current head of the stack. The purpose of this stack is to allow nesting of :meth:`.rollback` or :meth:`.commit` calls in context with various flavors of :meth:`.begin`. This nesting behavior applies to when :meth:`.Session.begin_nested` is used to emit a SAVEPOINT transaction, and is also used to produce a so-called "subtransaction" which allows a block of code to use a begin/rollback/commit sequence regardless of whether or not its enclosing code block has begun a transaction. The :meth:`.flush` method, whether called explicitly or via autoflush, is the primary consumer of the "subtransaction" feature, in that it wishes to guarantee that it works within in a transaction block regardless of whether or not the :class:`.Session` is in transactional mode when the method is called. See also: :meth:`.Session.rollback` :meth:`.Session.commit` :meth:`.Session.begin` :meth:`.Session.begin_nested` :attr:`.Session.is_active` :meth:`.SessionEvents.after_commit` :meth:`.SessionEvents.after_rollback` :meth:`.SessionEvents.after_soft_rollback` """ _rollback_exception = None def __init__(self, session, parent=None, nested=False): self.session = session self._connections = {} self._parent = parent self.nested = nested self._active = True self._prepared = False if not parent and nested: raise sa_exc.InvalidRequestError( "Can't start a SAVEPOINT transaction when no existing " "transaction is in progress") if self.session._enable_transaction_accounting: self._take_snapshot() @property def is_active(self): return self.session is not None and self._active def _assert_is_active(self): self._assert_is_open() if not self._active: if self._rollback_exception: raise sa_exc.InvalidRequestError( "This Session's transaction has been rolled back " "due to a previous exception during flush." " To begin a new transaction with this Session, " "first issue Session.rollback()." " Original exception was: %s" % self._rollback_exception ) else: raise sa_exc.InvalidRequestError( "This Session's transaction has been rolled back " "by a nested rollback() call. To begin a new " "transaction, issue Session.rollback() first." ) def _assert_is_open(self, error_msg="The transaction is closed"): if self.session is None: raise sa_exc.ResourceClosedError(error_msg) @property def _is_transaction_boundary(self): return self.nested or not self._parent def connection(self, bindkey, **kwargs): self._assert_is_active() engine = self.session.get_bind(bindkey, **kwargs) return self._connection_for_bind(engine) def _begin(self, nested=False): self._assert_is_active() return SessionTransaction( self.session, self, nested=nested) def _iterate_parents(self, upto=None): if self._parent is upto: return (self,) else: if self._parent is None: raise sa_exc.InvalidRequestError( "Transaction %s is not on the active transaction list" % ( upto)) return (self,) + self._parent._iterate_parents(upto) def _take_snapshot(self): if not self._is_transaction_boundary: self._new = self._parent._new self._deleted = self._parent._deleted return if not self.session._flushing: self.session.flush() self._new = weakref.WeakKeyDictionary() self._deleted = weakref.WeakKeyDictionary() def _restore_snapshot(self): assert self._is_transaction_boundary for s in set(self._new).union(self.session._new): self.session._expunge_state(s) if s.key: del s.key for s in set(self._deleted).union(self.session._deleted): if s.deleted: #assert s in self._deleted del s.deleted self.session._update_impl(s) assert not self.session._deleted for s in self.session.identity_map.all_states(): s.expire(s.dict, self.session.identity_map._modified) def _remove_snapshot(self): assert self._is_transaction_boundary if not self.nested and self.session.expire_on_commit: for s in self.session.identity_map.all_states(): s.expire(s.dict, self.session.identity_map._modified) def _connection_for_bind(self, bind): self._assert_is_active() if bind in self._connections: return self._connections[bind][0] if self._parent: conn = self._parent._connection_for_bind(bind) if not self.nested: return conn else: if isinstance(bind, engine.Connection): conn = bind if conn.engine in self._connections: raise sa_exc.InvalidRequestError( "Session already has a Connection associated for the " "given Connection's Engine") else: conn = bind.contextual_connect() if self.session.twophase and self._parent is None: transaction = conn.begin_twophase() elif self.nested: transaction = conn.begin_nested() else: transaction = conn.begin() self._connections[conn] = self._connections[conn.engine] = \ (conn, transaction, conn is not bind) self.session.dispatch.after_begin(self.session, self, conn) return conn def prepare(self): if self._parent is not None or not self.session.twophase: raise sa_exc.InvalidRequestError( "Only root two phase transactions of can be prepared") self._prepare_impl() def _prepare_impl(self): self._assert_is_active() if self._parent is None or self.nested: self.session.dispatch.before_commit(self.session) stx = self.session.transaction if stx is not self: for subtransaction in stx._iterate_parents(upto=self): subtransaction.commit() if not self.session._flushing: for _flush_guard in xrange(100): if self.session._is_clean(): break self.session.flush() else: raise exc.FlushError( "Over 100 subsequent flushes have occurred within " "session.commit() - is an after_flush() hook " "creating new objects?") if self._parent is None and self.session.twophase: try: for t in set(self._connections.values()): t[1].prepare() except: self.rollback() raise self._deactivate() self._prepared = True def commit(self): self._assert_is_open() if not self._prepared: self._prepare_impl() if self._parent is None or self.nested: for t in set(self._connections.values()): t[1].commit() self.session.dispatch.after_commit(self.session) if self.session._enable_transaction_accounting: self._remove_snapshot() self.close() return self._parent def rollback(self, _capture_exception=False): self._assert_is_open() stx = self.session.transaction if stx is not self: for subtransaction in stx._iterate_parents(upto=self): subtransaction.close() if self.is_active or self._prepared: for transaction in self._iterate_parents(): if transaction._parent is None or transaction.nested: transaction._rollback_impl() transaction._deactivate() break else: transaction._deactivate() sess = self.session if self.session._enable_transaction_accounting and \ not sess._is_clean(): # if items were added, deleted, or mutated # here, we need to re-restore the snapshot util.warn( "Session's state has been changed on " "a non-active transaction - this state " "will be discarded.") self._restore_snapshot() self.close() if self._parent and _capture_exception: self._parent._rollback_exception = sys.exc_info()[1] sess.dispatch.after_soft_rollback(sess, self) return self._parent def _rollback_impl(self): for t in set(self._connections.values()): t[1].rollback() if self.session._enable_transaction_accounting: self._restore_snapshot() self.session.dispatch.after_rollback(self.session) def _deactivate(self): self._active = False def close(self): self.session.transaction = self._parent if self._parent is None: for connection, transaction, autoclose in \ set(self._connections.values()): if autoclose: connection.close() else: transaction.close() if not self.session.autocommit: self.session.begin() self._deactivate() self.session = None self._connections = None def __enter__(self): return self def __exit__(self, type, value, traceback): self._assert_is_open("Cannot end transaction context. The transaction " "was closed from within the context") if self.session.transaction is None: return if type is None: try: self.commit() except: self.rollback() raise else: self.rollback() class Session(object): """Manages persistence operations for ORM-mapped objects. The Session's usage paradigm is described at :ref:`session_toplevel`. """ public_methods = ( '__contains__', '__iter__', 'add', 'add_all', 'begin', 'begin_nested', 'close', 'commit', 'connection', 'delete', 'execute', 'expire', 'expire_all', 'expunge', 'expunge_all', 'flush', 'get_bind', 'is_modified', 'merge', 'query', 'refresh', 'rollback', 'scalar') def __init__(self, bind=None, autoflush=True, expire_on_commit=True, _enable_transaction_accounting=True, autocommit=False, twophase=False, weak_identity_map=True, binds=None, extension=None, query_cls=query.Query): """Construct a new Session. See also the :func:`.sessionmaker` function which is used to generate a :class:`.Session`-producing callable with a given set of arguments. :param autocommit: Defaults to ``False``. When ``True``, the ``Session`` does not keep a persistent transaction running, and will acquire connections from the engine on an as-needed basis, returning them immediately after their use. Flushes will begin and commit (or possibly rollback) their own transaction if no transaction is present. When using this mode, the `session.begin()` method may be used to begin a transaction explicitly. Leaving it on its default value of ``False`` means that the ``Session`` will acquire a connection and begin a transaction the first time it is used, which it will maintain persistently until ``rollback()``, ``commit()``, or ``close()`` is called. When the transaction is released by any of these methods, the ``Session`` is ready for the next usage, which will again acquire and maintain a new connection/transaction. :param autoflush: When ``True``, all query operations will issue a ``flush()`` call to this ``Session`` before proceeding. This is a convenience feature so that ``flush()`` need not be called repeatedly in order for database queries to retrieve results. It's typical that ``autoflush`` is used in conjunction with ``autocommit=False``. In this scenario, explicit calls to ``flush()`` are rarely needed; you usually only need to call ``commit()`` (which flushes) to finalize changes. :param bind: An optional ``Engine`` or ``Connection`` to which this ``Session`` should be bound. When specified, all SQL operations performed by this session will execute via this connectable. :param binds: An optional dictionary which contains more granular "bind" information than the ``bind`` parameter provides. This dictionary can map individual ``Table`` instances as well as ``Mapper`` instances to individual ``Engine`` or ``Connection`` objects. Operations which proceed relative to a particular ``Mapper`` will consult this dictionary for the direct ``Mapper`` instance as well as the mapper's ``mapped_table`` attribute in order to locate an connectable to use. The full resolution is described in the ``get_bind()`` method of ``Session``. Usage looks like:: Session = sessionmaker(binds={ SomeMappedClass: create_engine('postgresql://engine1'), somemapper: create_engine('postgresql://engine2'), some_table: create_engine('postgresql://engine3'), }) Also see the :meth:`.Session.bind_mapper` and :meth:`.Session.bind_table` methods. :param \class_: Specify an alternate class other than ``sqlalchemy.orm.session.Session`` which should be used by the returned class. This is the only argument that is local to the ``sessionmaker()`` function, and is not sent directly to the constructor for ``Session``. :param _enable_transaction_accounting: Defaults to ``True``. A legacy-only flag which when ``False`` disables *all* 0.5-style object accounting on transaction boundaries, including auto-expiry of instances on rollback and commit, maintenance of the "new" and "deleted" lists upon rollback, and autoflush of pending changes upon begin(), all of which are interdependent. :param expire_on_commit: Defaults to ``True``. When ``True``, all instances will be fully expired after each ``commit()``, so that all attribute/object access subsequent to a completed transaction will load from the most recent database state. :param extension: An optional :class:`~.SessionExtension` instance, or a list of such instances, which will receive pre- and post- commit and flush events, as well as a post-rollback event. **Deprecated.** Please see :class:`.SessionEvents`. :param query_cls: Class which should be used to create new Query objects, as returned by the ``query()`` method. Defaults to :class:`~sqlalchemy.orm.query.Query`. :param twophase: When ``True``, all transactions will be started as a "two phase" transaction, i.e. using the "two phase" semantics of the database in use along with an XID. During a ``commit()``, after ``flush()`` has been issued for all attached databases, the ``prepare()`` method on each database's ``TwoPhaseTransaction`` will be called. This allows each database to roll back the entire transaction, before each transaction is committed. :param weak_identity_map: Defaults to ``True`` - when set to ``False``, objects placed in the :class:`.Session` will be strongly referenced until explicitly removed or the :class:`.Session` is closed. **Deprecated** - this option is obsolete. """ if weak_identity_map: self._identity_cls = identity.WeakInstanceDict else: util.warn_deprecated("weak_identity_map=False is deprecated. " "This feature is not needed.") self._identity_cls = identity.StrongInstanceDict self.identity_map = self._identity_cls() self._new = {} # InstanceState->object, strong refs object self._deleted = {} # same self.bind = bind self.__binds = {} self._flushing = False self.transaction = None self.hash_key = _new_sessionid() self.autoflush = autoflush self.autocommit = autocommit self.expire_on_commit = expire_on_commit self._enable_transaction_accounting = _enable_transaction_accounting self.twophase = twophase self._query_cls = query_cls if extension: for ext in util.to_list(extension): SessionExtension._adapt_listener(self, ext) if binds is not None: for mapperortable, bind in binds.iteritems(): if isinstance(mapperortable, (type, Mapper)): self.bind_mapper(mapperortable, bind) else: self.bind_table(mapperortable, bind) if not self.autocommit: self.begin() _sessions[self.hash_key] = self dispatch = event.dispatcher(SessionEvents) connection_callable = None transaction = None """The current active or inactive :class:`.SessionTransaction`.""" def begin(self, subtransactions=False, nested=False): """Begin a transaction on this Session. If this Session is already within a transaction, either a plain transaction or nested transaction, an error is raised, unless ``subtransactions=True`` or ``nested=True`` is specified. The ``subtransactions=True`` flag indicates that this :meth:`~.Session.begin` can create a subtransaction if a transaction is already in progress. For documentation on subtransactions, please see :ref:`session_subtransactions`. The ``nested`` flag begins a SAVEPOINT transaction and is equivalent to calling :meth:`~.Session.begin_nested`. For documentation on SAVEPOINT transactions, please see :ref:`session_begin_nested`. """ if self.transaction is not None: if subtransactions or nested: self.transaction = self.transaction._begin( nested=nested) else: raise sa_exc.InvalidRequestError( "A transaction is already begun. Use subtransactions=True " "to allow subtransactions.") else: self.transaction = SessionTransaction( self, nested=nested) return self.transaction # needed for __enter__/__exit__ hook def begin_nested(self): """Begin a `nested` transaction on this Session. The target database(s) must support SQL SAVEPOINTs or a SQLAlchemy-supported vendor implementation of the idea. For documentation on SAVEPOINT transactions, please see :ref:`session_begin_nested`. """ return self.begin(nested=True) def rollback(self): """Rollback the current transaction in progress. If no transaction is in progress, this method is a pass-through. This method rolls back the current transaction or nested transaction regardless of subtransactions being in effect. All subtransactions up to the first real transaction are closed. Subtransactions occur when begin() is called multiple times. """ if self.transaction is None: pass else: self.transaction.rollback() def commit(self): """Flush pending changes and commit the current transaction. If no transaction is in progress, this method raises an InvalidRequestError. By default, the :class:`.Session` also expires all database loaded state on all ORM-managed attributes after transaction commit. This so that subsequent operations load the most recent data from the database. This behavior can be disabled using the ``expire_on_commit=False`` option to :func:`.sessionmaker` or the :class:`.Session` constructor. If a subtransaction is in effect (which occurs when begin() is called multiple times), the subtransaction will be closed, and the next call to ``commit()`` will operate on the enclosing transaction. For a session configured with autocommit=False, a new transaction will be begun immediately after the commit, but note that the newly begun transaction does *not* use any connection resources until the first SQL is actually emitted. """ if self.transaction is None: if not self.autocommit: self.begin() else: raise sa_exc.InvalidRequestError("No transaction is begun.") self.transaction.commit() def prepare(self): """Prepare the current transaction in progress for two phase commit. If no transaction is in progress, this method raises an InvalidRequestError. Only root transactions of two phase sessions can be prepared. If the current transaction is not such, an InvalidRequestError is raised. """ if self.transaction is None: if not self.autocommit: self.begin() else: raise sa_exc.InvalidRequestError("No transaction is begun.") self.transaction.prepare() def connection(self, mapper=None, clause=None, bind=None, close_with_result=False, **kw): """Return a :class:`.Connection` object corresponding to this :class:`.Session` object's transactional state. If this :class:`.Session` is configured with ``autocommit=False``, either the :class:`.Connection` corresponding to the current transaction is returned, or if no transaction is in progress, a new one is begun and the :class:`.Connection` returned (note that no transactional state is established with the DBAPI until the first SQL statement is emitted). Alternatively, if this :class:`.Session` is configured with ``autocommit=True``, an ad-hoc :class:`.Connection` is returned using :meth:`.Engine.contextual_connect` on the underlying :class:`.Engine`. Ambiguity in multi-bind or unbound :class:`.Session` objects can be resolved through any of the optional keyword arguments. This ultimately makes usage of the :meth:`.get_bind` method for resolution. :param bind: Optional :class:`.Engine` to be used as the bind. If this engine is already involved in an ongoing transaction, that connection will be used. This argument takes precedence over ``mapper``, ``clause``. :param mapper: Optional :func:`.mapper` mapped class, used to identify the appropriate bind. This argument takes precedence over ``clause``. :param clause: A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`, :func:`~.sql.expression.text`, etc.) which will be used to locate a bind, if a bind cannot otherwise be identified. :param close_with_result: Passed to :meth:`Engine.connect`, indicating the :class:`.Connection` should be considered "single use", automatically closing when the first result set is closed. This flag only has an effect if this :class:`.Session` is configured with ``autocommit=True`` and does not already have a transaction in progress. :param \**kw: Additional keyword arguments are sent to :meth:`get_bind()`, allowing additional arguments to be passed to custom implementations of :meth:`get_bind`. """ if bind is None: bind = self.get_bind(mapper, clause=clause, **kw) return self._connection_for_bind(bind, close_with_result=close_with_result) def _connection_for_bind(self, engine, **kwargs): if self.transaction is not None: return self.transaction._connection_for_bind(engine) else: return engine.contextual_connect(**kwargs) def execute(self, clause, params=None, mapper=None, bind=None, **kw): """Execute a SQL expression construct or string statement within the current transaction. Returns a :class:`.ResultProxy` representing results of the statement execution, in the same manner as that of an :class:`.Engine` or :class:`.Connection`. E.g.:: result = session.execute( user_table.select().where(user_table.c.id == 5) ) :meth:`~.Session.execute` accepts any executable clause construct, such as :func:`~.sql.expression.select`, :func:`~.sql.expression.insert`, :func:`~.sql.expression.update`, :func:`~.sql.expression.delete`, and :func:`~.sql.expression.text`. Plain SQL strings can be passed as well, which in the case of :meth:`.Session.execute` only will be interpreted the same as if it were passed via a :func:`~.expression.text` construct. That is, the following usage:: result = session.execute( "SELECT * FROM user WHERE id=:param", {"param":5} ) is equivalent to:: from sqlalchemy import text result = session.execute( text("SELECT * FROM user WHERE id=:param"), {"param":5} ) The second positional argument to :meth:`.Session.execute` is an optional parameter set. Similar to that of :meth:`.Connection.execute`, whether this is passed as a single dictionary, or a list of dictionaries, determines whether the DBAPI cursor's ``execute()`` or ``executemany()`` is used to execute the statement. An INSERT construct may be invoked for a single row:: result = session.execute(users.insert(), {"id": 7, "name": "somename"}) or for multiple rows:: result = session.execute(users.insert(), [ {"id": 7, "name": "somename7"}, {"id": 8, "name": "somename8"}, {"id": 9, "name": "somename9"} ]) The statement is executed within the current transactional context of this :class:`.Session`. The :class:`.Connection` which is used to execute the statement can also be acquired directly by calling the :meth:`.Session.connection` method. Both methods use a rule-based resolution scheme in order to determine the :class:`.Connection`, which in the average case is derived directly from the "bind" of the :class:`.Session` itself, and in other cases can be based on the :func:`.mapper` and :class:`.Table` objects passed to the method; see the documentation for :meth:`.Session.get_bind` for a full description of this scheme. The :meth:`.Session.execute` method does *not* invoke autoflush. The :class:`.ResultProxy` returned by the :meth:`.Session.execute` method is returned with the "close_with_result" flag set to true; the significance of this flag is that if this :class:`.Session` is autocommitting and does not have a transaction-dedicated :class:`.Connection` available, a temporary :class:`.Connection` is established for the statement execution, which is closed (meaning, returned to the connection pool) when the :class:`.ResultProxy` has consumed all available data. This applies *only* when the :class:`.Session` is configured with autocommit=True and no transaction has been started. :param clause: An executable statement (i.e. an :class:`.Executable` expression such as :func:`.expression.select`) or string SQL statement to be executed. :param params: Optional dictionary, or list of dictionaries, containing bound parameter values. If a single dictionary, single-row execution occurs; if a list of dictionaries, an "executemany" will be invoked. The keys in each dictionary must correspond to parameter names present in the statement. :param mapper: Optional :func:`.mapper` or mapped class, used to identify the appropriate bind. This argument takes precedence over ``clause`` when locating a bind. See :meth:`.Session.get_bind` for more details. :param bind: Optional :class:`.Engine` to be used as the bind. If this engine is already involved in an ongoing transaction, that connection will be used. This argument takes precedence over ``mapper`` and ``clause`` when locating a bind. :param \**kw: Additional keyword arguments are sent to :meth:`.Session.get_bind()` to allow extensibility of "bind" schemes. .. seealso:: :ref:`sqlexpression_toplevel` - Tutorial on using Core SQL constructs. :ref:`connections_toplevel` - Further information on direct statement execution. :meth:`.Connection.execute` - core level statement execution method, which is :meth:`.Session.execute` ultimately uses in order to execute the statement. """ clause = expression._literal_as_text(clause) if bind is None: bind = self.get_bind(mapper, clause=clause, **kw) return self._connection_for_bind(bind, close_with_result=True).execute( clause, params or {}) def scalar(self, clause, params=None, mapper=None, bind=None, **kw): """Like :meth:`~.Session.execute` but return a scalar result.""" return self.execute(clause, params=params, mapper=mapper, bind=bind, **kw).scalar() def close(self): """Close this Session. This clears all items and ends any transaction in progress. If this session were created with ``autocommit=False``, a new transaction is immediately begun. Note that this new transaction does not use any connection resources until they are first needed. """ self.expunge_all() if self.transaction is not None: for transaction in self.transaction._iterate_parents(): transaction.close() @classmethod def close_all(cls): """Close *all* sessions in memory.""" for sess in _sessions.values(): sess.close() def expunge_all(self): """Remove all object instances from this ``Session``. This is equivalent to calling ``expunge(obj)`` on all objects in this ``Session``. """ for state in self.identity_map.all_states() + list(self._new): state.detach() self.identity_map = self._identity_cls() self._new = {} self._deleted = {} # TODO: need much more test coverage for bind_mapper() and similar ! # TODO: + crystalize + document resolution order vis. bind_mapper/bind_table def bind_mapper(self, mapper, bind): """Bind operations for a mapper to a Connectable. mapper A mapper instance or mapped class bind Any Connectable: a ``Engine`` or ``Connection``. All subsequent operations involving this mapper will use the given `bind`. """ if isinstance(mapper, type): mapper = _class_mapper(mapper) self.__binds[mapper.base_mapper] = bind for t in mapper._all_tables: self.__binds[t] = bind def bind_table(self, table, bind): """Bind operations on a Table to a Connectable. table A ``Table`` instance bind Any Connectable: a ``Engine`` or ``Connection``. All subsequent operations involving this ``Table`` will use the given `bind`. """ self.__binds[table] = bind def get_bind(self, mapper=None, clause=None): """Return a "bind" to which this :class:`.Session` is bound. The "bind" is usually an instance of :class:`.Engine`, except in the case where the :class:`.Session` has been explicitly bound directly to a :class:`.Connection`. For a multiply-bound or unbound :class:`.Session`, the ``mapper`` or ``clause`` arguments are used to determine the appropriate bind to return. Note that the "mapper" argument is usually present when :meth:`.Session.get_bind` is called via an ORM operation such as a :meth:`.Session.query`, each individual INSERT/UPDATE/DELETE operation within a :meth:`.Session.flush`, call, etc. The order of resolution is: 1. if mapper given and session.binds is present, locate a bind based on mapper. 2. if clause given and session.binds is present, locate a bind based on :class:`.Table` objects found in the given clause present in session.binds. 3. if session.bind is present, return that. 4. if clause given, attempt to return a bind linked to the :class:`.MetaData` ultimately associated with the clause. 5. if mapper given, attempt to return a bind linked to the :class:`.MetaData` ultimately associated with the :class:`.Table` or other selectable to which the mapper is mapped. 6. No bind can be found, :class:`.UnboundExecutionError` is raised. :param mapper: Optional :func:`.mapper` mapped class or instance of :class:`.Mapper`. The bind can be derived from a :class:`.Mapper` first by consulting the "binds" map associated with this :class:`.Session`, and secondly by consulting the :class:`.MetaData` associated with the :class:`.Table` to which the :class:`.Mapper` is mapped for a bind. :param clause: A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`, :func:`~.sql.expression.text`, etc.). If the ``mapper`` argument is not present or could not produce a bind, the given expression construct will be searched for a bound element, typically a :class:`.Table` associated with bound :class:`.MetaData`. """ if mapper is clause is None: if self.bind: return self.bind else: raise sa_exc.UnboundExecutionError( "This session is not bound to a single Engine or " "Connection, and no context was provided to locate " "a binding.") c_mapper = mapper is not None and _class_to_mapper(mapper) or None # manually bound? if self.__binds: if c_mapper: if c_mapper.base_mapper in self.__binds: return self.__binds[c_mapper.base_mapper] elif c_mapper.mapped_table in self.__binds: return self.__binds[c_mapper.mapped_table] if clause is not None: for t in sql_util.find_tables(clause, include_crud=True): if t in self.__binds: return self.__binds[t] if self.bind: return self.bind if isinstance(clause, sql.expression.ClauseElement) and clause.bind: return clause.bind if c_mapper and c_mapper.mapped_table.bind: return c_mapper.mapped_table.bind context = [] if mapper is not None: context.append('mapper %s' % c_mapper) if clause is not None: context.append('SQL expression') raise sa_exc.UnboundExecutionError( "Could not locate a bind configured on %s or this Session" % ( ', '.join(context))) def query(self, *entities, **kwargs): """Return a new ``Query`` object corresponding to this ``Session``.""" return self._query_cls(entities, self, **kwargs) @property @util.contextmanager def no_autoflush(self): """Return a context manager that disables autoflush. e.g.:: with session.no_autoflush: some_object = SomeClass() session.add(some_object) # won't autoflush some_object.related_thing = session.query(SomeRelated).first() Operations that proceed within the ``with:`` block will not be subject to flushes occurring upon query access. This is useful when initializing a series of objects which involve existing database queries, where the uncompleted object should not yet be flushed. .. versionadded:: 0.7.6 """ autoflush = self.autoflush self.autoflush = False yield self self.autoflush = autoflush def _autoflush(self): if self.autoflush and not self._flushing: self.flush() def _finalize_loaded(self, states): for state, dict_ in states.items(): state.commit_all(dict_, self.identity_map) def refresh(self, instance, attribute_names=None, lockmode=None): """Expire and refresh the attributes on the given instance. A query will be issued to the database and all attributes will be refreshed with their current database value. Lazy-loaded relational attributes will remain lazily loaded, so that the instance-wide refresh operation will be followed immediately by the lazy load of that attribute. Eagerly-loaded relational attributes will eagerly load within the single refresh operation. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction - usage of :meth:`~Session.refresh` usually only makes sense if non-ORM SQL statement were emitted in the ongoing transaction, or if autocommit mode is turned on. :param attribute_names: optional. An iterable collection of string attribute names indicating a subset of attributes to be refreshed. :param lockmode: Passed to the :class:`~sqlalchemy.orm.query.Query` as used by :meth:`~sqlalchemy.orm.query.Query.with_lockmode`. """ try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) self._expire_state(state, attribute_names) if self.query(_object_mapper(instance))._load_on_ident( state.key, refresh_state=state, lockmode=lockmode, only_load_props=attribute_names) is None: raise sa_exc.InvalidRequestError( "Could not refresh instance '%s'" % mapperutil.instance_str(instance)) def expire_all(self): """Expires all persistent instances within this Session. When any attributes on a persistent instance is next accessed, a query will be issued using the :class:`.Session` object's current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction. To expire individual objects and individual attributes on those objects, use :meth:`Session.expire`. The :class:`.Session` object's default behavior is to expire all state whenever the :meth:`Session.rollback` or :meth:`Session.commit` methods are called, so that new state can be loaded for the new transaction. For this reason, calling :meth:`Session.expire_all` should not be needed when autocommit is ``False``, assuming the transaction is isolated. """ for state in self.identity_map.all_states(): state.expire(state.dict, self.identity_map._modified) def expire(self, instance, attribute_names=None): """Expire the attributes on an instance. Marks the attributes of an instance as out of date. When an expired attribute is next accessed, a query will be issued to the :class:`.Session` object's current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction. To expire all objects in the :class:`.Session` simultaneously, use :meth:`Session.expire_all`. The :class:`.Session` object's default behavior is to expire all state whenever the :meth:`Session.rollback` or :meth:`Session.commit` methods are called, so that new state can be loaded for the new transaction. For this reason, calling :meth:`Session.expire` only makes sense for the specific case that a non-ORM SQL statement was emitted in the current transaction. :param instance: The instance to be refreshed. :param attribute_names: optional list of string attribute names indicating a subset of attributes to be expired. """ try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) self._expire_state(state, attribute_names) def _expire_state(self, state, attribute_names): self._validate_persistent(state) if attribute_names: state.expire_attributes(state.dict, attribute_names) else: # pre-fetch the full cascade since the expire is going to # remove associations cascaded = list(state.manager.mapper.cascade_iterator( 'refresh-expire', state)) self._conditional_expire(state) for o, m, st_, dct_ in cascaded: self._conditional_expire(st_) def _conditional_expire(self, state): """Expire a state if persistent, else expunge if pending""" if state.key: state.expire(state.dict, self.identity_map._modified) elif state in self._new: self._new.pop(state) state.detach() @util.deprecated("0.7", "The non-weak-referencing identity map " "feature is no longer needed.") def prune(self): """Remove unreferenced instances cached in the identity map. Note that this method is only meaningful if "weak_identity_map" is set to False. The default weak identity map is self-pruning. Removes any object in this Session's identity map that is not referenced in user code, modified, new or scheduled for deletion. Returns the number of objects pruned. """ return self.identity_map.prune() def expunge(self, instance): """Remove the `instance` from this ``Session``. This will free all internal references to the instance. Cascading will be applied according to the *expunge* cascade rule. """ try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) if state.session_id is not self.hash_key: raise sa_exc.InvalidRequestError( "Instance %s is not present in this Session" % mapperutil.state_str(state)) cascaded = list(state.manager.mapper.cascade_iterator( 'expunge', state)) self._expunge_state(state) for o, m, st_, dct_ in cascaded: self._expunge_state(st_) def _expunge_state(self, state): if state in self._new: self._new.pop(state) state.detach() elif self.identity_map.contains_state(state): self.identity_map.discard(state) self._deleted.pop(state, None) state.detach() elif self.transaction: self.transaction._deleted.pop(state, None) def _register_newly_persistent(self, state): mapper = _state_mapper(state) # prevent against last minute dereferences of the object obj = state.obj() if obj is not None: instance_key = mapper._identity_key_from_state(state) if _none_set.issubset(instance_key[1]) and \ not mapper.allow_partial_pks or \ _none_set.issuperset(instance_key[1]): raise exc.FlushError( "Instance %s has a NULL identity key. If this is an " "auto-generated value, check that the database table " "allows generation of new primary key values, and that " "the mapped Column object is configured to expect these " "generated values. Ensure also that this flush() is " "not occurring at an inappropriate time, such as within " "a load() event." % mapperutil.state_str(state) ) if state.key is None: state.key = instance_key elif state.key != instance_key: # primary key switch. use discard() in case another # state has already replaced this one in the identity # map (see test/orm/test_naturalpks.py ReversePKsTest) self.identity_map.discard(state) state.key = instance_key self.identity_map.replace(state) state.commit_all(state.dict, self.identity_map) # remove from new last, might be the last strong ref if state in self._new: if self._enable_transaction_accounting and self.transaction: self.transaction._new[state] = True self._new.pop(state) def _remove_newly_deleted(self, state): if self._enable_transaction_accounting and self.transaction: self.transaction._deleted[state] = True self.identity_map.discard(state) self._deleted.pop(state, None) state.deleted = True def add(self, instance): """Place an object in the ``Session``. Its state will be persisted to the database on the next flush operation. Repeated calls to ``add()`` will be ignored. The opposite of ``add()`` is ``expunge()``. """ try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) self._save_or_update_state(state) def add_all(self, instances): """Add the given collection of instances to this ``Session``.""" for instance in instances: self.add(instance) def _save_or_update_state(self, state): self._save_or_update_impl(state) mapper = _state_mapper(state) for o, m, st_, dct_ in mapper.cascade_iterator( 'save-update', state, halt_on=self._contains_state): self._save_or_update_impl(st_) def delete(self, instance): """Mark an instance as deleted. The database delete operation occurs upon ``flush()``. """ try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) if state.key is None: raise sa_exc.InvalidRequestError( "Instance '%s' is not persisted" % mapperutil.state_str(state)) if state in self._deleted: return # ensure object is attached to allow the # cascade operation to load deferred attributes # and collections self._attach(state) # grab the cascades before adding the item to the deleted list # so that autoflush does not delete the item # the strong reference to the instance itself is significant here cascade_states = list(state.manager.mapper.cascade_iterator( 'delete', state)) self._deleted[state] = state.obj() self.identity_map.add(state) for o, m, st_, dct_ in cascade_states: self._delete_impl(st_) def merge(self, instance, load=True, **kw): """Copy the state of a given instance into a corresponding instance within this :class:`.Session`. :meth:`.Session.merge` examines the primary key attributes of the source instance, and attempts to reconcile it with an instance of the same primary key in the session. If not found locally, it attempts to load the object from the database based on primary key, and if none can be located, creates a new instance. The state of each attribute on the source instance is then copied to the target instance. The resulting target instance is then returned by the method; the original source instance is left unmodified, and un-associated with the :class:`.Session` if not already. This operation cascades to associated instances if the association is mapped with ``cascade="merge"``. See :ref:`unitofwork_merging` for a detailed discussion of merging. :param instance: Instance to be merged. :param load: Boolean, when False, :meth:`.merge` switches into a "high performance" mode which causes it to forego emitting history events as well as all database access. This flag is used for cases such as transferring graphs of objects into a :class:`.Session` from a second level cache, or to transfer just-loaded objects into the :class:`.Session` owned by a worker thread or process without re-querying the database. The ``load=False`` use case adds the caveat that the given object has to be in a "clean" state, that is, has no pending changes to be flushed - even if the incoming object is detached from any :class:`.Session`. This is so that when the merge operation populates local attributes and cascades to related objects and collections, the values can be "stamped" onto the target object as is, without generating any history or attribute events, and without the need to reconcile the incoming data with any existing related objects or collections that might not be loaded. The resulting objects from ``load=False`` are always produced as "clean", so it is only appropriate that the given objects should be "clean" as well, else this suggests a mis-use of the method. """ if 'dont_load' in kw: load = not kw['dont_load'] util.warn_deprecated('dont_load=True has been renamed to ' 'load=False.') _recursive = {} if load: # flush current contents if we expect to load data self._autoflush() _object_mapper(instance) # verify mapped autoflush = self.autoflush try: self.autoflush = False return self._merge( attributes.instance_state(instance), attributes.instance_dict(instance), load=load, _recursive=_recursive) finally: self.autoflush = autoflush def _merge(self, state, state_dict, load=True, _recursive=None): mapper = _state_mapper(state) if state in _recursive: return _recursive[state] new_instance = False key = state.key if key is None: if not load: raise sa_exc.InvalidRequestError( "merge() with load=False option does not support " "objects transient (i.e. unpersisted) objects. flush() " "all changes on mapped instances before merging with " "load=False.") key = mapper._identity_key_from_state(state) if key in self.identity_map: merged = self.identity_map[key] elif not load: if state.modified: raise sa_exc.InvalidRequestError( "merge() with load=False option does not support " "objects marked as 'dirty'. flush() all changes on " "mapped instances before merging with load=False.") merged = mapper.class_manager.new_instance() merged_state = attributes.instance_state(merged) merged_state.key = key self._update_impl(merged_state) new_instance = True elif not _none_set.issubset(key[1]) or \ (mapper.allow_partial_pks and not _none_set.issuperset(key[1])): merged = self.query(mapper.class_).get(key[1]) else: merged = None if merged is None: merged = mapper.class_manager.new_instance() merged_state = attributes.instance_state(merged) merged_dict = attributes.instance_dict(merged) new_instance = True self._save_or_update_state(merged_state) else: merged_state = attributes.instance_state(merged) merged_dict = attributes.instance_dict(merged) _recursive[state] = merged # check that we didn't just pull the exact same # state out. if state is not merged_state: # version check if applicable if mapper.version_id_col is not None: existing_version = mapper._get_state_attr_by_column( state, state_dict, mapper.version_id_col, passive=attributes.PASSIVE_NO_INITIALIZE) merged_version = mapper._get_state_attr_by_column( merged_state, merged_dict, mapper.version_id_col, passive=attributes.PASSIVE_NO_INITIALIZE) if existing_version is not attributes.PASSIVE_NO_RESULT and \ merged_version is not attributes.PASSIVE_NO_RESULT and \ existing_version != merged_version: raise exc.StaleDataError( "Version id '%s' on merged state %s " "does not match existing version '%s'. " "Leave the version attribute unset when " "merging to update the most recent version." % ( existing_version, mapperutil.state_str(merged_state), merged_version )) merged_state.load_path = state.load_path merged_state.load_options = state.load_options for prop in mapper.iterate_properties: prop.merge(self, state, state_dict, merged_state, merged_dict, load, _recursive) if not load: # remove any history merged_state.commit_all(merged_dict, self.identity_map) if new_instance: merged_state.manager.dispatch.load(merged_state, None) return merged @classmethod def identity_key(cls, *args, **kwargs): return mapperutil.identity_key(*args, **kwargs) @classmethod def object_session(cls, instance): """Return the ``Session`` to which an object belongs.""" return object_session(instance) def _validate_persistent(self, state): if not self.identity_map.contains_state(state): raise sa_exc.InvalidRequestError( "Instance '%s' is not persistent within this Session" % mapperutil.state_str(state)) def _save_impl(self, state): if state.key is not None: raise sa_exc.InvalidRequestError( "Object '%s' already has an identity - it can't be registered " "as pending" % mapperutil.state_str(state)) self._attach(state) if state not in self._new: self._new[state] = state.obj() state.insert_order = len(self._new) def _update_impl(self, state): if (self.identity_map.contains_state(state) and state not in self._deleted): return if state.key is None: raise sa_exc.InvalidRequestError( "Instance '%s' is not persisted" % mapperutil.state_str(state)) if state.deleted: raise sa_exc.InvalidRequestError( "Instance '%s' has been deleted. Use the make_transient() " "function to send this object back to the transient state." % mapperutil.state_str(state) ) self._attach(state) self._deleted.pop(state, None) self.identity_map.add(state) def _save_or_update_impl(self, state): if state.key is None: self._save_impl(state) else: self._update_impl(state) def _delete_impl(self, state): if state in self._deleted: return if state.key is None: return self._attach(state) self._deleted[state] = state.obj() self.identity_map.add(state) def _attach(self, state): if state.key and \ state.key in self.identity_map and \ not self.identity_map.contains_state(state): raise sa_exc.InvalidRequestError("Can't attach instance " "%s; another instance with key %s is already " "present in this session." % (mapperutil.state_str(state), state.key)) if state.session_id and \ state.session_id is not self.hash_key and \ state.session_id in _sessions: raise sa_exc.InvalidRequestError( "Object '%s' is already attached to session '%s' " "(this is '%s')" % (mapperutil.state_str(state), state.session_id, self.hash_key)) if state.session_id != self.hash_key: state.session_id = self.hash_key if self.dispatch.after_attach: self.dispatch.after_attach(self, state.obj()) def __contains__(self, instance): """Return True if the instance is associated with this session. The instance may be pending or persistent within the Session for a result of True. """ try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) return self._contains_state(state) def __iter__(self): """Iterate over all pending or persistent instances within this Session.""" return iter(list(self._new.values()) + self.identity_map.values()) def _contains_state(self, state): return state in self._new or self.identity_map.contains_state(state) def flush(self, objects=None): """Flush all the object changes to the database. Writes out all pending object creations, deletions and modifications to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are automatically ordered by the Session's unit of work dependency solver. Database operations will be issued in the current transactional context and do not affect the state of the transaction, unless an error occurs, in which case the entire transaction is rolled back. You may flush() as often as you like within a transaction to move changes from Python to the database's transaction buffer. For ``autocommit`` Sessions with no active manual transaction, flush() will create a transaction on the fly that surrounds the entire set of operations int the flush. :param objects: Optional; restricts the flush operation to operate only on elements that are in the given collection. This feature is for an extremely narrow set of use cases where particular objects may need to be operated upon before the full flush() occurs. It is not intended for general use. """ if self._flushing: raise sa_exc.InvalidRequestError("Session is already flushing") if self._is_clean(): return try: self._flushing = True self._flush(objects) finally: self._flushing = False def _is_clean(self): return not self.identity_map.check_modified() and \ not self._deleted and \ not self._new def _flush(self, objects=None): dirty = self._dirty_states if not dirty and not self._deleted and not self._new: self.identity_map._modified.clear() return flush_context = UOWTransaction(self) if self.dispatch.before_flush: self.dispatch.before_flush(self, flush_context, objects) # re-establish "dirty states" in case the listeners # added dirty = self._dirty_states deleted = set(self._deleted) new = set(self._new) dirty = set(dirty).difference(deleted) # create the set of all objects we want to operate upon if objects: # specific list passed in objset = set() for o in objects: try: state = attributes.instance_state(o) except exc.NO_STATE: raise exc.UnmappedInstanceError(o) objset.add(state) else: objset = None # store objects whose fate has been decided processed = set() # put all saves/updates into the flush context. detect top-level # orphans and throw them into deleted. if objset: proc = new.union(dirty).intersection(objset).difference(deleted) else: proc = new.union(dirty).difference(deleted) for state in proc: is_orphan = _state_mapper(state)._is_orphan(state) and state.has_identity flush_context.register_object(state, isdelete=is_orphan) processed.add(state) # put all remaining deletes into the flush context. if objset: proc = deleted.intersection(objset).difference(processed) else: proc = deleted.difference(processed) for state in proc: flush_context.register_object(state, isdelete=True) if not flush_context.has_work: return flush_context.transaction = transaction = self.begin( subtransactions=True) try: flush_context.execute() self.dispatch.after_flush(self, flush_context) flush_context.finalize_flush_changes() # useful assertions: #if not objects: # assert not self.identity_map._modified #else: # assert self.identity_map._modified == \ # self.identity_map._modified.difference(objects) self.dispatch.after_flush_postexec(self, flush_context) transaction.commit() except: transaction.rollback(_capture_exception=True) raise def is_modified(self, instance, include_collections=True, passive=attributes.PASSIVE_OFF): """Return ``True`` if the given instance has locally modified attributes. This method retrieves the history for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value, if any. It is in effect a more expensive and accurate version of checking for the given instance in the :attr:`.Session.dirty` collection; a full test for each attribute's net "dirty" status is performed. E.g.:: return session.is_modified(someobject, passive=True) .. versionchanged:: 0.8 In SQLAlchemy 0.7 and earlier, the ``passive`` flag should **always** be explicitly set to ``True``. The current default value of :data:`.attributes.PASSIVE_OFF` for this flag is incorrect, in that it loads unloaded collections and attributes which by definition have no modified state, and furthermore trips off autoflush which then causes all subsequent, possibly modified attributes to lose their modified state. The default value of the flag will be changed in 0.8. A few caveats to this method apply: * Instances present in the :attr:`.Session.dirty` collection may report ``False`` when tested with this method. This is because the object may have received change events via attribute mutation, thus placing it in :attr:`.Session.dirty`, but ultimately the state is the same as that loaded from the database, resulting in no net change here. * Scalar attributes may not have recorded the previously set value when a new value was applied, if the attribute was not loaded, or was expired, at the time the new value was received - in these cases, the attribute is assumed to have a change, even if there is ultimately no net change against its database value. SQLAlchemy in most cases does not need the "old" value when a set event occurs, so it skips the expense of a SQL call if the old value isn't present, based on the assumption that an UPDATE of the scalar value is usually needed, and in those few cases where it isn't, is less expensive on average than issuing a defensive SELECT. The "old" value is fetched unconditionally only if the attribute container has the ``active_history`` flag set to ``True``. This flag is set typically for primary key attributes and scalar object references that are not a simple many-to-one. To set this flag for any arbitrary mapped column, use the ``active_history`` argument with :func:`.column_property`. :param instance: mapped instance to be tested for pending changes. :param include_collections: Indicates if multivalued collections should be included in the operation. Setting this to ``False`` is a way to detect only local-column based properties (i.e. scalar columns or many-to-one foreign keys) that would result in an UPDATE for this instance upon flush. :param passive: Indicates if unloaded attributes and collections should be loaded in the course of performing this test. If set to ``False``, or left at its default value of :data:`.PASSIVE_OFF`, unloaded attributes will be loaded. If set to ``True`` or :data:`.PASSIVE_NO_INITIALIZE`, unloaded collections and attributes will remain unloaded. As noted previously, the existence of this flag here is a bug, as unloaded attributes by definition have no changes, and the load operation also triggers an autoflush which then cancels out subsequent changes. This flag should **always be set to True**. .. versionchanged:: 0.8 The flag will be deprecated and the default set to ``True``. """ try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) dict_ = state.dict if passive is True: passive = attributes.PASSIVE_NO_INITIALIZE elif passive is False: passive = attributes.PASSIVE_OFF for attr in state.manager.attributes: if \ ( not include_collections and hasattr(attr.impl, 'get_collection') ) or not hasattr(attr.impl, 'get_history'): continue (added, unchanged, deleted) = \ attr.impl.get_history(state, dict_, passive=passive) if added or deleted: return True return False @property def is_active(self): """True if this :class:`.Session` is in "transaction mode" and is not in "partial rollback" state. The :class:`.Session` in its default mode of ``autocommit=False`` is essentially always in "transaction mode", in that a :class:`.SessionTransaction` is associated with it as soon as it is instantiated. This :class:`.SessionTransaction` is immediately replaced with a new one as soon as it is ended, due to a rollback, commit, or close operation. "Transaction mode" does *not* indicate whether or not actual database connection resources are in use; the :class:`.SessionTransaction` object coordinates among zero or more actual database transactions, and starts out with none, accumulating individual DBAPI connections as different data sources are used within its scope. The best way to track when a particular :class:`.Session` has actually begun to use DBAPI resources is to implement a listener using the :meth:`.SessionEvents.after_begin` method, which will deliver both the :class:`.Session` as well as the target :class:`.Connection` to a user-defined event listener. The "partial rollback" state refers to when an "inner" transaction, typically used during a flush, encounters an error and emits a rollback of the DBAPI connection. At this point, the :class:`.Session` is in "partial rollback" and awaits for the user to call :meth:`.rollback`, in order to close out the transaction stack. It is in this "partial rollback" period that the :attr:`.is_active` flag returns False. After the call to :meth:`.rollback`, the :class:`.SessionTransaction` is replaced with a new one and :attr:`.is_active` returns ``True`` again. When a :class:`.Session` is used in ``autocommit=True`` mode, the :class:`.SessionTransaction` is only instantiated within the scope of a flush call, or when :meth:`.Session.begin` is called. So :attr:`.is_active` will always be ``False`` outside of a flush or :meth:`.begin` block in this mode, and will be ``True`` within the :meth:`.begin` block as long as it doesn't enter "partial rollback" state. From all the above, it follows that the only purpose to this flag is for application frameworks that wish to detect is a "rollback" is necessary within a generic error handling routine, for :class:`.Session` objects that would otherwise be in "partial rollback" mode. In a typical integration case, this is also not necessary as it is standard practice to emit :meth:`.Session.rollback` unconditionally within the outermost exception catch. To track the transactional state of a :class:`.Session` fully, use event listeners, primarily the :meth:`.SessionEvents.after_begin`, :meth:`.SessionEvents.after_commit`, :meth:`.SessionEvents.after_rollback` and related events. """ return self.transaction and self.transaction.is_active identity_map = None """A mapping of object identities to objects themselves. Iterating through ``Session.identity_map.values()`` provides access to the full set of persistent objects (i.e., those that have row identity) currently in the session. See also: :func:`.identity_key` - operations involving identity keys. """ @property def _dirty_states(self): """The set of all persistent states considered dirty. This method returns all states that were modified including those that were possibly deleted. """ return self.identity_map._dirty_states() @property def dirty(self): """The set of all persistent instances considered dirty. E.g.:: some_mapped_object in session.dirty Instances are considered dirty when they were modified but not deleted. Note that this 'dirty' calculation is 'optimistic'; most attribute-setting or collection modification operations will mark an instance as 'dirty' and place it in this set, even if there is no net change to the attribute's value. At flush time, the value of each attribute is compared to its previously saved value, and if there's no net change, no SQL operation will occur (this is a more expensive operation so it's only done at flush time). To check if an instance has actionable net changes to its attributes, use the :meth:`.Session.is_modified` method. """ return util.IdentitySet( [state.obj() for state in self._dirty_states if state not in self._deleted]) @property def deleted(self): "The set of all instances marked as 'deleted' within this ``Session``" return util.IdentitySet(self._deleted.values()) @property def new(self): "The set of all instances marked as 'new' within this ``Session``." return util.IdentitySet(self._new.values()) _sessions = weakref.WeakValueDictionary() def make_transient(instance): """Make the given instance 'transient'. This will remove its association with any session and additionally will remove its "identity key", such that it's as though the object were newly constructed, except retaining its values. It also resets the "deleted" flag on the state if this object had been explicitly deleted by its session. Attributes which were "expired" or deferred at the instance level are reverted to undefined, and will not trigger any loads. """ state = attributes.instance_state(instance) s = _state_session(state) if s: s._expunge_state(state) # remove expired state and # deferred callables state.callables.clear() if state.key: del state.key if state.deleted: del state.deleted def object_session(instance): """Return the ``Session`` to which instance belongs. If the instance is not a mapped instance, an error is raised. """ try: return _state_session(attributes.instance_state(instance)) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) def _state_session(state): if state.session_id: try: return _sessions[state.session_id] except KeyError: pass return None _new_sessionid = util.counter()
gpl-2.0
Hani-K/Simplicity_Kernel_Exynos5433_LL
tools/perf/python/twatch.py
7370
1334
#! /usr/bin/python # -*- python -*- # -*- coding: utf-8 -*- # twatch - Experimental use of the perf python interface # Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com> # # This application 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; version 2. # # This application 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. import perf def main(): cpus = perf.cpu_map() threads = perf.thread_map() evsel = perf.evsel(task = 1, comm = 1, mmap = 0, wakeup_events = 1, watermark = 1, sample_id_all = 1, sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU | perf.SAMPLE_TID) evsel.open(cpus = cpus, threads = threads); evlist = perf.evlist(cpus, threads) evlist.add(evsel) evlist.mmap() while True: evlist.poll(timeout = -1) for cpu in cpus: event = evlist.read_on_cpu(cpu) if not event: continue print "cpu: %2d, pid: %4d, tid: %4d" % (event.sample_cpu, event.sample_pid, event.sample_tid), print event if __name__ == '__main__': main()
gpl-2.0
tlinnet/qNLS
plot_test.py
1
1400
import qNLS import matplotlib.pyplot as plt import nmrglue import numpy import copy import sys dic_ref, udic_ref, data_ref = qNLS.read_spectrum(file='test.ft2') table = nmrglue.analysis.peakpick.pick(data=data_ref, pthres=100000., nthres=None, algorithm='connected', est_params=False, cluster=False, table=True) uc_dim0 = nmrglue.pipe.make_uc(dic_ref, data_ref, dim=0) uc_dim1 = nmrglue.pipe.make_uc(dic_ref, data_ref, dim=1) y_axisppm = uc_dim0.unit(table['Y_AXIS'], "ppm") x_axisppm = uc_dim1.unit(table['X_AXIS'], "ppm") ax = qNLS.contour_plot(dic=dic_ref, udic=udic_ref, data=data_ref, contour_start=30000., contour_num=10, contour_factor=1.20, ppm=True, show=False, table=table) dic_resi, udic_resi, data_resi = qNLS.read_spectrum(file='test_resi.ft2') ax = qNLS.contour_plot(dic=dic_resi, udic=udic_resi, data=data_resi, contour_start=5000., contour_num=5, contour_factor=1.20, ppm=True, show=False, table=table) int_arr = data_ref[table['Y_AXIS'].astype(int), table['X_AXIS'].astype(int)] plt.close("all") #plt.show() dic_resi, udic_resi, data_resi = qNLS.read_spectrum(file='test_resi.ft2') int_arr_resi = data_resi[table['Y_AXIS'].astype(int), table['X_AXIS'].astype(int)] + int_arr qNLS.write_peak_list(filename="test.tab", x_axis_pts=table['X_AXIS'], y_axis_pts=table['Y_AXIS'], x_axis_ppm=x_axisppm, y_axis_ppm=y_axisppm, int_ref=int_arr, list_int_cov=[int_arr, int_arr_resi])
gpl-3.0
andmos/ansible
lib/ansible/modules/cloud/ovirt/ovirt_api_facts.py
32
2429
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (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 ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: ovirt_api_facts short_description: Retrieve facts about the oVirt/RHV API author: "Ondra Machacek (@machacekondra)" version_added: "2.5" description: - "Retrieve facts about the oVirt/RHV API." notes: - "This module creates a new top-level C(ovirt_api) fact, which contains a information about oVirt/RHV API." extends_documentation_fragment: ovirt_facts ''' EXAMPLES = ''' # Examples don't contain auth parameter for simplicity, # look at ovirt_auth module to see how to reuse authentication: # Gather facts oVirt API: - ovirt_api_facts: - debug: var: ovirt_api ''' RETURN = ''' ovirt_api: description: "Dictionary describing the oVirt API information. Api attributes are mapped to dictionary keys, all API attributes can be found at following url: https://ovirt.example.com/ovirt-engine/api/model#types/api." returned: On success. type: dict ''' import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( check_sdk, create_connection, get_dict_of_struct, ovirt_facts_full_argument_spec, ) def main(): argument_spec = ovirt_facts_full_argument_spec() module = AnsibleModule(argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) api = connection.system_service().get() module.exit_json( changed=False, ansible_facts=dict( ovirt_api=get_dict_of_struct( struct=api, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) ), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None) if __name__ == '__main__': main()
gpl-3.0
faux123/msm8660-aosp-ics
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Core.py
11088
3246
# Core.py - Python extension for perf script, core functions # # Copyright (C) 2010 by Tom Zanussi <tzanussi@gmail.com> # # This software may be distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. from collections import defaultdict def autodict(): return defaultdict(autodict) flag_fields = autodict() symbolic_fields = autodict() def define_flag_field(event_name, field_name, delim): flag_fields[event_name][field_name]['delim'] = delim def define_flag_value(event_name, field_name, value, field_str): flag_fields[event_name][field_name]['values'][value] = field_str def define_symbolic_field(event_name, field_name): # nothing to do, really pass def define_symbolic_value(event_name, field_name, value, field_str): symbolic_fields[event_name][field_name]['values'][value] = field_str def flag_str(event_name, field_name, value): string = "" if flag_fields[event_name][field_name]: print_delim = 0 keys = flag_fields[event_name][field_name]['values'].keys() keys.sort() for idx in keys: if not value and not idx: string += flag_fields[event_name][field_name]['values'][idx] break if idx and (value & idx) == idx: if print_delim and flag_fields[event_name][field_name]['delim']: string += " " + flag_fields[event_name][field_name]['delim'] + " " string += flag_fields[event_name][field_name]['values'][idx] print_delim = 1 value &= ~idx return string def symbol_str(event_name, field_name, value): string = "" if symbolic_fields[event_name][field_name]: keys = symbolic_fields[event_name][field_name]['values'].keys() keys.sort() for idx in keys: if not value and not idx: string = symbolic_fields[event_name][field_name]['values'][idx] break if (value == idx): string = symbolic_fields[event_name][field_name]['values'][idx] break return string trace_flags = { 0x00: "NONE", \ 0x01: "IRQS_OFF", \ 0x02: "IRQS_NOSUPPORT", \ 0x04: "NEED_RESCHED", \ 0x08: "HARDIRQ", \ 0x10: "SOFTIRQ" } def trace_flag_str(value): string = "" print_delim = 0 keys = trace_flags.keys() for idx in keys: if not value and not idx: string += "NONE" break if idx and (value & idx) == idx: if print_delim: string += " | "; string += trace_flags[idx] print_delim = 1 value &= ~idx return string def taskState(state): states = { 0 : "R", 1 : "S", 2 : "D", 64: "DEAD" } if state not in states: return "Unknown" return states[state] class EventHeaders: def __init__(self, common_cpu, common_secs, common_nsecs, common_pid, common_comm): self.cpu = common_cpu self.secs = common_secs self.nsecs = common_nsecs self.pid = common_pid self.comm = common_comm def ts(self): return (self.secs * (10 ** 9)) + self.nsecs def ts_format(self): return "%d.%d" % (self.secs, int(self.nsecs / 1000))
gpl-2.0
repotvsupertuga/tvsupertuga.repository
instal/plugin.video.youtube/resources/lib/youtube/helper/yt_login.py
3
5859
__author__ = 'bromix' import time def process(mode, provider, context, re_match, needs_tv_login=True): def _do_login(_for_tv=False): _client = provider.get_client(context) json_data = {} if _for_tv: json_data = _client.generate_user_code_tv() pass else: json_data = _client.generate_user_code() pass interval = int(json_data.get('interval', 5)) * 1000 if interval > 60000: interval = 5000 pass device_code = json_data['device_code'] user_code = json_data['user_code'] text = context.localize(provider.LOCAL_MAP['youtube.sign.go_to']) % '[B]youtube.com/activate[/B]' text += '[CR]%s [B]%s[/B]' % (context.localize(provider.LOCAL_MAP['youtube.sign.enter_code']), user_code) dialog = context.get_ui().create_progress_dialog( heading=context.localize(provider.LOCAL_MAP['youtube.sign.in']), text=text, background=False) steps = (10 * 60 * 1000) / interval # 10 Minutes dialog.set_total(steps) for i in range(steps): dialog.update() json_data = {} if _for_tv: json_data = _client.get_device_token_tv(device_code) pass else: json_data = _client.get_device_token(device_code) pass if not 'error' in json_data: access_token = json_data.get('access_token', '') expires_in = time.time() + int(json_data.get('expires_in', 3600)) refresh_token = json_data.get('refresh_token', '') if access_token and refresh_token: dialog.close() return access_token, expires_in, refresh_token # provider.reset_client() # context.get_access_manager().update_access_token(access_token, expires_in, refresh_token) #context.get_ui().refresh_container() elif json_data['error'] != u'authorization_pending': message = json_data['error'] title = '%s: %s' % (context.get_name(), message) context.get_ui().show_notification(message, title) context.log_error('Error: |%s|' % message) if dialog.is_aborted(): dialog.close() return '', 0, '' context.sleep(interval) pass dialog.close() pass if mode == 'out': # we clear the cache, so none cached data of an old account will be displayed. context.get_function_cache().clear() access_manager = context.get_access_manager() client = provider.get_client(context) if access_manager.has_refresh_token(): refresh_tokens = access_manager.get_refresh_token().split('|') refresh_tokens = list(set(refresh_tokens)) for refresh_token in refresh_tokens: client.revoke(refresh_token) pass pass provider.reset_client() access_manager.update_access_token(access_token='', refresh_token='') context.get_ui().refresh_container() pass elif mode == 'in': access_token_tv = '' expires_in_tv = 0 refresh_token_tv = '' requires_dual_login = context.get_settings().requires_dual_login() context.log_debug('Sign-in: Dual login required |%s|' % requires_dual_login) if needs_tv_login: context.get_ui().on_ok(context.localize(provider.LOCAL_MAP['youtube.sign.twice.title']), context.localize(provider.LOCAL_MAP['youtube.sign.twice.text'])) access_token_tv, expires_in_tv, refresh_token_tv = _do_login(_for_tv=True) # abort tv login context.log_debug('YouTube-TV Login: Access Token |%s| Refresh Token |%s| Expires |%s|' % (access_token_tv != '', refresh_token_tv != '', expires_in_tv)) if not access_token_tv and not refresh_token_tv: provider.reset_client() context.get_access_manager().update_access_token('') context.get_ui().refresh_container() return pass access_token_kodi, expires_in_kodi, refresh_token_kodi = _do_login(_for_tv=False) # abort kodi login context.log_debug('YouTube-Kodi Login: Access Token |%s| Refresh Token |%s| Expires |%s|' % (access_token_kodi != '', refresh_token_kodi != '', expires_in_kodi)) if not access_token_kodi and not refresh_token_kodi: provider.reset_client() context.get_access_manager().update_access_token('') context.get_ui().refresh_container() return if not requires_dual_login: access_token_tv, expires_in_tv, refresh_token_tv = access_token_kodi, expires_in_kodi, refresh_token_kodi # if needs_tv_login: access_token = '%s|%s' % (access_token_tv, access_token_kodi) refresh_token = '%s|%s' % (refresh_token_tv, refresh_token_kodi) expires_in = min(expires_in_tv, expires_in_kodi) # else: # access_token = access_token_kodi # refresh_token = refresh_token_kodi # expires_in = expires_in_kodi # pass # we clear the cache, so none cached data of an old account will be displayed. context.get_function_cache().clear() major_version = context.get_system_version().get_version()[0] context.get_settings().set_int('youtube.login.version', major_version) provider.reset_client() context.get_access_manager().update_access_token(access_token, expires_in, refresh_token) context.get_ui().refresh_container() pass pass
gpl-2.0
alepharchives/psutil
psutil/_compat.py
1
8814
#!/usr/bin/env python # # $Id$ # # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Module which provides compatibility with older Python versions.""" __all__ = ["PY3", "int", "long", "xrange", "exec_", "callable", "namedtuple", "property", "defaultdict"] import sys # --- python 2/3 compatibility layer PY3 = sys.version_info >= (3,) try: import __builtin__ except ImportError: import builtins as __builtin__ # py3 if PY3: int = int long = int xrange = range exec_ = getattr(__builtin__, "exec") print_ = getattr(__builtin__, "print") else: int = int long = long xrange = xrange def exec_(code, globs=None, locs=None): if globs is None: frame = _sys._getframe(1) globs = frame.f_globals if locs is None: locs = frame.f_locals del frame elif locs is None: locs = globs exec("""exec code in globs, locs""") def print_(s): sys.stdout.write(s + '\n') sys.stdout.flush() # removed in 3.0, reintroduced in 3.2 try: callable = callable except Exception: def callable(obj): for klass in type(obj).__mro__: if "__call__" in klass.__dict__: return True return False # --- stdlib additions try: from collections import namedtuple except ImportError: from operator import itemgetter as _itemgetter from keyword import iskeyword as _iskeyword import sys as _sys def namedtuple(typename, field_names, verbose=False, rename=False): """A collections.namedtuple implementation written in Python to support Python versions < 2.6. Taken from: http://code.activestate.com/recipes/500261/ """ # Parse and validate the field names. Validation serves two # purposes, generating informative error messages and preventing # template injection attacks. if isinstance(field_names, basestring): # names separated by whitespace and/or commas field_names = field_names.replace(',', ' ').split() field_names = tuple(map(str, field_names)) if rename: names = list(field_names) seen = set() for i, name in enumerate(names): if (not min(c.isalnum() or c=='_' for c in name) or _iskeyword(name) or not name or name[0].isdigit() or name.startswith('_') or name in seen): names[i] = '_%d' % i seen.add(name) field_names = tuple(names) for name in (typename,) + field_names: if not min(c.isalnum() or c=='_' for c in name): raise ValueError('Type names and field names can only contain ' \ 'alphanumeric characters and underscores: %r' % name) if _iskeyword(name): raise ValueError('Type names and field names cannot be a keyword: %r' \ % name) if name[0].isdigit(): raise ValueError('Type names and field names cannot start with a ' \ 'number: %r' % name) seen_names = set() for name in field_names: if name.startswith('_') and not rename: raise ValueError('Field names cannot start with an underscore: %r' % name) if name in seen_names: raise ValueError('Encountered duplicate field name: %r' % name) seen_names.add(name) # Create and fill-in the class template numfields = len(field_names) # tuple repr without parens or quotes argtxt = repr(field_names).replace("'", "")[1:-1] reprtxt = ', '.join('%s=%%r' % name for name in field_names) template = '''class %(typename)s(tuple): '%(typename)s(%(argtxt)s)' \n __slots__ = () \n _fields = %(field_names)r \n def __new__(_cls, %(argtxt)s): return _tuple.__new__(_cls, (%(argtxt)s)) \n @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new %(typename)s object from a sequence or iterable' result = new(cls, iterable) if len(result) != %(numfields)d: raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result)) return result \n def __repr__(self): return '%(typename)s(%(reprtxt)s)' %% self \n def _asdict(self): 'Return a new dict which maps field names to their values' return dict(zip(self._fields, self)) \n def _replace(_self, **kwds): 'Return a new %(typename)s object replacing specified fields with new values' result = _self._make(map(kwds.pop, %(field_names)r, _self)) if kwds: raise ValueError('Got unexpected field names: %%r' %% kwds.keys()) return result \n def __getnewargs__(self): return tuple(self) \n\n''' % locals() for i, name in enumerate(field_names): template += ' %s = _property(_itemgetter(%d))\n' % (name, i) if verbose: sys.stdout.write(template + '\n') sys.stdout.flush() # Execute the template string in a temporary namespace namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename, _property=property, _tuple=tuple) try: exec_(template, namespace) except SyntaxError: e = sys.exc_info()[1] raise SyntaxError(e.message + ':\n' + template) result = namespace[typename] # For pickling to work, the __module__ variable needs to be set # to the frame where the named tuple is created. Bypass this # step in enviroments where sys._getframe is not defined (Jython # for example) or sys._getframe is not defined for arguments # greater than 0 (IronPython). try: result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__') except (AttributeError, ValueError): pass return result # hack to support property.setter/deleter on python < 2.6 # http://docs.python.org/library/functions.html?highlight=property#property if hasattr(property, 'setter'): property = property else: class property(__builtin__.property): __metaclass__ = type def __init__(self, fget, *args, **kwargs): super(property, self).__init__(fget, *args, **kwargs) self.__doc__ = fget.__doc__ def getter(self, method): return property(method, self.fset, self.fdel) def setter(self, method): return property(self.fget, method, self.fdel) def deleter(self, method): return property(self.fget, self.fset, method) # py 2.5 collections.defauldict # Taken from: # http://code.activestate.com/recipes/523034-emulate-collectionsdefaultdict/ # credits: Jason Kirtland try: from collections import defaultdict except ImportError: class defaultdict(dict): def __init__(self, default_factory=None, *a, **kw): if (default_factory is not None and not hasattr(default_factory, '__call__')): raise TypeError('first argument must be callable') dict.__init__(self, *a, **kw) self.default_factory = default_factory def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.__missing__(key) def __missing__(self, key): if self.default_factory is None: raise KeyError(key) self[key] = value = self.default_factory() return value def __reduce__(self): if self.default_factory is None: args = tuple() else: args = self.default_factory, return type(self), args, None, None, self.items() def copy(self): return self.__copy__() def __copy__(self): return type(self)(self.default_factory, self) def __deepcopy__(self, memo): import copy return type(self)(self.default_factory, copy.deepcopy(self.items())) def __repr__(self): return 'defaultdict(%s, %s)' % (self.default_factory, dict.__repr__(self))
bsd-3-clause
creativewild/ansible
v1/tests/TestPlayVarsFiles.py
95
12363
#!/usr/bin/env python import os import shutil from tempfile import mkstemp from tempfile import mkdtemp from ansible.playbook.play import Play import ansible import unittest from nose.plugins.skip import SkipTest class FakeCallBacks(object): def __init__(self): pass def on_vars_prompt(self): pass def on_import_for_host(self, host, filename): pass class FakeInventory(object): def __init__(self): self.hosts = {} def basedir(self): return "." def src(self): return "fakeinventory" def get_variables(self, host, vault_password=None): if host in self.hosts: return self.hosts[host] else: return {} class FakePlayBook(object): def __init__(self): self.extra_vars = {} self.remote_user = None self.remote_port = None self.sudo = None self.sudo_user = None self.su = None self.su_user = None self.become = None self.become_method = None self.become_user = None self.transport = None self.only_tags = None self.skip_tags = None self.force_handlers = None self.VARS_CACHE = {} self.SETUP_CACHE = {} self.inventory = FakeInventory() self.callbacks = FakeCallBacks() self.VARS_CACHE['localhost'] = {} class TestMe(unittest.TestCase): ######################################## # BASIC FILE LOADING BEHAVIOR TESTS ######################################## def test_play_constructor(self): # __init__(self, playbook, ds, basedir, vault_password=None) playbook = FakePlayBook() ds = { "hosts": "localhost"} basedir = "." play = Play(playbook, ds, basedir) def test_vars_file(self): # make a vars file fd, temp_path = mkstemp() f = open(temp_path, "wb") f.write("foo: bar\n") f.close() # create a play with a vars_file playbook = FakePlayBook() ds = { "hosts": "localhost", "vars_files": [temp_path]} basedir = "." play = Play(playbook, ds, basedir) os.remove(temp_path) # make sure the variable was loaded assert 'foo' in play.vars_file_vars, "vars_file was not loaded into play.vars_file_vars" assert play.vars_file_vars['foo'] == 'bar', "foo was not set to bar in play.vars_file_vars" def test_vars_file_nonlist_error(self): # make a vars file fd, temp_path = mkstemp() f = open(temp_path, "wb") f.write("foo: bar\n") f.close() # create a play with a string for vars_files playbook = FakePlayBook() ds = { "hosts": "localhost", "vars_files": temp_path} basedir = "." error_hit = False try: play = Play(playbook, ds, basedir) except: error_hit = True os.remove(temp_path) assert error_hit == True, "no error was thrown when vars_files was not a list" def test_multiple_vars_files(self): # make a vars file fd, temp_path = mkstemp() f = open(temp_path, "wb") f.write("foo: bar\n") f.close() # make a second vars file fd, temp_path2 = mkstemp() f = open(temp_path2, "wb") f.write("baz: bang\n") f.close() # create a play with two vars_files playbook = FakePlayBook() ds = { "hosts": "localhost", "vars_files": [temp_path, temp_path2]} basedir = "." play = Play(playbook, ds, basedir) os.remove(temp_path) os.remove(temp_path2) # make sure the variables were loaded assert 'foo' in play.vars_file_vars, "vars_file was not loaded into play.vars_file_vars" assert play.vars_file_vars['foo'] == 'bar', "foo was not set to bar in play.vars_file_vars" assert 'baz' in play.vars_file_vars, "vars_file2 was not loaded into play.vars_file_vars" assert play.vars_file_vars['baz'] == 'bang', "baz was not set to bang in play.vars_file_vars" def test_vars_files_first_found(self): # make a vars file fd, temp_path = mkstemp() f = open(temp_path, "wb") f.write("foo: bar\n") f.close() # get a random file path fd, temp_path2 = mkstemp() # make sure this file doesn't exist os.remove(temp_path2) # create a play playbook = FakePlayBook() ds = { "hosts": "localhost", "vars_files": [[temp_path2, temp_path]]} basedir = "." play = Play(playbook, ds, basedir) os.remove(temp_path) # make sure the variable was loaded assert 'foo' in play.vars_file_vars, "vars_file was not loaded into play.vars_file_vars" assert play.vars_file_vars['foo'] == 'bar', "foo was not set to bar in play.vars_file_vars" def test_vars_files_multiple_found(self): # make a vars file fd, temp_path = mkstemp() f = open(temp_path, "wb") f.write("foo: bar\n") f.close() # make a second vars file fd, temp_path2 = mkstemp() f = open(temp_path2, "wb") f.write("baz: bang\n") f.close() # create a play playbook = FakePlayBook() ds = { "hosts": "localhost", "vars_files": [[temp_path, temp_path2]]} basedir = "." play = Play(playbook, ds, basedir) os.remove(temp_path) os.remove(temp_path2) # make sure the variables were loaded assert 'foo' in play.vars_file_vars, "vars_file was not loaded into play.vars_file_vars" assert play.vars_file_vars['foo'] == 'bar', "foo was not set to bar in play.vars_file_vars" assert 'baz' not in play.vars_file_vars, "vars_file2 was loaded after vars_file1 was loaded" def test_vars_files_assert_all_found(self): # make a vars file fd, temp_path = mkstemp() f = open(temp_path, "wb") f.write("foo: bar\n") f.close() # make a second vars file fd, temp_path2 = mkstemp() # make sure it doesn't exist os.remove(temp_path2) # create a play playbook = FakePlayBook() ds = { "hosts": "localhost", "vars_files": [temp_path, temp_path2]} basedir = "." error_hit = False error_msg = None try: play = Play(playbook, ds, basedir) except ansible.errors.AnsibleError, e: error_hit = True error_msg = e os.remove(temp_path) assert error_hit == True, "no error was thrown for missing vars_file" ######################################## # VARIABLE PRECEDENCE TESTS ######################################## # On the first run vars_files are loaded into play.vars_file_vars by host == None # * only files with vars from host==None will work here # On the secondary run(s), a host is given and the vars_files are loaded into VARS_CACHE # * this only occurs if host is not None, filename2 has vars in the name, and filename3 does not # filename -- the original string # filename2 -- filename templated with play vars # filename3 -- filename2 template with inject (hostvars + setup_cache + vars_cache) # filename4 -- path_dwim(filename3) def test_vars_files_for_host(self): # host != None # vars in filename2 # no vars in filename3 # make a vars file fd, temp_path = mkstemp() f = open(temp_path, "wb") f.write("foo: bar\n") f.close() # build play attributes playbook = FakePlayBook() ds = { "hosts": "localhost", "vars_files": ["{{ temp_path }}"]} basedir = "." playbook.VARS_CACHE['localhost']['temp_path'] = temp_path # create play and do first run play = Play(playbook, ds, basedir) # the second run is started by calling update_vars_files play.update_vars_files(['localhost']) os.remove(temp_path) assert 'foo' in play.playbook.VARS_CACHE['localhost'], "vars_file vars were not loaded into vars_cache" assert play.playbook.VARS_CACHE['localhost']['foo'] == 'bar', "foo does not equal bar" ######################################## # COMPLEX FILENAME TEMPLATING TESTS ######################################## def test_vars_files_two_vars_in_name(self): # self.vars_file_vars = ds['vars'] # self.vars_file_vars += _get_vars() ... aka extra_vars # make a temp dir temp_dir = mkdtemp() # make a temp file fd, temp_file = mkstemp(dir=temp_dir) f = open(temp_file, "wb") f.write("foo: bar\n") f.close() # build play attributes playbook = FakePlayBook() ds = { "hosts": "localhost", "vars": { "temp_dir": os.path.dirname(temp_file), "temp_file": os.path.basename(temp_file) }, "vars_files": ["{{ temp_dir + '/' + temp_file }}"]} basedir = "." # create play and do first run play = Play(playbook, ds, basedir) # cleanup shutil.rmtree(temp_dir) assert 'foo' in play.vars_file_vars, "double var templated vars_files filename not loaded" def test_vars_files_two_vars_different_scope(self): # # Use a play var and an inventory var to create the filename # # self.playbook.inventory.get_variables(host) # {'group_names': ['ungrouped'], 'inventory_hostname': 'localhost', # 'ansible_ssh_user': 'root', 'inventory_hostname_short': 'localhost'} # make a temp dir temp_dir = mkdtemp() # make a temp file fd, temp_file = mkstemp(dir=temp_dir) f = open(temp_file, "wb") f.write("foo: bar\n") f.close() # build play attributes playbook = FakePlayBook() playbook.inventory.hosts['localhost'] = {'inventory_hostname': os.path.basename(temp_file)} ds = { "hosts": "localhost", "vars": { "temp_dir": os.path.dirname(temp_file)}, "vars_files": ["{{ temp_dir + '/' + inventory_hostname }}"]} basedir = "." # create play and do first run play = Play(playbook, ds, basedir) # do the host run play.update_vars_files(['localhost']) # cleanup shutil.rmtree(temp_dir) assert 'foo' not in play.vars_file_vars, \ "mixed scope vars_file loaded into play vars" assert 'foo' in play.playbook.VARS_CACHE['localhost'], \ "differently scoped templated vars_files filename not loaded" assert play.playbook.VARS_CACHE['localhost']['foo'] == 'bar', \ "foo is not bar" def test_vars_files_two_vars_different_scope_first_found(self): # # Use a play var and an inventory var to create the filename # # make a temp dir temp_dir = mkdtemp() # make a temp file fd, temp_file = mkstemp(dir=temp_dir) f = open(temp_file, "wb") f.write("foo: bar\n") f.close() # build play attributes playbook = FakePlayBook() playbook.inventory.hosts['localhost'] = {'inventory_hostname': os.path.basename(temp_file)} ds = { "hosts": "localhost", "vars": { "temp_dir": os.path.dirname(temp_file)}, "vars_files": [["{{ temp_dir + '/' + inventory_hostname }}"]]} basedir = "." # create play and do first run play = Play(playbook, ds, basedir) # do the host run play.update_vars_files(['localhost']) # cleanup shutil.rmtree(temp_dir) assert 'foo' not in play.vars_file_vars, \ "mixed scope vars_file loaded into play vars" assert 'foo' in play.playbook.VARS_CACHE['localhost'], \ "differently scoped templated vars_files filename not loaded" assert play.playbook.VARS_CACHE['localhost']['foo'] == 'bar', \ "foo is not bar"
gpl-3.0
Leits/openprocurement.api
src/openprocurement/api/tests/chronograph.py
1
15576
# -*- coding: utf-8 -*- import unittest from openprocurement.api.tests.base import BaseTenderWebTest, test_lots, test_bids class TenderSwitchTenderingResourceTest(BaseTenderWebTest): def test_switch_to_tendering_by_enquiryPeriod_endDate(self): self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertNotEqual(response.json['data']["status"], "active.tendering") self.set_status('active.tendering', {'status': 'active.enquiries', "tenderPeriod": {"startDate": None}}) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], "active.tendering") def test_switch_to_tendering_by_tenderPeriod_startDate(self): self.set_status('active.tendering', {'status': 'active.enquiries', "tenderPeriod": {}}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertNotEqual(response.json['data']["status"], "active.tendering") self.set_status('active.tendering', {'status': self.initial_status, "enquiryPeriod": {}}) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], "active.tendering") class TenderSwitchQualificationResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' initial_bids = test_bids[:1] def test_switch_to_qualification(self): response = self.set_status('active.auction', {'status': self.initial_status}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active.qualification") self.assertEqual(len(response.json['data']["awards"]), 1) class TenderSwitchAuctionResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' initial_bids = test_bids def test_switch_to_auction(self): response = self.set_status('active.auction', {'status': self.initial_status}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active.auction") class TenderSwitchUnsuccessfulResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' def test_switch_to_unsuccessful(self): response = self.set_status('active.auction', {'status': self.initial_status}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "unsuccessful") class TenderLotSwitchQualificationResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' initial_lots = test_lots initial_bids = test_bids[:1] def test_switch_to_qualification(self): response = self.set_status('active.auction', {'status': self.initial_status}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active.qualification") self.assertEqual(len(response.json['data']["awards"]), 1) class TenderLotSwitchAuctionResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' initial_lots = test_lots initial_bids = test_bids def test_switch_to_auction(self): response = self.set_status('active.auction', {'status': self.initial_status}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active.auction") class TenderLotSwitchUnsuccessfulResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' initial_lots = test_lots def test_switch_to_unsuccessful(self): response = self.set_status('active.auction', {'status': self.initial_status}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "unsuccessful") self.assertEqual(set([i['status'] for i in response.json['data']["lots"]]), set(["unsuccessful"])) class TenderAuctionPeriodResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' def test_set_auction_period(self): self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"auctionPeriod": {"startDate": "9999-01-01T00:00:00+00:00"}}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']['auctionPeriod']['startDate'], '9999-01-01T00:00:00+00:00') response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"auctionPeriod": {"startDate": None}}}) self.assertEqual(response.status, '200 OK') self.assertNotIn('auctionPeriod', response.json['data']) class TenderLotAuctionPeriodResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' initial_lots = test_lots def test_set_auction_period(self): self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"lots": [{"auctionPeriod": {"startDate": "9999-01-01T00:00:00+00:00"}}]}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["lots"][0]['auctionPeriod']['startDate'], '9999-01-01T00:00:00+00:00') response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"lots": [{"auctionPeriod": {"startDate": None}}]}}) self.assertEqual(response.status, '200 OK') self.assertNotIn('auctionPeriod', response.json['data']["lots"][0]) class TenderComplaintSwitchResourceTest(BaseTenderWebTest): def test_switch_to_pending(self): response = self.app.post_json('/tenders/{}/complaints'.format(self.tender_id), {'data': { 'title': 'complaint title', 'description': 'complaint description', 'author': self.initial_data["procuringEntity"], 'status': 'claim' }}) self.assertEqual(response.status, '201 Created') self.assertEqual(response.json['data']['status'], 'claim') tender = self.db.get(self.tender_id) tender['complaints'][0]['dateSubmitted'] = '2014-01-01' self.db.save(tender) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["complaints"][0]['status'], 'pending') def test_switch_to_complaint(self): for status in ['invalid', 'resolved', 'declined']: self.app.authorization = ('Basic', ('token', '')) response = self.app.post_json('/tenders/{}/complaints'.format(self.tender_id), {'data': { 'title': 'complaint title', 'description': 'complaint description', 'author': self.initial_data["procuringEntity"], 'status': 'claim' }}) self.assertEqual(response.status, '201 Created') self.assertEqual(response.json['data']['status'], 'claim') complaint = response.json['data'] response = self.app.patch_json('/tenders/{}/complaints/{}?acc_token={}'.format(self.tender_id, complaint['id'], self.tender_token), {"data": { "status": "answered", "resolutionType": status }}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "answered") self.assertEqual(response.json['data']["resolutionType"], status) tender = self.db.get(self.tender_id) tender['complaints'][-1]['dateAnswered'] = '2014-01-01' self.db.save(tender) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["complaints"][-1]['status'], status) class TenderLotComplaintSwitchResourceTest(TenderComplaintSwitchResourceTest): initial_lots = test_lots class TenderAwardComplaintSwitchResourceTest(BaseTenderWebTest): initial_status = 'active.qualification' initial_bids = test_bids def setUp(self): super(TenderAwardComplaintSwitchResourceTest, self).setUp() # Create award response = self.app.post_json('/tenders/{}/awards'.format( self.tender_id), {'data': {'suppliers': [self.initial_data["procuringEntity"]], 'status': 'pending', 'bid_id': self.initial_bids[0]['id']}}) award = response.json['data'] self.award_id = award['id'] def test_switch_to_pending(self): response = self.app.post_json('/tenders/{}/awards/{}/complaints'.format(self.tender_id, self.award_id), {'data': { 'title': 'complaint title', 'description': 'complaint description', 'author': self.initial_data["procuringEntity"], 'status': 'claim' }}) self.assertEqual(response.status, '201 Created') self.assertEqual(response.json['data']['status'], 'claim') response = self.app.patch_json('/tenders/{}/awards/{}'.format(self.tender_id, self.award_id), {"data": {"status": "active"}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active") tender = self.db.get(self.tender_id) tender['awards'][0]['complaints'][0]['dateSubmitted'] = '2014-01-01' self.db.save(tender) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']['awards'][0]["complaints"][0]['status'], 'pending') def test_switch_to_complaint(self): response = self.app.patch_json('/tenders/{}/awards/{}'.format(self.tender_id, self.award_id), {"data": {"status": "active"}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active") for status in ['invalid', 'resolved', 'declined']: self.app.authorization = ('Basic', ('token', '')) response = self.app.post_json('/tenders/{}/awards/{}/complaints'.format(self.tender_id, self.award_id), {'data': { 'title': 'complaint title', 'description': 'complaint description', 'author': self.initial_data["procuringEntity"], 'status': 'claim' }}) self.assertEqual(response.status, '201 Created') self.assertEqual(response.json['data']['status'], 'claim') complaint = response.json['data'] response = self.app.patch_json('/tenders/{}/awards/{}/complaints/{}?acc_token={}'.format(self.tender_id, self.award_id, complaint['id'], self.tender_token), {"data": { "status": "answered", "resolutionType": status }}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "answered") self.assertEqual(response.json['data']["resolutionType"], status) tender = self.db.get(self.tender_id) tender['awards'][0]['complaints'][-1]['dateAnswered'] = '2014-01-01' self.db.save(tender) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']['awards'][0]["complaints"][-1]['status'], status) class TenderLotAwardComplaintSwitchResourceTest(TenderAwardComplaintSwitchResourceTest): initial_lots = test_lots def setUp(self): super(TenderAwardComplaintSwitchResourceTest, self).setUp() # Create award response = self.app.post_json('/tenders/{}/awards'.format(self.tender_id), {'data': { 'suppliers': [self.initial_data["procuringEntity"]], 'status': 'pending', 'bid_id': self.initial_bids[0]['id'], 'lotID': self.initial_bids[0]['lotValues'][0]['relatedLot'] }}) award = response.json['data'] self.award_id = award['id'] def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TenderAwardComplaintSwitchResourceTest)) suite.addTest(unittest.makeSuite(TenderComplaintSwitchResourceTest)) suite.addTest(unittest.makeSuite(TenderLotAwardComplaintSwitchResourceTest)) suite.addTest(unittest.makeSuite(TenderLotComplaintSwitchResourceTest)) suite.addTest(unittest.makeSuite(TenderLotSwitchAuctionResourceTest)) suite.addTest(unittest.makeSuite(TenderLotSwitchQualificationResourceTest)) suite.addTest(unittest.makeSuite(TenderLotSwitchUnsuccessfulResourceTest)) suite.addTest(unittest.makeSuite(TenderSwitchAuctionResourceTest)) suite.addTest(unittest.makeSuite(TenderSwitchQualificationResourceTest)) suite.addTest(unittest.makeSuite(TenderSwitchUnsuccessfulResourceTest)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
apache-2.0
cidadania/e-cidadania
src/apps/ecidadania/voting/migrations/0001_initial.py
1
20909
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Poll' db.create_table(u'voting_poll', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('question', self.gf('django.db.models.fields.CharField')(max_length=200)), ('pub_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('poll_lastup', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)), ('author', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='poll-author', null=True, to=orm['auth.User'])), ('space', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['spaces.Space'], null=True, blank=True)), ('poll_tags', self.gf('apps.thirdparty.tagging.fields.TagField')(max_length=255, blank=True)), ('start_date', self.gf('django.db.models.fields.DateField')()), ('end_date', self.gf('django.db.models.fields.DateField')()), )) db.send_create_signal(u'voting', ['Poll']) # Adding M2M table for field participants on 'Poll' m2m_table_name = db.shorten_name(u'voting_poll_participants') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('poll', models.ForeignKey(orm[u'voting.poll'], null=False)), ('user', models.ForeignKey(orm[u'auth.user'], null=False)) )) db.create_unique(m2m_table_name, ['poll_id', 'user_id']) # Adding model 'Choice' db.create_table(u'voting_choice', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('poll', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['voting.Poll'])), ('choice_text', self.gf('django.db.models.fields.CharField')(max_length=200, null=True, blank=True)), )) db.send_create_signal(u'voting', ['Choice']) # Adding M2M table for field votes on 'Choice' m2m_table_name = db.shorten_name(u'voting_choice_votes') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('choice', models.ForeignKey(orm[u'voting.choice'], null=False)), ('user', models.ForeignKey(orm[u'auth.user'], null=False)) )) db.create_unique(m2m_table_name, ['choice_id', 'user_id']) # Adding model 'Voting' db.create_table(u'voting_voting', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(unique=True, max_length=200)), ('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('space', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['spaces.Space'], null=True, blank=True)), ('date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('date_mod', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)), ('author', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)), ('start_date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)), ('end_date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)), ('ponderation', self.gf('django.db.models.fields.CharField')(max_length=3, null=True, blank=True)), ('max_votes', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)), )) db.send_create_signal(u'voting', ['Voting']) # Adding M2M table for field proposalsets on 'Voting' m2m_table_name = db.shorten_name(u'voting_voting_proposalsets') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('voting', models.ForeignKey(orm[u'voting.voting'], null=False)), ('proposalset', models.ForeignKey(orm[u'proposals.proposalset'], null=False)) )) db.create_unique(m2m_table_name, ['voting_id', 'proposalset_id']) # Adding M2M table for field proposals on 'Voting' m2m_table_name = db.shorten_name(u'voting_voting_proposals') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('voting', models.ForeignKey(orm[u'voting.voting'], null=False)), ('proposal', models.ForeignKey(orm[u'proposals.proposal'], null=False)) )) db.create_unique(m2m_table_name, ['voting_id', 'proposal_id']) # Adding model 'ConfirmVote' db.create_table(u'voting_confirmvote', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)), ('proposal', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['proposals.Proposal'], null=True, blank=True)), ('token', self.gf('django.db.models.fields.CharField')(max_length=32, null=True, blank=True)), ('requested_on', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), )) db.send_create_signal(u'voting', ['ConfirmVote']) def backwards(self, orm): # Deleting model 'Poll' db.delete_table(u'voting_poll') # Removing M2M table for field participants on 'Poll' db.delete_table(db.shorten_name(u'voting_poll_participants')) # Deleting model 'Choice' db.delete_table(u'voting_choice') # Removing M2M table for field votes on 'Choice' db.delete_table(db.shorten_name(u'voting_choice_votes')) # Deleting model 'Voting' db.delete_table(u'voting_voting') # Removing M2M table for field proposalsets on 'Voting' db.delete_table(db.shorten_name(u'voting_voting_proposalsets')) # Removing M2M table for field proposals on 'Voting' db.delete_table(db.shorten_name(u'voting_voting_proposals')) # Deleting model 'ConfirmVote' db.delete_table(u'voting_confirmvote') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'debate.debate': { 'Meta': {'object_name': 'Debate'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_mod': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'space': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['spaces.Space']", 'null': 'True', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'theme': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}) }, u'proposals.proposal': { 'Meta': {'object_name': 'Proposal'}, 'anon_allowed': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'proposal_authors'", 'null': 'True', 'to': u"orm['auth.User']"}), 'budget': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'close_reason': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'closed': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}), 'closed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'proposal_closed_by'", 'null': 'True', 'to': u"orm['auth.User']"}), 'code': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '300'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'latitude': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '17', 'decimal_places': '15', 'blank': 'True'}), 'longitude': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '17', 'decimal_places': '15', 'blank': 'True'}), 'merged': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}), 'merged_proposals': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'merged_proposals_rel_+'", 'null': 'True', 'to': u"orm['proposals.Proposal']"}), 'mod_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'object_pk': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'proposalset': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'proposal_in'", 'null': 'True', 'to': u"orm['proposals.ProposalSet']"}), 'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'refurbished': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}), 'space': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['spaces.Space']", 'null': 'True', 'blank': 'True'}), 'support_votes': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'support_votes'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['auth.User']"}), 'tags': ('apps.thirdparty.tagging.fields.TagField', [], {'max_length': '255', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'votes': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'voting_votes'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['auth.User']"}) }, u'proposals.proposalset': { 'Meta': {'object_name': 'ProposalSet'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'debate': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['debate.Debate']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}), 'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'space': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['spaces.Space']", 'null': 'True', 'blank': 'True'}) }, u'spaces.space': { 'Meta': {'ordering': "['name']", 'object_name': 'Space'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'banner': ('core.spaces.fields.StdImageField', [], {'max_length': '100'}), 'description': ('django.db.models.fields.TextField', [], {'default': "u'Write here your description.'"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'logo': ('core.spaces.fields.StdImageField', [], {'max_length': '100'}), 'mod_cal': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'mod_debate': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'mod_docs': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'mod_news': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'mod_proposals': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'mod_voting': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '250'}), 'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'url': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}) }, u'voting.choice': { 'Meta': {'object_name': 'Choice'}, 'choice_text': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'poll': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['voting.Poll']"}), 'votes': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, u'voting.confirmvote': { 'Meta': {'object_name': 'ConfirmVote'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'proposal': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['proposals.Proposal']", 'null': 'True', 'blank': 'True'}), 'requested_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, u'voting.poll': { 'Meta': {'object_name': 'Poll'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'poll-author'", 'null': 'True', 'to': u"orm['auth.User']"}), 'end_date': ('django.db.models.fields.DateField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'participants': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'poll_lastup': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'poll_tags': ('apps.thirdparty.tagging.fields.TagField', [], {'max_length': '255', 'blank': 'True'}), 'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'question': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'space': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['spaces.Space']", 'null': 'True', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {}) }, u'voting.voting': { 'Meta': {'object_name': 'Voting'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_mod': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'max_votes': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'ponderation': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'blank': 'True'}), 'proposals': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['proposals.Proposal']", 'null': 'True', 'blank': 'True'}), 'proposalsets': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['proposals.ProposalSet']", 'null': 'True', 'blank': 'True'}), 'space': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['spaces.Space']", 'null': 'True', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}) } } complete_apps = ['voting']
apache-2.0
quattor/aquilon
tests/broker/test_change_status_cluster.py
1
8145
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module for testing the cluster status commands.""" import unittest if __name__ == "__main__": import utils utils.import_depends() from brokertest import TestBrokerCommand class TestChangeClusterStatus(TestBrokerCommand): # This class is invoked after test_bind_esx_cluster, so we # know that we have a cluster (utecl1) which has 5 member hosts, # each of which are in "build" status. def test_100_BlockPromotion(self): command = ["change_status", "--hostname", "evh1.aqd-unittest.ms.com", "--buildstatus", "ready"] (out, err) = self.successtest(command) self.matchoutput(err, "Warning: requested status was 'ready' but " "resulting host status is 'almostready'.", command) command = "show host --hostname evh1.aqd-unittest.ms.com" out = self.commandtest(command.split(" ")) self.matchoutput(out, "Build Status: almostready", command) def test_110_PromoteCluster(self): command = ["change_status", "--cluster", "utecl1", "--buildstatus", "ready"] + self.valid_just_tcm err = self.statustest(command) # FIXME: the number of changed templates is not deterministic, we have # to figure out why. Until then make the check less strict to allow # unrelated changes to be tested. # self.matchoutput(err, "5/5 template", command) self.searchoutput(err, r'[1-5]/[1-5] template', command) # the almostready host should now be promoted command = "show host --hostname evh1.aqd-unittest.ms.com" out = self.commandtest(command.split(" ")) self.matchoutput(out, "Build Status: ready", command) # the build host should be unchanged command = "show host --hostname evh2.aqd-unittest.ms.com" out = self.commandtest(command.split(" ")) self.matchoutput(out, "Build Status: build", command) def test_120_BindDemotion(self): command = ["cluster", "--hostname", "evh1.aqd-unittest.ms.com", "--cluster", "utecl2"] + self.valid_just_tcm (out, err) = self.successtest(command) self.matchoutput(err, "Notice: changing build status of host " "evh1.aqd-unittest.ms.com from 'ready' to " "'almostready' because ESX cluster utecl2's " "state is 'build'.", command) command = "show host --hostname evh1.aqd-unittest.ms.com" out = self.commandtest(command.split(" ")) self.matchoutput(out, "Build Status: almostready", command) # Put the host back and confirm it can move to ready self.successtest(["cluster", "--hostname", "evh1.aqd-unittest.ms.com", "--cluster", "utecl1"] + self.valid_just_tcm) self.successtest(["change_status", "--hostname", "evh1.aqd-unittest.ms.com", "--buildstatus", "ready"] + self.valid_just_tcm) command = "show host --hostname evh1.aqd-unittest.ms.com" out = self.commandtest(command.split(" ")) self.matchoutput(out, "Build Status: ready", command) def test_130_DemoteCluster(self): command = ["change_status", "--cluster", "utecl1", "--buildstatus", "rebuild"] + self.valid_just_tcm err = self.statustest(command) # FIXME: the number of changed templates is not deterministic, we have # to figure out why. Until then make the check less strict to allow # unrelated changes to be tested. # self.matchoutput(err, "5/5 template", command) self.searchoutput(err, r'[1-5]/[1-5] template', command) # the ready host should be demoted command = "show host --hostname evh1.aqd-unittest.ms.com" out = self.commandtest(command.split(" ")) self.matchoutput(out, "Build Status: almostready", command) # the build host should be unchanged command = "show host --hostname evh2.aqd-unittest.ms.com" out = self.commandtest(command.split(" ")) self.matchoutput(out, "Build Status: build", command) def test_140_DecoClusterFail(self): # add a vm to make change fail self.noouttest(["add", "machine", "--machine", "evm1", "--cluster", "utecl1", "--model", "utmedium"]) command = ["change_status", "--cluster", "utecl1", "--buildstatus", "decommissioned"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Cannot change state to decommissioned, as " "ESX Cluster utecl1 has 1 VM(s).", command) command = ["change_status", "--hostname", "evh1.aqd-unittest.ms.com", "--buildstatus", "decommissioned"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Cannot change state to decommissioned, as " "ESX Cluster utecl1's state is not decommissioned.", command) # remove temp vm self.noouttest(["del", "machine", "--machine", "evm1"]) def test_145_DecoCluster(self): self.successtest(["change_status", "--cluster", "utecl1", "--buildstatus", "decommissioned"] + self.valid_just_tcm) # all vmhosts must be decoed. for i in range(1, 5): command = "show host --hostname evh%d.aqd-unittest.ms.com" % i out = self.commandtest(command.split(" ")) self.matchoutput(out, "Build Status: decommissioned", command) # can't add vm command = ["add", "machine", "--machine", "evm1", "--cluster", "utecl1", "--model", "utmedium"] out = self.badrequesttest(command) self.matchoutput(out, "Cannot add virtual machines to decommissioned holders.", command) # can't add host. command = ["cluster", "--hostname", "evh6.aqd-unittest.ms.com", "--cluster", "utecl1"] out = self.badrequesttest(command) self.matchoutput(out, "Cannot add hosts to decommissioned clusters.", command) # revert status changes self.successtest(["change_status", "--cluster", "utecl1", "--buildstatus", "rebuild"]) for i in range(1, 5): self.successtest(["change_status", "--hostname", "evh%d.aqd-unittest.ms.com" % i, "--buildstatus", "rebuild"]) def test_150_change_status_metacluster(self): command = ["change_status", "--metacluster", "utmc1", "--buildstatus", "ready"] self.statustest(command) def test_155_verify_metacluster(self): command = ["show_metacluster", "--metacluster", "utmc1"] out = self.commandtest(command) self.matchoutput(out, "Build Status: ready", command) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestChangeClusterStatus) unittest.TextTestRunner(verbosity=2).run(suite)
apache-2.0
gclenaghan/scikit-learn
doc/tutorial/text_analytics/solutions/exercise_01_language_train_model.py
25
2252
"""Build a language detector model The goal of this exercise is to train a linear classifier on text features that represent sequences of up to 3 consecutive characters so as to be recognize natural languages by using the frequencies of short character sequences as 'fingerprints'. """ # Author: Olivier Grisel <olivier.grisel@ensta.org> # License: Simplified BSD import sys from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import Perceptron from sklearn.pipeline import Pipeline from sklearn.datasets import load_files from sklearn.model_selection import train_test_split from sklearn import metrics # The training data folder must be passed as first argument languages_data_folder = sys.argv[1] dataset = load_files(languages_data_folder) # Split the dataset in training and test set: docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.5) # TASK: Build a an vectorizer that splits strings into sequence of 1 to 3 # characters instead of word tokens vectorizer = TfidfVectorizer(ngram_range=(1, 3), analyzer='char', use_idf=False) # TASK: Build a vectorizer / classifier pipeline using the previous analyzer # the pipeline instance should stored in a variable named clf clf = Pipeline([ ('vec', vectorizer), ('clf', Perceptron()), ]) # TASK: Fit the pipeline on the training set clf.fit(docs_train, y_train) # TASK: Predict the outcome on the testing set in a variable named y_predicted y_predicted = clf.predict(docs_test) # Print the classification report print(metrics.classification_report(y_test, y_predicted, target_names=dataset.target_names)) # Plot the confusion matrix cm = metrics.confusion_matrix(y_test, y_predicted) print(cm) #import pylab as pl #pl.matshow(cm, cmap=pl.cm.jet) #pl.show() # Predict the result on some short new sentences: sentences = [ u'This is a language detection test.', u'Ceci est un test de d\xe9tection de la langue.', u'Dies ist ein Test, um die Sprache zu erkennen.', ] predicted = clf.predict(sentences) for s, p in zip(sentences, predicted): print(u'The language of "%s" is "%s"' % (s, dataset.target_names[p]))
bsd-3-clause
GreenLunar/Bookie
bookie/tests/factory.py
6
3361
"""Provide tools for generating objects for testing purposes.""" from datetime import datetime from random import randint import random import string from bookie.models import DBSession from bookie.models import Bmark from bookie.models import Tag from bookie.models.applog import AppLog from bookie.models.auth import User from bookie.models.social import TwitterConnection from bookie.models.stats import ( StatBookmark, USER_CT, ) def random_int(max=1000): """Generate a random integer value :param max: Maximum value to hit. """ return randint(0, max) def random_string(length=None): """Generates a random string from urandom. :param length: Specify the number of chars in the generated string. """ chars = string.ascii_uppercase + string.digits str_length = length if length is not None else random_int() return unicode(u''.join(random.choice(chars) for x in range(str_length))) def random_url(): """Generate a random url that is totally bogus.""" url = u"http://{0}.com".format(random_string()) return url def make_applog(message=None, status=None): """Generate applog instances.""" if status is None: status = random_int(max=3) if message is None: message = random_string(100) alog = AppLog(**{ 'user': random_string(10), 'component': random_string(10), 'status': status, 'message': message, 'payload': u'', }) return alog def make_tag(name=None): if not name: name = random_string(255) return Tag(name) def make_twitter_connection(username='admin'): tconnection = TwitterConnection(username=username, is_active=True, last_connection=datetime.now(), uid=u'1022699448', access_key=u'dummy', access_secret=u'dummy', twitter_username='bookie', refresh_date=datetime.now()) DBSession.add(tconnection) DBSession.flush() return tconnection def make_bookmark(user=None, is_private=False): """Generate a fake bookmark for testing use.""" bmark = Bmark(random_url(), username=u"admin", desc=random_string(), ext=random_string(), is_private=is_private, tags=u"bookmarks") if user: bmark.username = user.username bmark.user = user DBSession.add(bmark) DBSession.flush() return bmark def make_user_bookmark_count(username, data, tstamp=None): """Generate a fake user bookmark count for testing use""" if tstamp is None: tstamp = datetime.utcnow() bmark_count = StatBookmark(tstamp=tstamp, attrib=USER_CT.format(username), data=data) DBSession.add(bmark_count) DBSession.flush() return [bmark_count.attrib, bmark_count.data, bmark_count.tstamp] def make_user(username=None): """Generate a fake user to test against.""" user = User() if not username: username = random_string(10) user.username = username DBSession.add(user) DBSession.flush() return user
agpl-3.0
XiaodunServerGroup/medicalmooc
common/lib/xmodule/xmodule/tests/test_progress.py
54
4783
"""Module progress tests""" import unittest from mock import Mock from xblock.field_data import DictFieldData from xmodule.progress import Progress from xmodule import x_module from . import get_test_system class ProgressTest(unittest.TestCase): ''' Test that basic Progress objects work. A Progress represents a fraction between 0 and 1. ''' not_started = Progress(0, 17) part_done = Progress(2, 6) half_done = Progress(3, 6) also_half_done = Progress(1, 2) done = Progress(7, 7) def test_create_object(self): # These should work: p = Progress(0, 2) p = Progress(1, 2) p = Progress(2, 2) p = Progress(2.5, 5.0) p = Progress(3.7, 12.3333) # These shouldn't self.assertRaises(ValueError, Progress, 0, 0) self.assertRaises(ValueError, Progress, 2, 0) self.assertRaises(ValueError, Progress, 1, -2) self.assertRaises(TypeError, Progress, 0, "all") # check complex numbers just for the heck of it :) self.assertRaises(TypeError, Progress, 2j, 3) def test_clamp(self): self.assertEqual((2, 2), Progress(3, 2).frac()) self.assertEqual((0, 2), Progress(-2, 2).frac()) def test_frac(self): p = Progress(1, 2) (a, b) = p.frac() self.assertEqual(a, 1) self.assertEqual(b, 2) def test_percent(self): self.assertEqual(self.not_started.percent(), 0) self.assertAlmostEqual(self.part_done.percent(), 33.33333333333333) self.assertEqual(self.half_done.percent(), 50) self.assertEqual(self.done.percent(), 100) self.assertEqual(self.half_done.percent(), self.also_half_done.percent()) def test_started(self): self.assertFalse(self.not_started.started()) self.assertTrue(self.part_done.started()) self.assertTrue(self.half_done.started()) self.assertTrue(self.done.started()) def test_inprogress(self): # only true if working on it self.assertFalse(self.done.inprogress()) self.assertFalse(self.not_started.inprogress()) self.assertTrue(self.part_done.inprogress()) self.assertTrue(self.half_done.inprogress()) def test_done(self): self.assertTrue(self.done.done()) self.assertFalse(self.half_done.done()) self.assertFalse(self.not_started.done()) def test_str(self): self.assertEqual(str(self.not_started), "0/17") self.assertEqual(str(self.part_done), "2/6") self.assertEqual(str(self.done), "7/7") def test_ternary_str(self): self.assertEqual(self.not_started.ternary_str(), "none") self.assertEqual(self.half_done.ternary_str(), "in_progress") self.assertEqual(self.done.ternary_str(), "done") def test_to_js_status(self): '''Test the Progress.to_js_status_str() method''' self.assertEqual(Progress.to_js_status_str(self.not_started), "none") self.assertEqual(Progress.to_js_status_str(self.half_done), "in_progress") self.assertEqual(Progress.to_js_status_str(self.done), "done") self.assertEqual(Progress.to_js_status_str(None), "0") def test_to_js_detail_str(self): '''Test the Progress.to_js_detail_str() method''' f = Progress.to_js_detail_str for p in (self.not_started, self.half_done, self.done): self.assertEqual(f(p), str(p)) # But None should be encoded as 0 self.assertEqual(f(None), "0") def test_add(self): '''Test the Progress.add_counts() method''' p = Progress(0, 2) p2 = Progress(1, 3) p3 = Progress(2, 5) pNone = None add = lambda a, b: Progress.add_counts(a, b).frac() self.assertEqual(add(p, p), (0, 4)) self.assertEqual(add(p, p2), (1, 5)) self.assertEqual(add(p2, p3), (3, 8)) self.assertEqual(add(p2, pNone), p2.frac()) self.assertEqual(add(pNone, p2), p2.frac()) def test_equality(self): '''Test that comparing Progress objects for equality works correctly.''' p = Progress(1, 2) p2 = Progress(2, 4) p3 = Progress(1, 2) self.assertTrue(p == p3) self.assertFalse(p == p2) # Check != while we're at it self.assertTrue(p != p2) self.assertFalse(p != p3) class ModuleProgressTest(unittest.TestCase): ''' Test that get_progress() does the right thing for the different modules ''' def test_xmodule_default(self): '''Make sure default get_progress exists, returns None''' xm = x_module.XModule(Mock(), get_test_system(), DictFieldData({'location': 'a://b/c/d/e'}), Mock()) p = xm.get_progress() self.assertEqual(p, None)
agpl-3.0
damien-dg/horizon
horizon/context_processors.py
92
1455
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, 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. """ Context processors used by Horizon. """ from horizon import conf def horizon(request): """The main Horizon context processor. Required for Horizon to function. It adds the Horizon config to the context as well as setting the names ``True`` and ``False`` in the context to their boolean equivalents for convenience. .. warning:: Don't put API calls in context processors; they will be called once for each template/template fragment which takes context that is used to render the complete output. """ context = {"HORIZON_CONFIG": conf.HORIZON_CONFIG, "True": True, "False": False} return context
apache-2.0
leppa/home-assistant
homeassistant/components/mqtt/light/schema_basic.py
3
31821
""" Support for MQTT lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.mqtt/ """ import logging import voluptuous as vol from homeassistant.components import mqtt from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_WHITE_VALUE, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_WHITE_VALUE, Light, ) from homeassistant.components.mqtt import ( CONF_COMMAND_TOPIC, CONF_QOS, CONF_RETAIN, CONF_STATE_TOPIC, CONF_UNIQUE_ID, MqttAttributes, MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo, subscription, ) from homeassistant.const import ( CONF_BRIGHTNESS, CONF_COLOR_TEMP, CONF_DEVICE, CONF_EFFECT, CONF_HS, CONF_NAME, CONF_OPTIMISTIC, CONF_PAYLOAD_OFF, CONF_PAYLOAD_ON, CONF_RGB, CONF_STATE, CONF_VALUE_TEMPLATE, CONF_WHITE_VALUE, CONF_XY, STATE_ON, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.restore_state import RestoreEntity import homeassistant.util.color as color_util from .schema import MQTT_LIGHT_SCHEMA_SCHEMA _LOGGER = logging.getLogger(__name__) CONF_BRIGHTNESS_COMMAND_TOPIC = "brightness_command_topic" CONF_BRIGHTNESS_SCALE = "brightness_scale" CONF_BRIGHTNESS_STATE_TOPIC = "brightness_state_topic" CONF_BRIGHTNESS_VALUE_TEMPLATE = "brightness_value_template" CONF_COLOR_TEMP_COMMAND_TEMPLATE = "color_temp_command_template" CONF_COLOR_TEMP_COMMAND_TOPIC = "color_temp_command_topic" CONF_COLOR_TEMP_STATE_TOPIC = "color_temp_state_topic" CONF_COLOR_TEMP_VALUE_TEMPLATE = "color_temp_value_template" CONF_EFFECT_COMMAND_TOPIC = "effect_command_topic" CONF_EFFECT_LIST = "effect_list" CONF_EFFECT_STATE_TOPIC = "effect_state_topic" CONF_EFFECT_VALUE_TEMPLATE = "effect_value_template" CONF_HS_COMMAND_TOPIC = "hs_command_topic" CONF_HS_STATE_TOPIC = "hs_state_topic" CONF_HS_VALUE_TEMPLATE = "hs_value_template" CONF_RGB_COMMAND_TEMPLATE = "rgb_command_template" CONF_RGB_COMMAND_TOPIC = "rgb_command_topic" CONF_RGB_STATE_TOPIC = "rgb_state_topic" CONF_RGB_VALUE_TEMPLATE = "rgb_value_template" CONF_STATE_VALUE_TEMPLATE = "state_value_template" CONF_XY_COMMAND_TOPIC = "xy_command_topic" CONF_XY_STATE_TOPIC = "xy_state_topic" CONF_XY_VALUE_TEMPLATE = "xy_value_template" CONF_WHITE_VALUE_COMMAND_TOPIC = "white_value_command_topic" CONF_WHITE_VALUE_SCALE = "white_value_scale" CONF_WHITE_VALUE_STATE_TOPIC = "white_value_state_topic" CONF_WHITE_VALUE_TEMPLATE = "white_value_template" CONF_ON_COMMAND_TYPE = "on_command_type" DEFAULT_BRIGHTNESS_SCALE = 255 DEFAULT_NAME = "MQTT Light" DEFAULT_OPTIMISTIC = False DEFAULT_PAYLOAD_OFF = "OFF" DEFAULT_PAYLOAD_ON = "ON" DEFAULT_WHITE_VALUE_SCALE = 255 DEFAULT_ON_COMMAND_TYPE = "last" VALUES_ON_COMMAND_TYPE = ["first", "last", "brightness"] PLATFORM_SCHEMA_BASIC = ( mqtt.MQTT_RW_PLATFORM_SCHEMA.extend( { vol.Optional(CONF_BRIGHTNESS_COMMAND_TOPIC): mqtt.valid_publish_topic, vol.Optional( CONF_BRIGHTNESS_SCALE, default=DEFAULT_BRIGHTNESS_SCALE ): vol.All(vol.Coerce(int), vol.Range(min=1)), vol.Optional(CONF_BRIGHTNESS_STATE_TOPIC): mqtt.valid_subscribe_topic, vol.Optional(CONF_BRIGHTNESS_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_COLOR_TEMP_COMMAND_TEMPLATE): cv.template, vol.Optional(CONF_COLOR_TEMP_COMMAND_TOPIC): mqtt.valid_publish_topic, vol.Optional(CONF_COLOR_TEMP_STATE_TOPIC): mqtt.valid_subscribe_topic, vol.Optional(CONF_COLOR_TEMP_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_DEVICE): mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA, vol.Optional(CONF_EFFECT_COMMAND_TOPIC): mqtt.valid_publish_topic, vol.Optional(CONF_EFFECT_LIST): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_EFFECT_STATE_TOPIC): mqtt.valid_subscribe_topic, vol.Optional(CONF_EFFECT_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_HS_COMMAND_TOPIC): mqtt.valid_publish_topic, vol.Optional(CONF_HS_STATE_TOPIC): mqtt.valid_subscribe_topic, vol.Optional(CONF_HS_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_ON_COMMAND_TYPE, default=DEFAULT_ON_COMMAND_TYPE): vol.In( VALUES_ON_COMMAND_TYPE ), vol.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean, vol.Optional(CONF_PAYLOAD_OFF, default=DEFAULT_PAYLOAD_OFF): cv.string, vol.Optional(CONF_PAYLOAD_ON, default=DEFAULT_PAYLOAD_ON): cv.string, vol.Optional(CONF_RGB_COMMAND_TEMPLATE): cv.template, vol.Optional(CONF_RGB_COMMAND_TOPIC): mqtt.valid_publish_topic, vol.Optional(CONF_RGB_STATE_TOPIC): mqtt.valid_subscribe_topic, vol.Optional(CONF_RGB_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_STATE_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_UNIQUE_ID): cv.string, vol.Optional(CONF_WHITE_VALUE_COMMAND_TOPIC): mqtt.valid_publish_topic, vol.Optional( CONF_WHITE_VALUE_SCALE, default=DEFAULT_WHITE_VALUE_SCALE ): vol.All(vol.Coerce(int), vol.Range(min=1)), vol.Optional(CONF_WHITE_VALUE_STATE_TOPIC): mqtt.valid_subscribe_topic, vol.Optional(CONF_WHITE_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_XY_COMMAND_TOPIC): mqtt.valid_publish_topic, vol.Optional(CONF_XY_STATE_TOPIC): mqtt.valid_subscribe_topic, vol.Optional(CONF_XY_VALUE_TEMPLATE): cv.template, } ) .extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema) .extend(mqtt.MQTT_JSON_ATTRS_SCHEMA.schema) .extend(MQTT_LIGHT_SCHEMA_SCHEMA.schema) ) async def async_setup_entity_basic( config, async_add_entities, config_entry, discovery_hash=None ): """Set up a MQTT Light.""" config.setdefault(CONF_STATE_VALUE_TEMPLATE, config.get(CONF_VALUE_TEMPLATE)) async_add_entities([MqttLight(config, config_entry, discovery_hash)]) # pylint: disable=too-many-ancestors class MqttLight( MqttAttributes, MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo, Light, RestoreEntity, ): """Representation of a MQTT light.""" def __init__(self, config, config_entry, discovery_hash): """Initialize MQTT light.""" self._state = False self._sub_state = None self._brightness = None self._hs = None self._color_temp = None self._effect = None self._white_value = None self._topic = None self._payload = None self._templates = None self._optimistic = False self._optimistic_rgb = False self._optimistic_brightness = False self._optimistic_color_temp = False self._optimistic_effect = False self._optimistic_hs = False self._optimistic_white_value = False self._optimistic_xy = False self._unique_id = config.get(CONF_UNIQUE_ID) # Load config self._setup_from_config(config) device_config = config.get(CONF_DEVICE) MqttAttributes.__init__(self, config) MqttAvailability.__init__(self, config) MqttDiscoveryUpdate.__init__(self, discovery_hash, self.discovery_update) MqttEntityDeviceInfo.__init__(self, device_config, config_entry) async def async_added_to_hass(self): """Subscribe to MQTT events.""" await super().async_added_to_hass() await self._subscribe_topics() async def discovery_update(self, discovery_payload): """Handle updated discovery message.""" config = PLATFORM_SCHEMA_BASIC(discovery_payload) self._setup_from_config(config) await self.attributes_discovery_update(config) await self.availability_discovery_update(config) await self.device_info_discovery_update(config) await self._subscribe_topics() self.async_write_ha_state() def _setup_from_config(self, config): """(Re)Setup the entity.""" self._config = config topic = { key: config.get(key) for key in ( CONF_BRIGHTNESS_COMMAND_TOPIC, CONF_BRIGHTNESS_STATE_TOPIC, CONF_COLOR_TEMP_COMMAND_TOPIC, CONF_COLOR_TEMP_STATE_TOPIC, CONF_COMMAND_TOPIC, CONF_EFFECT_COMMAND_TOPIC, CONF_EFFECT_STATE_TOPIC, CONF_HS_COMMAND_TOPIC, CONF_HS_STATE_TOPIC, CONF_RGB_COMMAND_TOPIC, CONF_RGB_STATE_TOPIC, CONF_STATE_TOPIC, CONF_WHITE_VALUE_COMMAND_TOPIC, CONF_WHITE_VALUE_STATE_TOPIC, CONF_XY_COMMAND_TOPIC, CONF_XY_STATE_TOPIC, ) } self._topic = topic self._payload = {"on": config[CONF_PAYLOAD_ON], "off": config[CONF_PAYLOAD_OFF]} self._templates = { CONF_BRIGHTNESS: config.get(CONF_BRIGHTNESS_VALUE_TEMPLATE), CONF_COLOR_TEMP: config.get(CONF_COLOR_TEMP_VALUE_TEMPLATE), CONF_COLOR_TEMP_COMMAND_TEMPLATE: config.get( CONF_COLOR_TEMP_COMMAND_TEMPLATE ), CONF_EFFECT: config.get(CONF_EFFECT_VALUE_TEMPLATE), CONF_HS: config.get(CONF_HS_VALUE_TEMPLATE), CONF_RGB: config.get(CONF_RGB_VALUE_TEMPLATE), CONF_RGB_COMMAND_TEMPLATE: config.get(CONF_RGB_COMMAND_TEMPLATE), CONF_STATE: config.get(CONF_STATE_VALUE_TEMPLATE), CONF_WHITE_VALUE: config.get(CONF_WHITE_VALUE_TEMPLATE), CONF_XY: config.get(CONF_XY_VALUE_TEMPLATE), } optimistic = config[CONF_OPTIMISTIC] self._optimistic = optimistic or topic[CONF_STATE_TOPIC] is None self._optimistic_rgb = optimistic or topic[CONF_RGB_STATE_TOPIC] is None self._optimistic_brightness = ( optimistic or ( topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None and topic[CONF_BRIGHTNESS_STATE_TOPIC] is None ) or ( topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is None and topic[CONF_RGB_STATE_TOPIC] is None ) ) self._optimistic_color_temp = ( optimistic or topic[CONF_COLOR_TEMP_STATE_TOPIC] is None ) self._optimistic_effect = optimistic or topic[CONF_EFFECT_STATE_TOPIC] is None self._optimistic_hs = optimistic or topic[CONF_HS_STATE_TOPIC] is None self._optimistic_white_value = ( optimistic or topic[CONF_WHITE_VALUE_STATE_TOPIC] is None ) self._optimistic_xy = optimistic or topic[CONF_XY_STATE_TOPIC] is None async def _subscribe_topics(self): """(Re)Subscribe to topics.""" topics = {} templates = {} for key, tpl in list(self._templates.items()): if tpl is None: templates[key] = lambda value: value else: tpl.hass = self.hass templates[key] = tpl.async_render_with_possible_json_value last_state = await self.async_get_last_state() @callback def state_received(msg): """Handle new MQTT messages.""" payload = templates[CONF_STATE](msg.payload) if not payload: _LOGGER.debug("Ignoring empty state message from '%s'", msg.topic) return if payload == self._payload["on"]: self._state = True elif payload == self._payload["off"]: self._state = False self.async_write_ha_state() if self._topic[CONF_STATE_TOPIC] is not None: topics[CONF_STATE_TOPIC] = { "topic": self._topic[CONF_STATE_TOPIC], "msg_callback": state_received, "qos": self._config[CONF_QOS], } elif self._optimistic and last_state: self._state = last_state.state == STATE_ON @callback def brightness_received(msg): """Handle new MQTT messages for the brightness.""" payload = templates[CONF_BRIGHTNESS](msg.payload) if not payload: _LOGGER.debug("Ignoring empty brightness message from '%s'", msg.topic) return device_value = float(payload) percent_bright = device_value / self._config[CONF_BRIGHTNESS_SCALE] self._brightness = percent_bright * 255 self.async_write_ha_state() if self._topic[CONF_BRIGHTNESS_STATE_TOPIC] is not None: topics[CONF_BRIGHTNESS_STATE_TOPIC] = { "topic": self._topic[CONF_BRIGHTNESS_STATE_TOPIC], "msg_callback": brightness_received, "qos": self._config[CONF_QOS], } self._brightness = 255 elif ( self._optimistic_brightness and last_state and last_state.attributes.get(ATTR_BRIGHTNESS) ): self._brightness = last_state.attributes.get(ATTR_BRIGHTNESS) elif self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None: self._brightness = 255 else: self._brightness = None @callback def rgb_received(msg): """Handle new MQTT messages for RGB.""" payload = templates[CONF_RGB](msg.payload) if not payload: _LOGGER.debug("Ignoring empty rgb message from '%s'", msg.topic) return rgb = [int(val) for val in payload.split(",")] self._hs = color_util.color_RGB_to_hs(*rgb) if self._topic[CONF_BRIGHTNESS_STATE_TOPIC] is None: percent_bright = float(color_util.color_RGB_to_hsv(*rgb)[2]) / 100.0 self._brightness = percent_bright * 255 self.async_write_ha_state() if self._topic[CONF_RGB_STATE_TOPIC] is not None: topics[CONF_RGB_STATE_TOPIC] = { "topic": self._topic[CONF_RGB_STATE_TOPIC], "msg_callback": rgb_received, "qos": self._config[CONF_QOS], } self._hs = (0, 0) if ( self._optimistic_rgb and last_state and last_state.attributes.get(ATTR_HS_COLOR) ): self._hs = last_state.attributes.get(ATTR_HS_COLOR) elif self._topic[CONF_RGB_COMMAND_TOPIC] is not None: self._hs = (0, 0) @callback def color_temp_received(msg): """Handle new MQTT messages for color temperature.""" payload = templates[CONF_COLOR_TEMP](msg.payload) if not payload: _LOGGER.debug("Ignoring empty color temp message from '%s'", msg.topic) return self._color_temp = int(payload) self.async_write_ha_state() if self._topic[CONF_COLOR_TEMP_STATE_TOPIC] is not None: topics[CONF_COLOR_TEMP_STATE_TOPIC] = { "topic": self._topic[CONF_COLOR_TEMP_STATE_TOPIC], "msg_callback": color_temp_received, "qos": self._config[CONF_QOS], } self._color_temp = 150 if ( self._optimistic_color_temp and last_state and last_state.attributes.get(ATTR_COLOR_TEMP) ): self._color_temp = last_state.attributes.get(ATTR_COLOR_TEMP) elif self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC] is not None: self._color_temp = 150 else: self._color_temp = None @callback def effect_received(msg): """Handle new MQTT messages for effect.""" payload = templates[CONF_EFFECT](msg.payload) if not payload: _LOGGER.debug("Ignoring empty effect message from '%s'", msg.topic) return self._effect = payload self.async_write_ha_state() if self._topic[CONF_EFFECT_STATE_TOPIC] is not None: topics[CONF_EFFECT_STATE_TOPIC] = { "topic": self._topic[CONF_EFFECT_STATE_TOPIC], "msg_callback": effect_received, "qos": self._config[CONF_QOS], } self._effect = "none" if ( self._optimistic_effect and last_state and last_state.attributes.get(ATTR_EFFECT) ): self._effect = last_state.attributes.get(ATTR_EFFECT) elif self._topic[CONF_EFFECT_COMMAND_TOPIC] is not None: self._effect = "none" else: self._effect = None @callback def hs_received(msg): """Handle new MQTT messages for hs color.""" payload = templates[CONF_HS](msg.payload) if not payload: _LOGGER.debug("Ignoring empty hs message from '%s'", msg.topic) return try: hs_color = [float(val) for val in payload.split(",", 2)] self._hs = hs_color self.async_write_ha_state() except ValueError: _LOGGER.debug("Failed to parse hs state update: '%s'", payload) if self._topic[CONF_HS_STATE_TOPIC] is not None: topics[CONF_HS_STATE_TOPIC] = { "topic": self._topic[CONF_HS_STATE_TOPIC], "msg_callback": hs_received, "qos": self._config[CONF_QOS], } self._hs = (0, 0) if ( self._optimistic_hs and last_state and last_state.attributes.get(ATTR_HS_COLOR) ): self._hs = last_state.attributes.get(ATTR_HS_COLOR) elif self._topic[CONF_HS_COMMAND_TOPIC] is not None: self._hs = (0, 0) @callback def white_value_received(msg): """Handle new MQTT messages for white value.""" payload = templates[CONF_WHITE_VALUE](msg.payload) if not payload: _LOGGER.debug("Ignoring empty white value message from '%s'", msg.topic) return device_value = float(payload) percent_white = device_value / self._config[CONF_WHITE_VALUE_SCALE] self._white_value = percent_white * 255 self.async_write_ha_state() if self._topic[CONF_WHITE_VALUE_STATE_TOPIC] is not None: topics[CONF_WHITE_VALUE_STATE_TOPIC] = { "topic": self._topic[CONF_WHITE_VALUE_STATE_TOPIC], "msg_callback": white_value_received, "qos": self._config[CONF_QOS], } self._white_value = 255 elif ( self._optimistic_white_value and last_state and last_state.attributes.get(ATTR_WHITE_VALUE) ): self._white_value = last_state.attributes.get(ATTR_WHITE_VALUE) elif self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC] is not None: self._white_value = 255 else: self._white_value = None @callback def xy_received(msg): """Handle new MQTT messages for xy color.""" payload = templates[CONF_XY](msg.payload) if not payload: _LOGGER.debug("Ignoring empty xy-color message from '%s'", msg.topic) return xy_color = [float(val) for val in payload.split(",")] self._hs = color_util.color_xy_to_hs(*xy_color) self.async_write_ha_state() if self._topic[CONF_XY_STATE_TOPIC] is not None: topics[CONF_XY_STATE_TOPIC] = { "topic": self._topic[CONF_XY_STATE_TOPIC], "msg_callback": xy_received, "qos": self._config[CONF_QOS], } self._hs = (0, 0) if ( self._optimistic_xy and last_state and last_state.attributes.get(ATTR_HS_COLOR) ): self._hs = last_state.attributes.get(ATTR_HS_COLOR) elif self._topic[CONF_XY_COMMAND_TOPIC] is not None: self._hs = (0, 0) self._sub_state = await subscription.async_subscribe_topics( self.hass, self._sub_state, topics ) async def async_will_remove_from_hass(self): """Unsubscribe when removed.""" self._sub_state = await subscription.async_unsubscribe_topics( self.hass, self._sub_state ) await MqttAttributes.async_will_remove_from_hass(self) await MqttAvailability.async_will_remove_from_hass(self) @property def brightness(self): """Return the brightness of this light between 0..255.""" brightness = self._brightness if brightness: brightness = min(round(brightness), 255) return brightness @property def hs_color(self): """Return the hs color value.""" return self._hs @property def color_temp(self): """Return the color temperature in mired.""" return self._color_temp @property def white_value(self): """Return the white property.""" white_value = self._white_value if white_value: white_value = min(round(white_value), 255) return white_value @property def should_poll(self): """No polling needed for a MQTT light.""" return False @property def name(self): """Return the name of the device if any.""" return self._config[CONF_NAME] @property def unique_id(self): """Return a unique ID.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def assumed_state(self): """Return true if we do optimistic updates.""" return self._optimistic @property def effect_list(self): """Return the list of supported effects.""" return self._config.get(CONF_EFFECT_LIST) @property def effect(self): """Return the current effect.""" return self._effect @property def supported_features(self): """Flag supported features.""" supported_features = 0 supported_features |= self._topic[CONF_RGB_COMMAND_TOPIC] is not None and ( SUPPORT_COLOR | SUPPORT_BRIGHTNESS ) supported_features |= ( self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None and SUPPORT_BRIGHTNESS ) supported_features |= ( self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC] is not None and SUPPORT_COLOR_TEMP ) supported_features |= ( self._topic[CONF_EFFECT_COMMAND_TOPIC] is not None and SUPPORT_EFFECT ) supported_features |= ( self._topic[CONF_HS_COMMAND_TOPIC] is not None and SUPPORT_COLOR ) supported_features |= ( self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC] is not None and SUPPORT_WHITE_VALUE ) supported_features |= ( self._topic[CONF_XY_COMMAND_TOPIC] is not None and SUPPORT_COLOR ) return supported_features async def async_turn_on(self, **kwargs): """Turn the device on. This method is a coroutine. """ should_update = False on_command_type = self._config[CONF_ON_COMMAND_TYPE] if on_command_type == "first": mqtt.async_publish( self.hass, self._topic[CONF_COMMAND_TOPIC], self._payload["on"], self._config[CONF_QOS], self._config[CONF_RETAIN], ) should_update = True # If brightness is being used instead of an on command, make sure # there is a brightness input. Either set the brightness to our # saved value or the maximum value if this is the first call elif on_command_type == "brightness": if ATTR_BRIGHTNESS not in kwargs: kwargs[ATTR_BRIGHTNESS] = self._brightness if self._brightness else 255 if ATTR_HS_COLOR in kwargs and self._topic[CONF_RGB_COMMAND_TOPIC] is not None: hs_color = kwargs[ATTR_HS_COLOR] # If there's a brightness topic set, we don't want to scale the RGB # values given using the brightness. if self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None: brightness = 255 else: brightness = kwargs.get( ATTR_BRIGHTNESS, self._brightness if self._brightness else 255 ) rgb = color_util.color_hsv_to_RGB( hs_color[0], hs_color[1], brightness / 255 * 100 ) tpl = self._templates[CONF_RGB_COMMAND_TEMPLATE] if tpl: rgb_color_str = tpl.async_render( {"red": rgb[0], "green": rgb[1], "blue": rgb[2]} ) else: rgb_color_str = "{},{},{}".format(*rgb) mqtt.async_publish( self.hass, self._topic[CONF_RGB_COMMAND_TOPIC], rgb_color_str, self._config[CONF_QOS], self._config[CONF_RETAIN], ) if self._optimistic_rgb: self._hs = kwargs[ATTR_HS_COLOR] should_update = True if ATTR_HS_COLOR in kwargs and self._topic[CONF_HS_COMMAND_TOPIC] is not None: hs_color = kwargs[ATTR_HS_COLOR] mqtt.async_publish( self.hass, self._topic[CONF_HS_COMMAND_TOPIC], "{},{}".format(*hs_color), self._config[CONF_QOS], self._config[CONF_RETAIN], ) if self._optimistic_hs: self._hs = kwargs[ATTR_HS_COLOR] should_update = True if ATTR_HS_COLOR in kwargs and self._topic[CONF_XY_COMMAND_TOPIC] is not None: xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR]) mqtt.async_publish( self.hass, self._topic[CONF_XY_COMMAND_TOPIC], "{},{}".format(*xy_color), self._config[CONF_QOS], self._config[CONF_RETAIN], ) if self._optimistic_xy: self._hs = kwargs[ATTR_HS_COLOR] should_update = True if ( ATTR_BRIGHTNESS in kwargs and self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None ): percent_bright = float(kwargs[ATTR_BRIGHTNESS]) / 255 brightness_scale = self._config[CONF_BRIGHTNESS_SCALE] device_brightness = min( round(percent_bright * brightness_scale), brightness_scale ) mqtt.async_publish( self.hass, self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC], device_brightness, self._config[CONF_QOS], self._config[CONF_RETAIN], ) if self._optimistic_brightness: self._brightness = kwargs[ATTR_BRIGHTNESS] should_update = True elif ( ATTR_BRIGHTNESS in kwargs and ATTR_HS_COLOR not in kwargs and self._topic[CONF_RGB_COMMAND_TOPIC] is not None ): rgb = color_util.color_hsv_to_RGB( self._hs[0], self._hs[1], kwargs[ATTR_BRIGHTNESS] / 255 * 100 ) tpl = self._templates[CONF_RGB_COMMAND_TEMPLATE] if tpl: rgb_color_str = tpl.async_render( {"red": rgb[0], "green": rgb[1], "blue": rgb[2]} ) else: rgb_color_str = "{},{},{}".format(*rgb) mqtt.async_publish( self.hass, self._topic[CONF_RGB_COMMAND_TOPIC], rgb_color_str, self._config[CONF_QOS], self._config[CONF_RETAIN], ) if self._optimistic_brightness: self._brightness = kwargs[ATTR_BRIGHTNESS] should_update = True if ( ATTR_COLOR_TEMP in kwargs and self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC] is not None ): color_temp = int(kwargs[ATTR_COLOR_TEMP]) tpl = self._templates[CONF_COLOR_TEMP_COMMAND_TEMPLATE] if tpl: color_temp = tpl.async_render({"value": color_temp}) mqtt.async_publish( self.hass, self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC], color_temp, self._config[CONF_QOS], self._config[CONF_RETAIN], ) if self._optimistic_color_temp: self._color_temp = kwargs[ATTR_COLOR_TEMP] should_update = True if ATTR_EFFECT in kwargs and self._topic[CONF_EFFECT_COMMAND_TOPIC] is not None: effect = kwargs[ATTR_EFFECT] if effect in self._config.get(CONF_EFFECT_LIST): mqtt.async_publish( self.hass, self._topic[CONF_EFFECT_COMMAND_TOPIC], effect, self._config[CONF_QOS], self._config[CONF_RETAIN], ) if self._optimistic_effect: self._effect = kwargs[ATTR_EFFECT] should_update = True if ( ATTR_WHITE_VALUE in kwargs and self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC] is not None ): percent_white = float(kwargs[ATTR_WHITE_VALUE]) / 255 white_scale = self._config[CONF_WHITE_VALUE_SCALE] device_white_value = min(round(percent_white * white_scale), white_scale) mqtt.async_publish( self.hass, self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC], device_white_value, self._config[CONF_QOS], self._config[CONF_RETAIN], ) if self._optimistic_white_value: self._white_value = kwargs[ATTR_WHITE_VALUE] should_update = True if on_command_type == "last": mqtt.async_publish( self.hass, self._topic[CONF_COMMAND_TOPIC], self._payload["on"], self._config[CONF_QOS], self._config[CONF_RETAIN], ) should_update = True if self._optimistic: # Optimistically assume that the light has changed state. self._state = True should_update = True if should_update: self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the device off. This method is a coroutine. """ mqtt.async_publish( self.hass, self._topic[CONF_COMMAND_TOPIC], self._payload["off"], self._config[CONF_QOS], self._config[CONF_RETAIN], ) if self._optimistic: # Optimistically assume that the light has changed state. self._state = False self.async_write_ha_state()
apache-2.0
BT-fgarbely/odoo
addons/account_payment/report/payment_order.py
378
2974
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import osv from openerp.report import report_sxw class payment_order(report_sxw.rml_parse): def __init__(self, cr, uid, name, context=None): super(payment_order, self).__init__(cr, uid, name, context=context) self.localcontext.update( { 'time': time, 'get_invoice_name': self._get_invoice_name, 'get_amount_total_in_currency': self._get_amount_total_in_currency, 'get_amount_total': self._get_amount_total, 'get_account_name': self._get_account_name, }) def _get_invoice_name(self, invoice_id): if invoice_id: value_name = self.pool['account.invoice'].name_get(self.cr, self.uid, [invoice_id]) if value_name: return value_name[0][1] return False def _get_amount_total_in_currency(self, payment): total = 0.0 if payment.line_ids: currency_cmp = payment.line_ids[0].currency.id else: return False for line in payment.line_ids: if currency_cmp == line.currency.id: total += line.amount_currency else: return False return total def _get_amount_total(self, payment): total = 0.0 if not payment.line_ids: return False for line in payment.line_ids: total += line.amount return total def _get_account_name(self,bank_id): if bank_id: value_name = self.pool['res.partner.bank'].name_get(self.cr, self.uid, [bank_id]) if value_name: return value_name[0][1] return False class report_paymentorder(osv.AbstractModel): _name = 'report.account_payment.report_paymentorder' _inherit = 'report.abstract_report' _template = 'account_payment.report_paymentorder' _wrapped_report_class = payment_order # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
wevote/WeVoteServer
image/views_admin.py
1
9402
# image/views_admin.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from .controllers import cache_all_kind_of_images_locally_for_all_organizations, \ cache_all_kind_of_images_locally_for_all_voters, \ cache_and_create_resized_images_for_organization, create_resized_images_for_all_organizations, \ cache_and_create_resized_images_for_voter, create_resized_images_for_all_voters, \ retrieve_all_images_for_one_candidate, retrieve_all_images_for_one_organization, retrieve_all_images_for_one_voter from admin_tools.views import redirect_to_sign_in_page from candidate.models import CandidateManager from django.contrib.auth.decorators import login_required from django.contrib.messages import get_messages from django.shortcuts import render from organization.models import OrganizationManager from voter.models import fetch_voter_id_from_voter_device_link, voter_has_authority import wevote_functions.admin from wevote_functions.functions import convert_to_int, get_voter_api_device_id, positive_value_exists logger = wevote_functions.admin.get_logger(__name__) @login_required def cache_images_locally_for_all_organizations_view(request): # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'admin'} if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) messages_on_stage = get_messages(request) cache_images_locally_for_all_organizations_results = cache_all_kind_of_images_locally_for_all_organizations() template_values = { 'messages_on_stage': messages_on_stage, 'cache_images_for_all_organizations': cache_images_locally_for_all_organizations_results, } return render(request, 'image/cache_images_locally_for_all_organizations.html', template_values) @login_required def cache_images_locally_for_all_voters_view(request): # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'admin'} if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) voter_api_device_id = get_voter_api_device_id(request) # We look in the cookies for voter_api_device_id voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id) voter_id = convert_to_int(voter_id) messages_on_stage = get_messages(request) cache_images_locally_for_all_voters_results = cache_all_kind_of_images_locally_for_all_voters() template_values = { 'messages_on_stage': messages_on_stage, 'cache_images_for_all_voters': cache_images_locally_for_all_voters_results, 'voter_id_signed_in': voter_id } return render(request, 'image/cache_images_locally_for_all_voters.html', template_values) @login_required def create_resized_images_for_all_organizations_view(request): # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'admin'} if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) messages_on_stage = get_messages(request) create_resized_images_for_organization_results = create_resized_images_for_all_organizations() template_values = { 'messages_on_stage': messages_on_stage, 'create_resized_images_for_organization': create_resized_images_for_organization_results, 'organization_we_vote_id': "" } return render(request, 'image/create_resized_images_for_organization.html', template_values) @login_required def create_resized_images_for_organization_view(request, organization_we_vote_id): # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'admin'} if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) messages_on_stage = get_messages(request) if positive_value_exists(organization_we_vote_id): organization_manager = OrganizationManager() organization_results = organization_manager.retrieve_organization_from_we_vote_id(organization_we_vote_id) if organization_results['success']: organization = organization_results['organization'] create_resized_images_for_organization_results = cache_and_create_resized_images_for_organization( organization_we_vote_id) else: create_resized_images_for_organization_results = {} template_values = { 'messages_on_stage': messages_on_stage, 'create_resized_images_for_organization': create_resized_images_for_organization_results, 'organization_we_vote_id': organization_we_vote_id, 'organization': organization } return render(request, 'image/create_resized_images_for_organization.html', template_values) @login_required def create_resized_images_for_voters_view(request, voter_id): # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'admin'} if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) voter_id = convert_to_int(voter_id) messages_on_stage = get_messages(request) if positive_value_exists(voter_id): create_resized_images_for_voters_results = cache_and_create_resized_images_for_voter(voter_id) else: create_resized_images_for_voters_results = create_resized_images_for_all_voters() template_values = { 'messages_on_stage': messages_on_stage, 'create_resized_images_for_voters': create_resized_images_for_voters_results, 'voter_id_signed_in': voter_id } return render(request, 'image/create_resized_images_for_voters.html', template_values) @login_required def images_for_one_voter_view(request, voter_id): # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'admin'} if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) voter_id = convert_to_int(voter_id) messages_on_stage = get_messages(request) we_vote_image_list = retrieve_all_images_for_one_voter(voter_id) template_values = { 'messages_on_stage': messages_on_stage, 'images_for_one_voter': we_vote_image_list, 'voter_id': voter_id } return render(request, 'image/images_for_one_voter.html', template_values) @login_required def images_for_one_candidate_view(request, candidate_we_vote_id): # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'admin'} if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) candidate = None if positive_value_exists(candidate_we_vote_id): candidate_manager = CandidateManager() candidate_results = candidate_manager.retrieve_candidate_from_we_vote_id( candidate_we_vote_id) if candidate_results['success']: candidate = candidate_results['candidate'] messages_on_stage = get_messages(request) we_vote_image_list = retrieve_all_images_for_one_candidate(candidate_we_vote_id) template_values = { 'messages_on_stage': messages_on_stage, 'images_for_one_candidate': we_vote_image_list, 'candidate_we_vote_id': candidate_we_vote_id, 'candidate': candidate } return render(request, 'image/images_for_one_candidate.html', template_values) @login_required def images_for_one_organization_view(request, organization_we_vote_id): # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'admin'} if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) if positive_value_exists(organization_we_vote_id): organization_manager = OrganizationManager() organization_results = organization_manager.retrieve_organization_from_we_vote_id(organization_we_vote_id) if organization_results['success']: organization = organization_results['organization'] messages_on_stage = get_messages(request) we_vote_image_list = retrieve_all_images_for_one_organization(organization_we_vote_id) template_values = { 'messages_on_stage': messages_on_stage, 'images_for_one_organization': we_vote_image_list, 'organization_we_vote_id': organization_we_vote_id, 'organization': organization } return render(request, 'image/images_for_one_organization.html', template_values)
mit
the-packet-thrower/pynet
Week06/library/eos_vrrp.py
8
26971
#!/usr/bin/python # # Copyright (c) 2015, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # Neither the name of Arista Networks nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # DOCUMENTATION = """ --- module: eos_vrrp short_description: Manage EOS VRRP resources description: - This module will manage VRRP configurations on EOS nodes version_added: 1.2.0 category: VRRP author: Arista EOS+ requirements: - Arista EOS 4.13.7M or later with command API enabled - Python Client for eAPI 0.4.0 or later notes: - All configuration is idempotent unless otherwise specified - Supports eos metaparameters for using the eAPI transport - Supports stateful resource configuration. options: interface: description: - The interface on which the VRRP is configured required: true default: null choices: [] aliases: [] version_added: 1.2.0 vrid: description: - The unique identifying ID of the VRRP on its interface required: true default: null choices: [] aliases: [] version_added: 1.2.0 enable: description: - The state of the VRRP required: false default: True choices: [True, False] aliases: [] version_added: 1.2.0 primary_ip: description: - The ip address of the virtual router required: false default: '0.0.0.0' choices: [] aliases: [] version_added: 1.2.0 priority: description: - The priority setting for the virtual router required: false default: 100 choices: [] aliases: [] version_added: 1.2.0 description: description: - Text description of the virtual router required: false default: null choices: [] aliases: [] version_added: 1.2.0 ip_version: description: - VRRP version in place on the virtual router required: false default: 2 choices: [2, 3] aliases: [] version_added: 1.2.0 secondary_ip: description: - Array of secondary ip addresses assigned to the VRRP required: false default: [] choices: [] aliases: [] version_added: 1.2.0 timers_advertise: description: - Interval between advertisement messages to virtual router group required: false default: 1 choices: [] aliases: [] version_added: 1.2.0 preempt: description: - Preempt mode setting for the virtual router required: false default: True choices: [True, False] aliases: [] version_added: 1.2.0 preempt_delay_min: description: - Interval between a preempt event and takeover required: false default: 0 choices: [] aliases: [] version_added: 1.2.0 preempt_delay_reload: description: - Interval between a preempt event and takeover after reload required: false default: 0 choices: [] aliases: [] version_added: 1.2.0 delay_reload: description: - Delay between switch reload and VRRP initialization required: false default: 0 choices: [] aliases: [] version_added: 1.2.0 mac_addr_adv_interval: description: - Interval between advertisement messages to virtual router group required: false default: 30 choices: [] aliases: [] version_added: 1.2.0 track: description: - Array of track definitions to be assigned to the vrrp required: false default: [] choices: [] aliases: [] version_added: 1.2.0 """ EXAMPLES = """ # Configure the set of tracked objects for the VRRP # Create a list of dictionaries, where name is the object to be # tracked, action is shutdown or decrement, and amount is the # decrement amount. Amount is not specified when action is shutdown. vars: tracks: - name: Ethernet1 action: shutdown - name: Ethernet2 action: decrement amount: 5 # Setup the VRRP - eos_vrrp: interface=Vlan70 vrid=10 enable=True primary_ip=10.10.10.1 priority=50 description='vrrp 10 on Vlan70' ip_version=2 secondary_ip=['10.10.10.70','10.10.10.80'] timers_advertise=15 preempt=True preempt_delay_min=30 preempt_delay_reload=30 delay_reload=30 track="{{ tracks }}" """ import yaml #<<EOS_COMMON_MODULE_START>> import syslog import collections from ansible.module_utils.basic import * try: import pyeapi PYEAPI_AVAILABLE = True except ImportError: PYEAPI_AVAILABLE = False DEFAULT_SYSLOG_PRIORITY = syslog.LOG_NOTICE DEFAULT_CONNECTION = 'localhost' TRANSPORTS = ['socket', 'http', 'https', 'http_local'] class EosConnection(object): __attributes__ = ['username', 'password', 'host', 'transport', 'port'] def __init__(self, **kwargs): self.connection = kwargs['connection'] self.transport = kwargs.get('transport') self.username = kwargs.get('username') self.password = kwargs.get('password') self.host = kwargs.get('host') self.port = kwargs.get('port') self.config = kwargs.get('config') def connect(self): if self.config is not None: pyeapi.load_config(self.config) config = dict() if self.connection is not None: config = pyeapi.config_for(self.connection) if not config: msg = 'Connection name "{}" not found'.format(self.connection) for key in self.__attributes__: if getattr(self, key) is not None: config[key] = getattr(self, key) if 'transport' not in config: raise ValueError('Connection must define a transport') connection = pyeapi.client.make_connection(**config) node = pyeapi.client.Node(connection, **config) try: node.enable('show version') except (pyeapi.eapilib.ConnectionError, pyeapi.eapilib.CommandError): raise ValueError('unable to connect to {}'.format(node)) return node class EosAnsibleModule(AnsibleModule): meta_args = { 'config': dict(), 'username': dict(), 'password': dict(), 'host': dict(), 'connection': dict(default=DEFAULT_CONNECTION), 'transport': dict(choices=TRANSPORTS), 'port': dict(), 'debug': dict(type='bool', default='false'), 'logging': dict(type='bool', default='true') } stateful_args = { 'state': dict(default='present', choices=['present', 'absent']), } def __init__(self, stateful=True, autorefresh=False, *args, **kwargs): kwargs['argument_spec'].update(self.meta_args) self._stateful = stateful if stateful: kwargs['argument_spec'].update(self.stateful_args) ## Ok, so in Ansible 2.0, ## AnsibleModule.__init__() sets self.params and then ## calls self.log() ## (through self._log_invocation()) ## ## However, self.log() (overridden in EosAnsibleModule) ## references self._logging ## and self._logging (defined in EosAnsibleModule) ## references self.params. ## ## So ... I'm defining self._logging without "or self.params['logging']" ## *before* AnsibleModule.__init__() to avoid a "ref before def". ## ## I verified that this works with Ansible 1.9.4 and 2.0.0.2. ## The only caveat is that the first log message in ## AnsibleModule.__init__() won't be subject to the value of ## self.params['logging']. self._logging = kwargs.get('logging') super(EosAnsibleModule, self).__init__(*args, **kwargs) self.result = dict(changed=False, changes=dict()) self._debug = kwargs.get('debug') or self.boolean(self.params['debug']) self._logging = kwargs.get('logging') or self.params['logging'] self.log('DEBUG flag is %s' % self._debug) self.debug('pyeapi_version', self.check_pyeapi()) self.debug('stateful', self._stateful) self.debug('params', self.params) self._attributes = self.map_argument_spec() self.validate() self._autorefresh = autorefresh self._node = EosConnection(**self.params) self._node.connect() self._node = self.connect() self._instance = None self.desired_state = self.params['state'] if self._stateful else None self.exit_after_flush = kwargs.get('exit_after_flush') @property def instance(self): if self._instance: return self._instance func = self.func('instance') if not func: self.fail('Module does not support "instance"') try: self._instance = func(self) except Exception as exc: self.fail('instance[error]: %s' % exc.message) self.log("called instance: %s" % self._instance) return self._instance @property def attributes(self): return self._attributes @property def node(self): return self._node def check_pyeapi(self): if not PYEAPI_AVAILABLE: self.fail('Unable to import pyeapi, is it installed?') return pyeapi.__version__ def map_argument_spec(self): """map_argument_spec maps only the module argument spec to attrs This method will map the argumentspec minus the meta_args to attrs and return the attrs. This returns a dict object that includes only the original argspec plus the stateful_args (if self._stateful=True) Returns: dict: Returns a dict object that includes the original argument_spec plus stateful_args with values minus meta_args """ keys = set(self.params).difference(self.meta_args) attrs = dict() attrs = dict([(k, self.params[k]) for k in self.params if k in keys]) if 'CHECKMODE' in attrs: del attrs['CHECKMODE'] return attrs def validate(self): for key, value in self.attributes.iteritems(): func = self.func('validate_%s' % key) if func: self.attributes[key] = func(value) def create(self): if not self.check_mode: func = self.func('create') if not func: self.fail('Module must define "create" function') return self.invoke(func, self) def remove(self): if not self.check_mode: func = self.func('remove') if not func: self.fail('Module most define "remove" function') return self.invoke(func, self) def flush(self, exit_after_flush=False): self.exit_after_flush = exit_after_flush if self.desired_state == 'present' or not self._stateful: if self.instance.get('state') == 'absent': changed = self.create() self.result['changed'] = changed or True self.refresh() # After a create command, flush the running-config # so we get the latest for any other attributes self._node._running_config = None changeset = self.attributes.viewitems() - self.instance.viewitems() if self._debug: self.debug('desired_state', self.attributes) self.debug('current_state', self.instance) changes = self.update(changeset) if changes: self.result['changes'] = changes self.result['changed'] = True self._attributes.update(changes) flush = self.func('flush') if flush: self.invoke(flush, self) elif self.desired_state == 'absent' and self._stateful: if self.instance.get('state') == 'present': changed = self.remove() self.result['changed'] = changed or True elif self._stateful: if self.desired_state != self.instance.get('state'): func = self.func(self.desired_state) changed = self.invoke(func, self) self.result['changed'] = changed or True self.refresh() # By calling self.instance here we trigger another show running-config # all which causes delay. Only if debug is enabled do we call this # since it will display the latest state of the object. if self._debug: self.result['instance'] = self.instance if self.exit_after_flush: self.exit() def update(self, changeset): changes = dict() for key, value in changeset: if value is not None: changes[key] = value func = self.func('set_%s' % key) if func and not self.check_mode: try: self.invoke(func, self) except Exception as exc: self.fail(exc.message) return changes def connect(self): if self.params['config']: pyeapi.load_config(self.params['config']) config = dict() if self.params['connection']: config = pyeapi.config_for(self.params['connection']) if not config: msg = 'Connection name "%s" not found' % self.params['connection'] self.fail(msg) if self.params['username']: config['username'] = self.params['username'] if self.params['password']: config['password'] = self.params['password'] if self.params['transport']: config['transport'] = self.params['transport'] if self.params['port']: config['port'] = self.params['port'] if self.params['host']: config['host'] = self.params['host'] if 'transport' not in config: self.fail('Connection must define a transport') connection = pyeapi.client.make_connection(**config) self.log('Creating connection with autorefresh=%s' % self._autorefresh) node = pyeapi.client.Node(connection, autorefresh=self._autorefresh, **config) try: resp = node.enable('show version') self.debug('eos_version', resp[0]['result']['version']) self.debug('eos_model', resp[0]['result']['modelName']) except (pyeapi.eapilib.ConnectionError, pyeapi.eapilib.CommandError): self.fail('unable to connect to %s' % node) else: self.log('Connected to node %s' % node) self.debug('node', str(node)) return node def config(self, commands): self.result['changed'] = True if not self.check_mode: self.node.config(commands) def api(self, module): return self.node.api(module) def func(self, name): return globals().get(name) def invoke(self, func, *args, **kwargs): try: return func(*args, **kwargs) except Exception as exc: self.fail(exc.message) def invoke_function(self, name, *args, **kwargs): func = self.func(name) if func: return self.invoke(func, *args, **kwargs) def fail(self, msg): self.invoke_function('on_fail', self) self.log('ERROR: %s' % msg, syslog.LOG_ERR) self.fail_json(msg=msg) def exit(self): self.invoke_function('on_exit', self) self.log('Module completed successfully') self.exit_json(**self.result) def refresh(self): self._instance = None def debug(self, key, value): if self._debug: if 'debug' not in self.result: self.result['debug'] = dict() self.result['debug'][key] = value def log(self, message, log_args=None, priority=None): if self._logging: syslog.openlog('ansible-eos') priority = priority or DEFAULT_SYSLOG_PRIORITY syslog.syslog(priority, str(message)) @classmethod def add_state(cls, name): cls.stateful_args['state']['choices'].append(name) #<<EOS_COMMON_MODULE_END>> def instance(module): """ Returns an instance of Vrrp based on interface and vrid """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] _instance = dict(interface=interface, vrid=vrid, state='absent') try: result = module.node.api('vrrp').get(interface)[vrid] except: result = None if result: _instance['state'] = 'present' _instance['enable'] = result['enable'] _instance['primary_ip'] = result['primary_ip'] _instance['priority'] = str(result['priority']) _instance['description'] = result['description'] _instance['ip_version'] = str(result['ip_version']) _instance['secondary_ip'] = yaml.dump(sorted(result['secondary_ip'])) _instance['timers_advertise'] = str(result['timers_advertise']) _instance['preempt'] = result['preempt'] _instance['preempt_delay_min'] = str(result['preempt_delay_min']) _instance['preempt_delay_reload'] = str(result['preempt_delay_reload']) _instance['delay_reload'] = str(result['delay_reload']) _instance['mac_addr_adv_interval'] = \ str(result['mac_addr_adv_interval']) _instance['track'] = yaml.dump(sorted(result['track'])) return _instance def create(module): """Creates a vrrp on the interface """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] module.node.api('vrrp').create(interface, vrid) def remove(module): """Removes a vrrp configuration from the interface """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] module.node.api('vrrp').delete(interface, vrid) def set_enable(module): """Configures the enable attribute for the vrrp. """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['enable'] module.node.api('vrrp').set_enable(interface, vrid, value=value) def set_primary_ip(module): """Configures the primary ip attribute for the vrrp. """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['primary_ip'] module.node.api('vrrp').set_primary_ip(interface, vrid, value=value) def set_priority(module): """Configures the priority attribute for the vrrp """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['priority'] if not value.isdigit(): raise ValueError("vrrp argument 'priority' must be an integer") module.node.api('vrrp').set_priority(interface, vrid, value=int(value)) def set_description(module): """Configures the description attribute for the vrrp """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['description'] if value == '': # Empty string passed in - disable description on the vrrp module.node.api('vrrp').set_description(interface, vrid, disable=True) else: module.node.api('vrrp').set_description(interface, vrid, value=value) def set_ip_version(module): """Configures the ip version attribute for the vrrp """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['ip_version'] if not value.isdigit(): raise ValueError("vrrp argument 'ip_version' must be an integer") module.node.api('vrrp').set_ip_version(interface, vrid, value=int(value)) def validate_secondary_ip(value): """Converts the secondary ip array argument into a string that is matchable in ansible-eos. The array is sorted before conversion so matching is exact. """ if value is None: return None # If value string is not surrounded by brackets as # a list, add the brackets if not re.match(r'^\[.*\]$', value): value = "[%s]" % value # Convert the string to an object, sort, and convert # back to string for matching newval = sorted(yaml.load(value)) newstr = yaml.dump(newval) return newstr def set_secondary_ip(module): """Configures the secondary ip attribute for the vrrp """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['secondary_ip'] if value == '': value = [] else: value = yaml.load(value) module.node.api('vrrp').set_secondary_ips(interface, vrid, value) def set_timers_advertise(module): """Configures the timers advertise attribute for the vrrp """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['timers_advertise'] if not value.isdigit(): raise ValueError("vrrp argument 'timers_advertise' must be an integer") module.node.api('vrrp').set_timers_advertise(interface, vrid, value=int(value)) def set_preempt(module): """Configures the preempt attribute for the vrrp. """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['preempt'] module.node.api('vrrp').set_preempt(interface, vrid, value=value) def set_preempt_delay_min(module): """Configures the preempt delay minimum attribute for the vrrp """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['preempt_delay_min'] if not value.isdigit(): raise ValueError("vrrp argument 'preempt_delay_min' must " "be an integer") module.node.api('vrrp').set_preempt_delay_min(interface, vrid, value=int(value)) def set_preempt_delay_reload(module): """Configures the preempt delay reload attribute for the vrrp """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['preempt_delay_reload'] if not value.isdigit(): raise ValueError("vrrp argument 'preempt_delay_reload' must " "be an integer") module.node.api('vrrp').set_preempt_delay_reload(interface, vrid, value=int(value)) def set_delay_reload(module): """Configures the delay reload attribute for the vrrp """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['delay_reload'] if not value.isdigit(): raise ValueError("vrrp argument 'delay_reload' must " "be an integer") module.node.api('vrrp').set_delay_reload(interface, vrid, value=int(value)) def set_mac_addr_adv_interval(module): """Configures the mac-address advertisement-interval attribute for the vrrp """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['mac_addr_adv_interval'] if not value.isdigit(): raise ValueError("vrrp argument 'mac_addr_adv_interval' must " "be an integer") module.node.api('vrrp').set_mac_addr_adv_interval(interface, vrid, value=int(value)) def validate_track(value): """Converts the tracked object array argument into a string that is matchable in ansible-eos. The array is sorted before conversion so matching is exact. """ if value is None: return None # If value string is not surrounded by brackets as # a list, add the brackets if not re.match(r'^\[.*\]$', value): value = "[%s]" % value # Convert the string to an object, sort, and convert # back to string for matching newval = sorted(yaml.load(value)) newstr = yaml.dump(newval) return newstr def set_track(module): """Configures the track attributes for the vrrp Takes the tracks definition string used by eos_vrrp and converts it to a dictionary for the set_tracks method of pyeapi. """ interface = module.attributes['interface'] vrid = module.attributes['vrid'] value = module.attributes['track'] if value == '': value = [] else: value = yaml.load(value) module.node.api('vrrp').set_tracks(interface, vrid, value) def main(): """ The main module routine called when the module is run by Ansible """ argument_spec = dict( interface=dict(required=True), vrid=dict(required=True, type='int'), enable=dict(type='bool', default=True), primary_ip=dict(default='0.0.0.0'), priority=dict(default='100'), description=dict(), secondary_ip=dict(default=''), ip_version=dict(default='2'), timers_advertise=dict(default='1'), mac_addr_adv_interval=dict(default='30'), preempt=dict(type='bool', default=True), preempt_delay_min=dict(default='0'), preempt_delay_reload=dict(default='0'), delay_reload=dict(default='0'), authentication_type=dict(), track=dict(default=''), ) argument_spec['continue'] = dict() module = EosAnsibleModule(argument_spec=argument_spec, supports_check_mode=True) module.flush(True) main()
gpl-3.0
guettli/django
django/template/defaulttags.py
14
50344
"""Default tags used by the template system, available to all templates.""" from __future__ import unicode_literals import re import sys import warnings from collections import namedtuple from datetime import datetime from itertools import cycle as itertools_cycle, groupby from django.conf import settings from django.utils import six, timezone from django.utils.encoding import force_text from django.utils.html import conditional_escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils.safestring import mark_safe from .base import ( BLOCK_TAG_END, BLOCK_TAG_START, COMMENT_TAG_END, COMMENT_TAG_START, SINGLE_BRACE_END, SINGLE_BRACE_START, VARIABLE_ATTRIBUTE_SEPARATOR, VARIABLE_TAG_END, VARIABLE_TAG_START, Context, Node, NodeList, TemplateSyntaxError, VariableDoesNotExist, kwarg_re, render_value_in_context, token_kwargs, ) from .defaultfilters import date from .library import Library from .smartif import IfParser, Literal register = Library() class AutoEscapeControlNode(Node): """Implements the actions of the autoescape tag.""" def __init__(self, setting, nodelist): self.setting, self.nodelist = setting, nodelist def render(self, context): old_setting = context.autoescape context.autoescape = self.setting output = self.nodelist.render(context) context.autoescape = old_setting if self.setting: return mark_safe(output) else: return output class CommentNode(Node): def render(self, context): return '' class CsrfTokenNode(Node): def render(self, context): csrf_token = context.get('csrf_token') if csrf_token: if csrf_token == 'NOTPROVIDED': return format_html("") else: return format_html("<input type='hidden' name='csrfmiddlewaretoken' value='{}' />", csrf_token) else: # It's very probable that the token is missing because of # misconfiguration, so we raise a warning if settings.DEBUG: warnings.warn( "A {% csrf_token %} was used in a template, but the context " "did not provide the value. This is usually caused by not " "using RequestContext." ) return '' class CycleNode(Node): def __init__(self, cyclevars, variable_name=None, silent=False): self.cyclevars = cyclevars self.variable_name = variable_name self.silent = silent def render(self, context): if self not in context.render_context: # First time the node is rendered in template context.render_context[self] = itertools_cycle(self.cyclevars) cycle_iter = context.render_context[self] value = next(cycle_iter).resolve(context) if self.variable_name: context.set_upward(self.variable_name, value) if self.silent: return '' return render_value_in_context(value, context) def reset(self, context): """ Reset the cycle iteration back to the beginning. """ context.render_context[self] = itertools_cycle(self.cyclevars) class DebugNode(Node): def render(self, context): from pprint import pformat output = [force_text(pformat(val)) for val in context] output.append('\n\n') output.append(force_text(pformat(sys.modules))) return ''.join(output) class FilterNode(Node): def __init__(self, filter_expr, nodelist): self.filter_expr, self.nodelist = filter_expr, nodelist def render(self, context): output = self.nodelist.render(context) # Apply filters. with context.push(var=output): return self.filter_expr.resolve(context) class FirstOfNode(Node): def __init__(self, variables, asvar=None): self.vars = variables self.asvar = asvar def render(self, context): for var in self.vars: value = var.resolve(context, True) if value: first = render_value_in_context(value, context) if self.asvar: context[self.asvar] = first return '' return first return '' class ForNode(Node): child_nodelists = ('nodelist_loop', 'nodelist_empty') def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None): self.loopvars, self.sequence = loopvars, sequence self.is_reversed = is_reversed self.nodelist_loop = nodelist_loop if nodelist_empty is None: self.nodelist_empty = NodeList() else: self.nodelist_empty = nodelist_empty def __repr__(self): reversed_text = ' reversed' if self.is_reversed else '' return "<For Node: for %s in %s, tail_len: %d%s>" % \ (', '.join(self.loopvars), self.sequence, len(self.nodelist_loop), reversed_text) def __iter__(self): for node in self.nodelist_loop: yield node for node in self.nodelist_empty: yield node def render(self, context): if 'forloop' in context: parentloop = context['forloop'] else: parentloop = {} with context.push(): try: values = self.sequence.resolve(context, True) except VariableDoesNotExist: values = [] if values is None: values = [] if not hasattr(values, '__len__'): values = list(values) len_values = len(values) if len_values < 1: return self.nodelist_empty.render(context) nodelist = [] if self.is_reversed: values = reversed(values) num_loopvars = len(self.loopvars) unpack = num_loopvars > 1 # Create a forloop value in the context. We'll update counters on each # iteration just below. loop_dict = context['forloop'] = {'parentloop': parentloop} for i, item in enumerate(values): # Shortcuts for current loop iteration number. loop_dict['counter0'] = i loop_dict['counter'] = i + 1 # Reverse counter iteration numbers. loop_dict['revcounter'] = len_values - i loop_dict['revcounter0'] = len_values - i - 1 # Boolean values designating first and last times through loop. loop_dict['first'] = (i == 0) loop_dict['last'] = (i == len_values - 1) pop_context = False if unpack: # If there are multiple loop variables, unpack the item into # them. try: len_item = len(item) except TypeError: # not an iterable len_item = 1 # Check loop variable count before unpacking if num_loopvars != len_item: raise ValueError( "Need {} values to unpack in for loop; got {}. " .format(num_loopvars, len_item), ) unpacked_vars = dict(zip(self.loopvars, item)) pop_context = True context.update(unpacked_vars) else: context[self.loopvars[0]] = item for node in self.nodelist_loop: nodelist.append(node.render_annotated(context)) if pop_context: # The loop variables were pushed on to the context so pop them # off again. This is necessary because the tag lets the length # of loopvars differ to the length of each set of items and we # don't want to leave any vars from the previous loop on the # context. context.pop() return mark_safe(''.join(force_text(n) for n in nodelist)) class IfChangedNode(Node): child_nodelists = ('nodelist_true', 'nodelist_false') def __init__(self, nodelist_true, nodelist_false, *varlist): self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self._varlist = varlist def render(self, context): # Init state storage state_frame = self._get_context_stack_frame(context) if self not in state_frame: state_frame[self] = None nodelist_true_output = None try: if self._varlist: # Consider multiple parameters. This automatically behaves # like an OR evaluation of the multiple variables. compare_to = [var.resolve(context, True) for var in self._varlist] else: # The "{% ifchanged %}" syntax (without any variables) compares the rendered output. compare_to = nodelist_true_output = self.nodelist_true.render(context) except VariableDoesNotExist: compare_to = None if compare_to != state_frame[self]: state_frame[self] = compare_to # render true block if not already rendered return nodelist_true_output or self.nodelist_true.render(context) elif self.nodelist_false: return self.nodelist_false.render(context) return '' def _get_context_stack_frame(self, context): # The Context object behaves like a stack where each template tag can create a new scope. # Find the place where to store the state to detect changes. if 'forloop' in context: # Ifchanged is bound to the local for loop. # When there is a loop-in-loop, the state is bound to the inner loop, # so it resets when the outer loop continues. return context['forloop'] else: # Using ifchanged outside loops. Effectively this is a no-op because the state is associated with 'self'. return context.render_context class IfEqualNode(Node): child_nodelists = ('nodelist_true', 'nodelist_false') def __init__(self, var1, var2, nodelist_true, nodelist_false, negate): self.var1, self.var2 = var1, var2 self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self.negate = negate def __repr__(self): return "<IfEqualNode>" def render(self, context): val1 = self.var1.resolve(context, True) val2 = self.var2.resolve(context, True) if (self.negate and val1 != val2) or (not self.negate and val1 == val2): return self.nodelist_true.render(context) return self.nodelist_false.render(context) class IfNode(Node): def __init__(self, conditions_nodelists): self.conditions_nodelists = conditions_nodelists def __repr__(self): return "<IfNode>" def __iter__(self): for _, nodelist in self.conditions_nodelists: for node in nodelist: yield node @property def nodelist(self): return NodeList(node for _, nodelist in self.conditions_nodelists for node in nodelist) def render(self, context): for condition, nodelist in self.conditions_nodelists: if condition is not None: # if / elif clause try: match = condition.eval(context) except VariableDoesNotExist: match = None else: # else clause match = True if match: return nodelist.render(context) return '' class LoremNode(Node): def __init__(self, count, method, common): self.count, self.method, self.common = count, method, common def render(self, context): try: count = int(self.count.resolve(context)) except (ValueError, TypeError): count = 1 if self.method == 'w': return words(count, common=self.common) else: paras = paragraphs(count, common=self.common) if self.method == 'p': paras = ['<p>%s</p>' % p for p in paras] return '\n\n'.join(paras) GroupedResult = namedtuple('GroupedResult', ['grouper', 'list']) class RegroupNode(Node): def __init__(self, target, expression, var_name): self.target, self.expression = target, expression self.var_name = var_name def resolve_expression(self, obj, context): # This method is called for each object in self.target. See regroup() # for the reason why we temporarily put the object in the context. context[self.var_name] = obj return self.expression.resolve(context, True) def render(self, context): obj_list = self.target.resolve(context, True) if obj_list is None: # target variable wasn't found in context; fail silently. context[self.var_name] = [] return '' # List of dictionaries in the format: # {'grouper': 'key', 'list': [list of contents]}. context[self.var_name] = [ GroupedResult(grouper=key, list=list(val)) for key, val in groupby(obj_list, lambda obj: self.resolve_expression(obj, context)) ] return '' class LoadNode(Node): def render(self, context): return '' class NowNode(Node): def __init__(self, format_string, asvar=None): self.format_string = format_string self.asvar = asvar def render(self, context): tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None formatted = date(datetime.now(tz=tzinfo), self.format_string) if self.asvar: context[self.asvar] = formatted return '' else: return formatted class ResetCycleNode(Node): def __init__(self, node): self.node = node def render(self, context): self.node.reset(context) return '' class SpacelessNode(Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): from django.utils.html import strip_spaces_between_tags return strip_spaces_between_tags(self.nodelist.render(context).strip()) class TemplateTagNode(Node): mapping = {'openblock': BLOCK_TAG_START, 'closeblock': BLOCK_TAG_END, 'openvariable': VARIABLE_TAG_START, 'closevariable': VARIABLE_TAG_END, 'openbrace': SINGLE_BRACE_START, 'closebrace': SINGLE_BRACE_END, 'opencomment': COMMENT_TAG_START, 'closecomment': COMMENT_TAG_END, } def __init__(self, tagtype): self.tagtype = tagtype def render(self, context): return self.mapping.get(self.tagtype, '') class URLNode(Node): def __init__(self, view_name, args, kwargs, asvar): self.view_name = view_name self.args = args self.kwargs = kwargs self.asvar = asvar def render(self, context): from django.urls import reverse, NoReverseMatch args = [arg.resolve(context) for arg in self.args] kwargs = { force_text(k, 'ascii'): v.resolve(context) for k, v in self.kwargs.items() } view_name = self.view_name.resolve(context) try: current_app = context.request.current_app except AttributeError: try: current_app = context.request.resolver_match.namespace except AttributeError: current_app = None # Try to look up the URL. If it fails, raise NoReverseMatch unless the # {% url ... as var %} construct is used, in which case return nothing. url = '' try: url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) except NoReverseMatch: if self.asvar is None: raise if self.asvar: context[self.asvar] = url return '' else: if context.autoescape: url = conditional_escape(url) return url class VerbatimNode(Node): def __init__(self, content): self.content = content def render(self, context): return self.content class WidthRatioNode(Node): def __init__(self, val_expr, max_expr, max_width, asvar=None): self.val_expr = val_expr self.max_expr = max_expr self.max_width = max_width self.asvar = asvar def render(self, context): try: value = self.val_expr.resolve(context) max_value = self.max_expr.resolve(context) max_width = int(self.max_width.resolve(context)) except VariableDoesNotExist: return '' except (ValueError, TypeError): raise TemplateSyntaxError("widthratio final argument must be a number") try: value = float(value) max_value = float(max_value) ratio = (value / max_value) * max_width result = str(int(round(ratio))) except ZeroDivisionError: return '0' except (ValueError, TypeError, OverflowError): return '' if self.asvar: context[self.asvar] = result return '' else: return result class WithNode(Node): def __init__(self, var, name, nodelist, extra_context=None): self.nodelist = nodelist # var and name are legacy attributes, being left in case they are used # by third-party subclasses of this Node. self.extra_context = extra_context or {} if name: self.extra_context[name] = var def __repr__(self): return "<WithNode>" def render(self, context): values = {key: val.resolve(context) for key, val in six.iteritems(self.extra_context)} with context.push(**values): return self.nodelist.render(context) @register.tag def autoescape(parser, token): """ Force autoescape behavior for this block. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 2: raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.") arg = args[1] if arg not in ('on', 'off'): raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'") nodelist = parser.parse(('endautoescape',)) parser.delete_first_token() return AutoEscapeControlNode((arg == 'on'), nodelist) @register.tag def comment(parser, token): """ Ignores everything between ``{% comment %}`` and ``{% endcomment %}``. """ parser.skip_past('endcomment') return CommentNode() @register.tag def cycle(parser, token): """ Cycles among the given strings each time this tag is encountered. Within a loop, cycles among the given strings each time through the loop:: {% for o in some_list %} <tr class="{% cycle 'row1' 'row2' %}"> ... </tr> {% endfor %} Outside of a loop, give the values a unique name the first time you call it, then use that name each successive time through:: <tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> You can use any number of values, separated by spaces. Commas can also be used to separate values; if a comma is used, the cycle values are interpreted as literal strings. The optional flag "silent" can be used to prevent the cycle declaration from returning any value:: {% for o in some_list %} {% cycle 'row1' 'row2' as rowcolors silent %} <tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr> {% endfor %} """ # Note: This returns the exact same node on each {% cycle name %} call; # that is, the node object returned from {% cycle a b c as name %} and the # one returned from {% cycle name %} are the exact same object. This # shouldn't cause problems (heh), but if it does, now you know. # # Ugly hack warning: This stuffs the named template dict into parser so # that names are only unique within each template (as opposed to using # a global variable, which would make cycle names have to be unique across # *all* templates. # # It keeps the last node in the parser to be able to reset it with # {% resetcycle %}. args = token.split_contents() if len(args) < 2: raise TemplateSyntaxError("'cycle' tag requires at least two arguments") if len(args) == 2: # {% cycle foo %} case. name = args[1] if not hasattr(parser, '_named_cycle_nodes'): raise TemplateSyntaxError("No named cycles in template. '%s' is not defined" % name) if name not in parser._named_cycle_nodes: raise TemplateSyntaxError("Named cycle '%s' does not exist" % name) return parser._named_cycle_nodes[name] as_form = False if len(args) > 4: # {% cycle ... as foo [silent] %} case. if args[-3] == "as": if args[-1] != "silent": raise TemplateSyntaxError("Only 'silent' flag is allowed after cycle's name, not '%s'." % args[-1]) as_form = True silent = True args = args[:-1] elif args[-2] == "as": as_form = True silent = False if as_form: name = args[-1] values = [parser.compile_filter(arg) for arg in args[1:-2]] node = CycleNode(values, name, silent=silent) if not hasattr(parser, '_named_cycle_nodes'): parser._named_cycle_nodes = {} parser._named_cycle_nodes[name] = node else: values = [parser.compile_filter(arg) for arg in args[1:]] node = CycleNode(values) parser._last_cycle_node = node return node @register.tag def csrf_token(parser, token): return CsrfTokenNode() @register.tag def debug(parser, token): """ Outputs a whole load of debugging information, including the current context and imported modules. Sample usage:: <pre> {% debug %} </pre> """ return DebugNode() @register.tag('filter') def do_filter(parser, token): """ Filters the contents of the block through variable filters. Filters can also be piped through each other, and they can have arguments -- just like in variable syntax. Sample usage:: {% filter force_escape|lower %} This text will be HTML-escaped, and will appear in lowercase. {% endfilter %} Note that the ``escape`` and ``safe`` filters are not acceptable arguments. Instead, use the ``autoescape`` tag to manage autoescaping for blocks of template code. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments _, rest = token.contents.split(None, 1) filter_expr = parser.compile_filter("var|%s" % (rest)) for func, unused in filter_expr.filters: filter_name = getattr(func, '_filter_name', None) if filter_name in ('escape', 'safe'): raise TemplateSyntaxError('"filter %s" is not permitted. Use the "autoescape" tag instead.' % filter_name) nodelist = parser.parse(('endfilter',)) parser.delete_first_token() return FilterNode(filter_expr, nodelist) @register.tag def firstof(parser, token): """ Outputs the first variable passed that is not False. Outputs nothing if all the passed variables are False. Sample usage:: {% firstof var1 var2 var3 as myvar %} This is equivalent to:: {% if var1 %} {{ var1 }} {% elif var2 %} {{ var2 }} {% elif var3 %} {{ var3 }} {% endif %} but obviously much cleaner! You can also use a literal string as a fallback value in case all passed variables are False:: {% firstof var1 var2 var3 "fallback value" %} If you want to disable auto-escaping of variables you can use:: {% autoescape off %} {% firstof var1 var2 var3 "<strong>fallback value</strong>" %} {% autoescape %} Or if only some variables should be escaped, you can use:: {% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %} """ bits = token.split_contents()[1:] asvar = None if len(bits) < 1: raise TemplateSyntaxError("'firstof' statement requires at least one argument") if len(bits) >= 2 and bits[-2] == 'as': asvar = bits[-1] bits = bits[:-2] return FirstOfNode([parser.compile_filter(bit) for bit in bits], asvar) @register.tag('for') def do_for(parser, token): """ Loops over each item in an array. For example, to display a list of athletes given ``athlete_list``:: <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul> You can loop over a list in reverse by using ``{% for obj in list reversed %}``. You can also unpack multiple values from a two-dimensional array:: {% for key,value in dict.items %} {{ key }}: {{ value }} {% endfor %} The ``for`` tag can take an optional ``{% empty %}`` clause that will be displayed if the given array is empty or could not be found:: <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% empty %} <li>Sorry, no athletes in this list.</li> {% endfor %} <ul> The above is equivalent to -- but shorter, cleaner, and possibly faster than -- the following:: <ul> {% if athlete_list %} {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} {% else %} <li>Sorry, no athletes in this list.</li> {% endif %} </ul> The for loop sets a number of variables available within the loop: ========================== ================================================ Variable Description ========================== ================================================ ``forloop.counter`` The current iteration of the loop (1-indexed) ``forloop.counter0`` The current iteration of the loop (0-indexed) ``forloop.revcounter`` The number of iterations from the end of the loop (1-indexed) ``forloop.revcounter0`` The number of iterations from the end of the loop (0-indexed) ``forloop.first`` True if this is the first time through the loop ``forloop.last`` True if this is the last time through the loop ``forloop.parentloop`` For nested loops, this is the loop "above" the current one ========================== ================================================ """ bits = token.split_contents() if len(bits) < 4: raise TemplateSyntaxError("'for' statements should have at least four" " words: %s" % token.contents) is_reversed = bits[-1] == 'reversed' in_index = -3 if is_reversed else -2 if bits[in_index] != 'in': raise TemplateSyntaxError("'for' statements should use the format" " 'for x in y': %s" % token.contents) loopvars = re.split(r' *, *', ' '.join(bits[1:in_index])) for var in loopvars: if not var or ' ' in var: raise TemplateSyntaxError("'for' tag received an invalid argument:" " %s" % token.contents) sequence = parser.compile_filter(bits[in_index + 1]) nodelist_loop = parser.parse(('empty', 'endfor',)) token = parser.next_token() if token.contents == 'empty': nodelist_empty = parser.parse(('endfor',)) parser.delete_first_token() else: nodelist_empty = None return ForNode(loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty) def do_ifequal(parser, token, negate): bits = list(token.split_contents()) if len(bits) != 3: raise TemplateSyntaxError("%r takes two arguments" % bits[0]) end_tag = 'end' + bits[0] nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag,)) parser.delete_first_token() else: nodelist_false = NodeList() val1 = parser.compile_filter(bits[1]) val2 = parser.compile_filter(bits[2]) return IfEqualNode(val1, val2, nodelist_true, nodelist_false, negate) @register.tag def ifequal(parser, token): """ Outputs the contents of the block if the two arguments equal each other. Examples:: {% ifequal user.id comment.user_id %} ... {% endifequal %} {% ifnotequal user.id comment.user_id %} ... {% else %} ... {% endifnotequal %} """ return do_ifequal(parser, token, False) @register.tag def ifnotequal(parser, token): """ Outputs the contents of the block if the two arguments are not equal. See ifequal. """ return do_ifequal(parser, token, True) class TemplateLiteral(Literal): def __init__(self, value, text): self.value = value self.text = text # for better error messages def display(self): return self.text def eval(self, context): return self.value.resolve(context, ignore_failures=True) class TemplateIfParser(IfParser): error_class = TemplateSyntaxError def __init__(self, parser, *args, **kwargs): self.template_parser = parser super(TemplateIfParser, self).__init__(*args, **kwargs) def create_var(self, value): return TemplateLiteral(self.template_parser.compile_filter(value), value) @register.tag('if') def do_if(parser, token): """ The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e., exists, is not empty, and is not a false boolean value), the contents of the block are output: :: {% if athlete_list %} Number of athletes: {{ athlete_list|count }} {% elif athlete_in_locker_room_list %} Athletes should be out of the locker room soon! {% else %} No athletes. {% endif %} In the above, if ``athlete_list`` is not empty, the number of athletes will be displayed by the ``{{ athlete_list|count }}`` variable. As you can see, the ``if`` tag may take one or several `` {% elif %}`` clauses, as well as an ``{% else %}`` clause that will be displayed if all previous conditions fail. These clauses are optional. ``if`` tags may use ``or``, ``and`` or ``not`` to test a number of variables or to negate a given variable:: {% if not athlete_list %} There are no athletes. {% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches. {% endif %} {% if athlete_list and coach_list %} Both athletes and coaches are available. {% endif %} {% if not athlete_list or coach_list %} There are no athletes, or there are some coaches. {% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches. {% endif %} Comparison operators are also available, and the use of filters is also allowed, for example:: {% if articles|length >= 5 %}...{% endif %} Arguments and operators _must_ have a space between them, so ``{% if 1>2 %}`` is not a valid if tag. All supported operators are: ``or``, ``and``, ``in``, ``not in`` ``==``, ``!=``, ``>``, ``>=``, ``<`` and ``<=``. Operator precedence follows Python. """ # {% if ... %} bits = token.split_contents()[1:] condition = TemplateIfParser(parser, bits).parse() nodelist = parser.parse(('elif', 'else', 'endif')) conditions_nodelists = [(condition, nodelist)] token = parser.next_token() # {% elif ... %} (repeatable) while token.contents.startswith('elif'): bits = token.split_contents()[1:] condition = TemplateIfParser(parser, bits).parse() nodelist = parser.parse(('elif', 'else', 'endif')) conditions_nodelists.append((condition, nodelist)) token = parser.next_token() # {% else %} (optional) if token.contents == 'else': nodelist = parser.parse(('endif',)) conditions_nodelists.append((None, nodelist)) token = parser.next_token() # {% endif %} if token.contents != 'endif': raise TemplateSyntaxError('Malformed template tag at line {0}: "{1}"'.format(token.lineno, token.contents)) return IfNode(conditions_nodelists) @register.tag def ifchanged(parser, token): """ Checks if a value has changed from the last iteration of a loop. The ``{% ifchanged %}`` block tag is used within a loop. It has two possible uses. 1. Checks its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:: <h1>Archive for {{ year }}</h1> {% for date in days %} {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> {% endfor %} 2. If given one or more variables, check whether any variable has changed. For example, the following shows the date every time it changes, while showing the hour if either the hour or the date has changed:: {% for date in days %} {% ifchanged date.date %} {{ date.date }} {% endifchanged %} {% ifchanged date.hour date.date %} {{ date.hour }} {% endifchanged %} {% endfor %} """ bits = token.split_contents() nodelist_true = parser.parse(('else', 'endifchanged')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endifchanged',)) parser.delete_first_token() else: nodelist_false = NodeList() values = [parser.compile_filter(bit) for bit in bits[1:]] return IfChangedNode(nodelist_true, nodelist_false, *values) def find_library(parser, name): try: return parser.libraries[name] except KeyError: raise TemplateSyntaxError( "'%s' is not a registered tag library. Must be one of:\n%s" % ( name, "\n".join(sorted(parser.libraries.keys())), ), ) def load_from_library(library, label, names): """ Return a subset of tags and filters from a library. """ subset = Library() for name in names: found = False if name in library.tags: found = True subset.tags[name] = library.tags[name] if name in library.filters: found = True subset.filters[name] = library.filters[name] if found is False: raise TemplateSyntaxError( "'%s' is not a valid tag or filter in tag library '%s'" % ( name, label, ), ) return subset @register.tag def load(parser, token): """ Loads a custom template tag library into the parser. For example, to load the template tags in ``django/templatetags/news/photos.py``:: {% load news.photos %} Can also be used to load an individual tag/filter from a library:: {% load byline from news %} """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments bits = token.contents.split() if len(bits) >= 4 and bits[-2] == "from": # from syntax is used; load individual tags from the library name = bits[-1] lib = find_library(parser, name) subset = load_from_library(lib, name, bits[1:-2]) parser.add_library(subset) else: # one or more libraries are specified; load and add them to the parser for name in bits[1:]: lib = find_library(parser, name) parser.add_library(lib) return LoadNode() @register.tag def lorem(parser, token): """ Creates random Latin text useful for providing test data in templates. Usage format:: {% lorem [count] [method] [random] %} ``count`` is a number (or variable) containing the number of paragraphs or words to generate (default is 1). ``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for plain-text paragraph blocks (default is ``b``). ``random`` is the word ``random``, which if given, does not use the common paragraph (starting "Lorem ipsum dolor sit amet, consectetuer..."). Examples: * ``{% lorem %}`` will output the common "lorem ipsum" paragraph * ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph and two random paragraphs each wrapped in HTML ``<p>`` tags * ``{% lorem 2 w random %}`` will output two random latin words """ bits = list(token.split_contents()) tagname = bits[0] # Random bit common = bits[-1] != 'random' if not common: bits.pop() # Method bit if bits[-1] in ('w', 'p', 'b'): method = bits.pop() else: method = 'b' # Count bit if len(bits) > 1: count = bits.pop() else: count = '1' count = parser.compile_filter(count) if len(bits) != 1: raise TemplateSyntaxError("Incorrect format for %r tag" % tagname) return LoremNode(count, method, common) @register.tag def now(parser, token): """ Displays the date, formatted according to the given string. Uses the same format as PHP's ``date()`` function; see http://php.net/date for all the possible values. Sample usage:: It is {% now "jS F Y H:i" %} """ bits = token.split_contents() asvar = None if len(bits) == 4 and bits[-2] == 'as': asvar = bits[-1] bits = bits[:-2] if len(bits) != 2: raise TemplateSyntaxError("'now' statement takes one argument") format_string = bits[1][1:-1] return NowNode(format_string, asvar) @register.tag def regroup(parser, token): """ Regroups a list of alike objects by a common attribute. This complex tag is best illustrated by use of an example: say that ``musicians`` is a list of ``Musician`` objects that have ``name`` and ``instrument`` attributes, and you'd like to display a list that looks like: * Guitar: * Django Reinhardt * Emily Remler * Piano: * Lovie Austin * Bud Powell * Trumpet: * Duke Ellington The following snippet of template code would accomplish this dubious task:: {% regroup musicians by instrument as grouped %} <ul> {% for group in grouped %} <li>{{ group.grouper }} <ul> {% for musician in group.list %} <li>{{ musician.name }}</li> {% endfor %} </ul> {% endfor %} </ul> As you can see, ``{% regroup %}`` populates a variable with a list of objects with ``grouper`` and ``list`` attributes. ``grouper`` contains the item that was grouped by; ``list`` contains the list of objects that share that ``grouper``. In this case, ``grouper`` would be ``Guitar``, ``Piano`` and ``Trumpet``, and ``list`` is the list of musicians who play this instrument. Note that ``{% regroup %}`` does not work when the list to be grouped is not sorted by the key you are grouping by! This means that if your list of musicians was not sorted by instrument, you'd need to make sure it is sorted before using it, i.e.:: {% regroup musicians|dictsort:"instrument" by instrument as grouped %} """ bits = token.split_contents() if len(bits) != 6: raise TemplateSyntaxError("'regroup' tag takes five arguments") target = parser.compile_filter(bits[1]) if bits[2] != 'by': raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'") if bits[4] != 'as': raise TemplateSyntaxError("next-to-last argument to 'regroup' tag must" " be 'as'") var_name = bits[5] # RegroupNode will take each item in 'target', put it in the context under # 'var_name', evaluate 'var_name'.'expression' in the current context, and # group by the resulting value. After all items are processed, it will # save the final result in the context under 'var_name', thus clearing the # temporary values. This hack is necessary because the template engine # doesn't provide a context-aware equivalent of Python's getattr. expression = parser.compile_filter(var_name + VARIABLE_ATTRIBUTE_SEPARATOR + bits[3]) return RegroupNode(target, expression, var_name) @register.tag def resetcycle(parser, token): """ Resets a cycle tag. If an argument is given, resets the last rendered cycle tag whose name matches the argument, else resets the last rendered cycle tag (named or unnamed). """ args = token.split_contents() if len(args) > 2: raise TemplateSyntaxError("%r tag accepts at most one argument." % args[0]) if len(args) == 2: name = args[1] try: return ResetCycleNode(parser._named_cycle_nodes[name]) except (AttributeError, KeyError): raise TemplateSyntaxError("Named cycle '%s' does not exist." % name) try: return ResetCycleNode(parser._last_cycle_node) except AttributeError: raise TemplateSyntaxError("No cycles in template.") @register.tag def spaceless(parser, token): """ Removes whitespace between HTML tags, including tab and newline characters. Example usage:: {% spaceless %} <p> <a href="foo/">Foo</a> </p> {% endspaceless %} This example would return this HTML:: <p><a href="foo/">Foo</a></p> Only space between *tags* is normalized -- not space between tags and text. In this example, the space around ``Hello`` won't be stripped:: {% spaceless %} <strong> Hello </strong> {% endspaceless %} """ nodelist = parser.parse(('endspaceless',)) parser.delete_first_token() return SpacelessNode(nodelist) @register.tag def templatetag(parser, token): """ Outputs one of the bits used to compose template tags. Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the ``{% templatetag %}`` tag. The argument tells which template bit to output: ================== ======= Argument Outputs ================== ======= ``openblock`` ``{%`` ``closeblock`` ``%}`` ``openvariable`` ``{{`` ``closevariable`` ``}}`` ``openbrace`` ``{`` ``closebrace`` ``}`` ``opencomment`` ``{#`` ``closecomment`` ``#}`` ================== ======= """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'templatetag' statement takes one argument") tag = bits[1] if tag not in TemplateTagNode.mapping: raise TemplateSyntaxError("Invalid templatetag argument: '%s'." " Must be one of: %s" % (tag, list(TemplateTagNode.mapping))) return TemplateTagNode(tag) @register.tag def url(parser, token): r""" Return an absolute URL matching the given view with its parameters. This is a way to define links that aren't tied to a particular URL configuration:: {% url "url_name" arg1 arg2 %} or {% url "url_name" name1=value1 name2=value2 %} The first argument is a django.conf.urls.url() name. Other arguments are space-separated values that will be filled in place of positional and keyword arguments in the URL. Don't mix positional and keyword arguments. All arguments for the URL must be present. For example, if you have a view ``app_name.views.client_details`` taking the client's id and the corresponding line in a URLconf looks like this:: url('^client/(\d+)/$', views.client_details, name='client-detail-view') and this app's URLconf is included into the project's URLconf under some path:: url('^clients/', include('app_name.urls')) then in a template you can create a link for a certain client like this:: {% url "client-detail-view" client.id %} The URL will look like ``/clients/client/123/``. The first argument may also be the name of a template variable that will be evaluated to obtain the view name or the URL name, e.g.:: {% with url_name="client-detail-view" %} {% url url_name client.id %} {% endwith %} """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument, the name of a url()." % bits[0]) viewname = parser.compile_filter(bits[1]) args = [] kwargs = {} asvar = None bits = bits[2:] if len(bits) >= 2 and bits[-2] == 'as': asvar = bits[-1] bits = bits[:-2] if len(bits): for bit in bits: match = kwarg_re.match(bit) if not match: raise TemplateSyntaxError("Malformed arguments to url tag") name, value = match.groups() if name: kwargs[name] = parser.compile_filter(value) else: args.append(parser.compile_filter(value)) return URLNode(viewname, args, kwargs, asvar) @register.tag def verbatim(parser, token): """ Stops the template engine from rendering the contents of this block tag. Usage:: {% verbatim %} {% don't process this %} {% endverbatim %} You can also designate a specific closing tag block (allowing the unrendered use of ``{% endverbatim %}``):: {% verbatim myblock %} ... {% endverbatim myblock %} """ nodelist = parser.parse(('endverbatim',)) parser.delete_first_token() return VerbatimNode(nodelist.render(Context())) @register.tag def widthratio(parser, token): """ For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant. For example:: <img src="bar.png" alt="Bar" height="10" width="{% widthratio this_value max_value max_width %}" /> If ``this_value`` is 175, ``max_value`` is 200, and ``max_width`` is 100, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88). In some cases you might want to capture the result of widthratio in a variable. It can be useful for instance in a blocktrans like this:: {% widthratio this_value max_value max_width as width %} {% blocktrans %}The width is: {{ width }}{% endblocktrans %} """ bits = token.split_contents() if len(bits) == 4: tag, this_value_expr, max_value_expr, max_width = bits asvar = None elif len(bits) == 6: tag, this_value_expr, max_value_expr, max_width, as_, asvar = bits if as_ != 'as': raise TemplateSyntaxError("Invalid syntax in widthratio tag. Expecting 'as' keyword") else: raise TemplateSyntaxError("widthratio takes at least three arguments") return WidthRatioNode(parser.compile_filter(this_value_expr), parser.compile_filter(max_value_expr), parser.compile_filter(max_width), asvar=asvar) @register.tag('with') def do_with(parser, token): """ Adds one or more values to the context (inside of this block) for caching and easy access. For example:: {% with total=person.some_sql_method %} {{ total }} object{{ total|pluralize }} {% endwith %} Multiple values can be added to the context:: {% with foo=1 bar=2 %} ... {% endwith %} The legacy format of ``{% with person.some_sql_method as total %}`` is still accepted. """ bits = token.split_contents() remaining_bits = bits[1:] extra_context = token_kwargs(remaining_bits, parser, support_legacy=True) if not extra_context: raise TemplateSyntaxError("%r expected at least one variable " "assignment" % bits[0]) if remaining_bits: raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0])) nodelist = parser.parse(('endwith',)) parser.delete_first_token() return WithNode(None, None, nodelist, extra_context=extra_context)
bsd-3-clause
ojengwa/oh-mainline
vendor/packages/sphinx/sphinx/transforms.py
15
18874
# -*- coding: utf-8 -*- """ sphinx.transforms ~~~~~~~~~~~~~~~~~ Docutils transforms used by Sphinx when reading documents. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from os import path from docutils import nodes from docutils.utils import new_document, relative_path from docutils.parsers.rst import Parser as RSTParser from docutils.transforms import Transform from docutils.transforms.parts import ContentsFilter from sphinx import addnodes from sphinx.locale import _, init as init_locale from sphinx.util import split_index_msg from sphinx.util.nodes import traverse_translatable_index, extract_messages from sphinx.util.osutil import ustrftime, find_catalog from sphinx.util.compat import docutils_version from sphinx.util.pycompat import all from sphinx.domains.std import ( make_term_from_paragraph_node, make_termnodes_from_paragraph_node, ) default_substitutions = set([ 'version', 'release', 'today', ]) class DefaultSubstitutions(Transform): """ Replace some substitutions if they aren't defined in the document. """ # run before the default Substitutions default_priority = 210 def apply(self): config = self.document.settings.env.config # only handle those not otherwise defined in the document to_handle = default_substitutions - set(self.document.substitution_defs) for ref in self.document.traverse(nodes.substitution_reference): refname = ref['refname'] if refname in to_handle: text = config[refname] if refname == 'today' and not text: # special handling: can also specify a strftime format text = ustrftime(config.today_fmt or _('%B %d, %Y')) ref.replace_self(nodes.Text(text, text)) class MoveModuleTargets(Transform): """ Move module targets that are the first thing in a section to the section title. XXX Python specific """ default_priority = 210 def apply(self): for node in self.document.traverse(nodes.target): if not node['ids']: continue if (node.has_key('ismod') and node.parent.__class__ is nodes.section and # index 0 is the section title node node.parent.index(node) == 1): node.parent['ids'][0:0] = node['ids'] node.parent.remove(node) class HandleCodeBlocks(Transform): """ Several code block related transformations. """ default_priority = 210 def apply(self): # move doctest blocks out of blockquotes for node in self.document.traverse(nodes.block_quote): if all(isinstance(child, nodes.doctest_block) for child in node.children): node.replace_self(node.children) # combine successive doctest blocks #for node in self.document.traverse(nodes.doctest_block): # if node not in node.parent.children: # continue # parindex = node.parent.index(node) # while len(node.parent) > parindex+1 and \ # isinstance(node.parent[parindex+1], nodes.doctest_block): # node[0] = nodes.Text(node[0] + '\n\n' + # node.parent[parindex+1][0]) # del node.parent[parindex+1] class SortIds(Transform): """ Sort secion IDs so that the "id[0-9]+" one comes last. """ default_priority = 261 def apply(self): for node in self.document.traverse(nodes.section): if len(node['ids']) > 1 and node['ids'][0].startswith('id'): node['ids'] = node['ids'][1:] + [node['ids'][0]] class CitationReferences(Transform): """ Replace citation references by pending_xref nodes before the default docutils transform tries to resolve them. """ default_priority = 619 def apply(self): for citnode in self.document.traverse(nodes.citation_reference): cittext = citnode.astext() refnode = addnodes.pending_xref(cittext, reftype='citation', reftarget=cittext, refwarn=True, ids=citnode["ids"]) refnode.line = citnode.line or citnode.parent.line refnode += nodes.Text('[' + cittext + ']') citnode.parent.replace(citnode, refnode) class CustomLocaleReporter(object): """ Replacer for document.reporter.get_source_and_line method. reST text lines for translation do not have the original source line number. This class provides the correct line numbers when reporting. """ def __init__(self, source, line): self.source, self.line = source, line def set_reporter(self, document): if docutils_version < (0, 9): document.reporter.locator = self.get_source_and_line else: document.reporter.get_source_and_line = self.get_source_and_line def get_source_and_line(self, lineno=None): return self.source, self.line class Locale(Transform): """ Replace translatable nodes with their translated doctree. """ default_priority = 0 def apply(self): env = self.document.settings.env settings, source = self.document.settings, self.document['source'] # XXX check if this is reliable assert source.startswith(env.srcdir) docname = path.splitext(relative_path(env.srcdir, source))[0] textdomain = find_catalog(docname, self.document.settings.gettext_compact) # fetch translations dirs = [path.join(env.srcdir, directory) for directory in env.config.locale_dirs] catalog, has_catalog = init_locale(dirs, env.config.language, textdomain) if not has_catalog: return parser = RSTParser() #phase1: replace reference ids with translated names for node, msg in extract_messages(self.document): msgstr = catalog.gettext(msg) # XXX add marker to untranslated parts if not msgstr or msgstr == msg or not msgstr.strip(): # as-of-yet untranslated continue # Avoid "Literal block expected; none found." warnings. # If msgstr ends with '::' then it cause warning message at # parser.parse() processing. # literal-block-warning is only appear in avobe case. if msgstr.strip().endswith('::'): msgstr += '\n\n dummy literal' # dummy literal node will discard by 'patch = patch[0]' patch = new_document(source, settings) CustomLocaleReporter(node.source, node.line).set_reporter(patch) parser.parse(msgstr, patch) patch = patch[0] # XXX doctest and other block markup if not isinstance(patch, nodes.paragraph): continue # skip for now processed = False # skip flag # update title(section) target name-id mapping if isinstance(node, nodes.title): section_node = node.parent new_name = nodes.fully_normalize_name(patch.astext()) old_name = nodes.fully_normalize_name(node.astext()) if old_name != new_name: # if name would be changed, replace node names and # document nameids mapping with new name. names = section_node.setdefault('names', []) names.append(new_name) if old_name in names: names.remove(old_name) _id = self.document.nameids.get(old_name, None) explicit = self.document.nametypes.get(old_name, None) # * if explicit: _id is label. title node need another id. # * if not explicit: # # * _id is None: # # _id is None means _id was duplicated. # old_name entry still exists in nameids and # nametypes for another duplicated entry. # # * _id is provided: bellow process if not explicit and _id: # _id was not duplicated. # remove old_name entry from document ids database # to reuse original _id. self.document.nameids.pop(old_name, None) self.document.nametypes.pop(old_name, None) self.document.ids.pop(_id, None) # re-entry with new named section node. self.document.note_implicit_target( section_node, section_node) # replace target's refname to new target name def is_named_target(node): return isinstance(node, nodes.target) and \ node.get('refname') == old_name for old_target in self.document.traverse(is_named_target): old_target['refname'] = new_name processed = True # glossary terms update refid if isinstance(node, nodes.term): gloss_entries = env.temp_data.setdefault('gloss_entries', set()) ids = [] termnodes = [] for _id in node['names']: if _id in gloss_entries: gloss_entries.remove(_id) _id, _, new_termnodes = \ make_termnodes_from_paragraph_node(env, patch, _id) ids.append(_id) termnodes.extend(new_termnodes) if termnodes and ids: patch = make_term_from_paragraph_node(termnodes, ids) node['ids'] = patch['ids'] node['names'] = patch['names'] processed = True # update leaves with processed nodes if processed: for child in patch.children: child.parent = node node.children = patch.children node['translated'] = True #phase2: translation for node, msg in extract_messages(self.document): if node.get('translated', False): continue msgstr = catalog.gettext(msg) # XXX add marker to untranslated parts if not msgstr or msgstr == msg: # as-of-yet untranslated continue # Avoid "Literal block expected; none found." warnings. # If msgstr ends with '::' then it cause warning message at # parser.parse() processing. # literal-block-warning is only appear in avobe case. if msgstr.strip().endswith('::'): msgstr += '\n\n dummy literal' # dummy literal node will discard by 'patch = patch[0]' patch = new_document(source, settings) CustomLocaleReporter(node.source, node.line).set_reporter(patch) parser.parse(msgstr, patch) patch = patch[0] # XXX doctest and other block markup if not isinstance(patch, nodes.paragraph): continue # skip for now # auto-numbered foot note reference should use original 'ids'. def is_autonumber_footnote_ref(node): return isinstance(node, nodes.footnote_reference) and \ node.get('auto') == 1 def list_replace_or_append(lst, old, new): if old in lst: lst[lst.index(old)] = new else: lst.append(new) old_foot_refs = node.traverse(is_autonumber_footnote_ref) new_foot_refs = patch.traverse(is_autonumber_footnote_ref) if len(old_foot_refs) != len(new_foot_refs): env.warn_node('inconsistent footnote references in ' 'translated message', node) old_foot_namerefs = {} for r in old_foot_refs: old_foot_namerefs.setdefault(r.get('refname'), []).append(r) for new in new_foot_refs: refname = new.get('refname') refs = old_foot_namerefs.get(refname, []) if not refs: continue old = refs.pop(0) new['ids'] = old['ids'] for id in new['ids']: self.document.ids[id] = new list_replace_or_append( self.document.autofootnote_refs, old, new) if refname: list_replace_or_append( self.document.footnote_refs.setdefault(refname, []), old, new) list_replace_or_append( self.document.refnames.setdefault(refname, []), old, new) # reference should use new (translated) 'refname'. # * reference target ".. _Python: ..." is not translatable. # * use translated refname for section refname. # * inline reference "`Python <...>`_" has no 'refname'. def is_refnamed_ref(node): return isinstance(node, nodes.reference) and \ 'refname' in node old_refs = node.traverse(is_refnamed_ref) new_refs = patch.traverse(is_refnamed_ref) if len(old_refs) != len(new_refs): env.warn_node('inconsistent references in ' 'translated message', node) old_ref_names = [r['refname'] for r in old_refs] new_ref_names = [r['refname'] for r in new_refs] orphans = list(set(old_ref_names) - set(new_ref_names)) for new in new_refs: if not self.document.has_name(new['refname']): # Maybe refname is translated but target is not translated. # Note: multiple translated refnames break link ordering. if orphans: new['refname'] = orphans.pop(0) else: # orphan refnames is already empty! # reference number is same in new_refs and old_refs. pass self.document.note_refname(new) # refnamed footnote and citation should use original 'ids'. def is_refnamed_footnote_ref(node): footnote_ref_classes = (nodes.footnote_reference, nodes.citation_reference) return isinstance(node, footnote_ref_classes) and \ 'refname' in node old_refs = node.traverse(is_refnamed_footnote_ref) new_refs = patch.traverse(is_refnamed_footnote_ref) refname_ids_map = {} if len(old_refs) != len(new_refs): env.warn_node('inconsistent references in ' 'translated message', node) for old in old_refs: refname_ids_map[old["refname"]] = old["ids"] for new in new_refs: refname = new["refname"] if refname in refname_ids_map: new["ids"] = refname_ids_map[refname] # Original pending_xref['reftarget'] contain not-translated # target name, new pending_xref must use original one. # This code restricts to change ref-targets in the translation. old_refs = node.traverse(addnodes.pending_xref) new_refs = patch.traverse(addnodes.pending_xref) xref_reftarget_map = {} if len(old_refs) != len(new_refs): env.warn_node('inconsistent term references in ' 'translated message', node) def get_ref_key(node): case = node["refdomain"], node["reftype"] if case == ('std', 'term'): return None else: return ( node["refdomain"], node["reftype"], node['reftarget'],) for old in old_refs: key = get_ref_key(old) if key: xref_reftarget_map[key] = old["reftarget"] for new in new_refs: key = get_ref_key(new) if key in xref_reftarget_map: new['reftarget'] = xref_reftarget_map[key] # update leaves for child in patch.children: child.parent = node node.children = patch.children node['translated'] = True # Extract and translate messages for index entries. for node, entries in traverse_translatable_index(self.document): new_entries = [] for type, msg, tid, main in entries: msg_parts = split_index_msg(type, msg) msgstr_parts = [] for part in msg_parts: msgstr = catalog.gettext(part) if not msgstr: msgstr = part msgstr_parts.append(msgstr) new_entries.append((type, ';'.join(msgstr_parts), tid, main)) node['raw_entries'] = entries node['entries'] = new_entries class RemoveTranslatableInline(Transform): """ Remove inline nodes used for translation as placeholders. """ default_priority = 999 def apply(self): from sphinx.builders.gettext import MessageCatalogBuilder env = self.document.settings.env builder = env.app.builder if isinstance(builder, MessageCatalogBuilder): return for inline in self.document.traverse(nodes.inline): if 'translatable' in inline: inline.parent.remove(inline) inline.parent += inline.children class SphinxContentsFilter(ContentsFilter): """ Used with BuildEnvironment.add_toc_from() to discard cross-file links within table-of-contents link nodes. """ def visit_pending_xref(self, node): text = node.astext() self.parent.append(nodes.literal(text, text)) raise nodes.SkipNode def visit_image(self, node): raise nodes.SkipNode
agpl-3.0
mkrautz/gyp-libmumble
test/win/gyptest-cl-warning-level.py
344
1394
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Make sure warning level is extracted properly. """ import TestGyp import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'compiler-flags' test.run_gyp('warning-level.gyp', chdir=CHDIR) # A separate target for each warning level: one pass (compiling a file # containing a warning that's above the specified level); and one fail # (compiling a file at the specified level). No pass for 4 of course, # because it would have to have no warnings. The default warning level is # equivalent to level 1. test.build('warning-level.gyp', 'test_wl1_fail', chdir=CHDIR, status=1) test.build('warning-level.gyp', 'test_wl1_pass', chdir=CHDIR) test.build('warning-level.gyp', 'test_wl2_fail', chdir=CHDIR, status=1) test.build('warning-level.gyp', 'test_wl2_pass', chdir=CHDIR) test.build('warning-level.gyp', 'test_wl3_fail', chdir=CHDIR, status=1) test.build('warning-level.gyp', 'test_wl3_pass', chdir=CHDIR) test.build('warning-level.gyp', 'test_wl4_fail', chdir=CHDIR, status=1) test.build('warning-level.gyp', 'test_def_fail', chdir=CHDIR, status=1) test.build('warning-level.gyp', 'test_def_pass', chdir=CHDIR) test.pass_test()
bsd-3-clause
edf-hpc/three.js
utils/converters/msgpack/json2msgpack.py
331
1366
#!/usr/bin/env python __doc__ = ''' Convert a json file to msgpack. If fed only an input file the converted will write out a .pack file of the same base name in the same directory $ json2msgpack.py -i foo.json foo.json > foo.pack Specify an output file path $ json2msgpack.py -i foo.json -o /bar/tmp/bar.pack foo.json > /bar/tmp/bar.pack Dependencies: https://github.com/msgpack/msgpack-python ''' import os import sys import json import argparse sys.path.append(os.path.dirname(os.path.realpath(__file__))) import msgpack EXT = '.pack' def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--infile', required=True, help='Input json file to convert to msgpack') parser.add_argument('-o', '--outfile', help=('Optional output. If not specified the .pack file '\ 'will write to the same director as the input file.')) args = parser.parse_args() convert(args.infile, args.outfile) def convert(infile, outfile): if not outfile: ext = infile.split('.')[-1] outfile = '%s%s' % (infile[:-len(ext)-1], EXT) print('%s > %s' % (infile, outfile)) print('reading in JSON') with open(infile) as op: data = json.load(op) print('writing to msgpack') with open(outfile, 'wb') as op: msgpack.dump(data, op) if __name__ == '__main__': main()
mit
simongoffin/website_version
addons/crm_partner_assign/wizard/crm_forward_to_partner.py
377
10606
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class crm_lead_forward_to_partner(osv.TransientModel): """ Forward info history to partners. """ _name = 'crm.lead.forward.to.partner' def _convert_to_assignation_line(self, cr, uid, lead, partner, context=None): lead_location = [] partner_location = [] if lead.country_id: lead_location.append(lead.country_id.name) if lead.city: lead_location.append(lead.city) if partner: if partner.country_id: partner_location.append(partner.country_id.name) if partner.city: partner_location.append(partner.city) return {'lead_id': lead.id, 'lead_location': ", ".join(lead_location), 'partner_assigned_id': partner and partner.id or False, 'partner_location': ", ".join(partner_location), 'lead_link': self.get_lead_portal_url(cr, uid, lead.id, lead.type, context=context), } def default_get(self, cr, uid, fields, context=None): if context is None: context = {} lead_obj = self.pool.get('crm.lead') email_template_obj = self.pool.get('email.template') try: template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', 'email_template_lead_forward_mail')[1] except ValueError: template_id = False res = super(crm_lead_forward_to_partner, self).default_get(cr, uid, fields, context=context) active_ids = context.get('active_ids') default_composition_mode = context.get('default_composition_mode') res['assignation_lines'] = [] if template_id: res['body'] = email_template_obj.get_email_template(cr, uid, template_id).body_html if active_ids: lead_ids = lead_obj.browse(cr, uid, active_ids, context=context) if default_composition_mode == 'mass_mail': partner_assigned_ids = lead_obj.search_geo_partner(cr, uid, active_ids, context=context) else: partner_assigned_ids = dict((lead.id, lead.partner_assigned_id and lead.partner_assigned_id.id or False) for lead in lead_ids) res['partner_id'] = lead_ids[0].partner_assigned_id.id for lead in lead_ids: partner_id = partner_assigned_ids.get(lead.id) or False partner = False if partner_id: partner = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context) res['assignation_lines'].append(self._convert_to_assignation_line(cr, uid, lead, partner)) return res def action_forward(self, cr, uid, ids, context=None): lead_obj = self.pool.get('crm.lead') record = self.browse(cr, uid, ids[0], context=context) email_template_obj = self.pool.get('email.template') try: template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', 'email_template_lead_forward_mail')[1] except ValueError: raise osv.except_osv(_('Email Template Error'), _('The Forward Email Template is not in the database')) try: portal_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_portal')[1] except ValueError: raise osv.except_osv(_('Portal Group Error'), _('The Portal group cannot be found')) local_context = context.copy() if not (record.forward_type == 'single'): no_email = set() for lead in record.assignation_lines: if lead.partner_assigned_id and not lead.partner_assigned_id.email: no_email.add(lead.partner_assigned_id.name) if no_email: raise osv.except_osv(_('Email Error'), ('Set an email address for the partner(s): %s' % ", ".join(no_email))) if record.forward_type == 'single' and not record.partner_id.email: raise osv.except_osv(_('Email Error'), ('Set an email address for the partner %s' % record.partner_id.name)) partners_leads = {} for lead in record.assignation_lines: partner = record.forward_type == 'single' and record.partner_id or lead.partner_assigned_id lead_details = { 'lead_link': lead.lead_link, 'lead_id': lead.lead_id, } if partner: partner_leads = partners_leads.get(partner.id) if partner_leads: partner_leads['leads'].append(lead_details) else: partners_leads[partner.id] = {'partner': partner, 'leads': [lead_details]} stage_id = False if record.assignation_lines and record.assignation_lines[0].lead_id.type == 'lead': try: stage_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', 'stage_portal_lead_assigned')[1] except ValueError: pass for partner_id, partner_leads in partners_leads.items(): in_portal = False for contact in (partner.child_ids or [partner]): if contact.user_ids: in_portal = portal_id in [g.id for g in contact.user_ids[0].groups_id] local_context['partner_id'] = partner_leads['partner'] local_context['partner_leads'] = partner_leads['leads'] local_context['partner_in_portal'] = in_portal email_template_obj.send_mail(cr, uid, template_id, ids[0], context=local_context) lead_ids = [lead['lead_id'].id for lead in partner_leads['leads']] values = {'partner_assigned_id': partner_id, 'user_id': partner_leads['partner'].user_id.id} if stage_id: values['stage_id'] = stage_id if partner_leads['partner'].user_id: values['section_id'] = partner_leads['partner'].user_id.default_section_id.id lead_obj.write(cr, uid, lead_ids, values) self.pool.get('crm.lead').message_subscribe(cr, uid, lead_ids, [partner_id], context=context) return True def get_lead_portal_url(self, cr, uid, lead_id, type, context=None): action = type == 'opportunity' and 'action_portal_opportunities' or 'action_portal_leads' try: action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'crm_partner_assign', action)[1] except ValueError: action_id = False portal_link = "%s/?db=%s#id=%s&action=%s&view_type=form" % (self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url'), cr.dbname, lead_id, action_id) return portal_link def get_portal_url(self, cr, uid, ids, context=None): portal_link = "%s/?db=%s" % (self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url'), cr.dbname) return portal_link _columns = { 'forward_type': fields.selection([('single', 'a single partner: manual selection of partner'), ('assigned', "several partners: automatic assignation, using GPS coordinates and partner's grades"), ], 'Forward selected leads to'), 'partner_id': fields.many2one('res.partner', 'Forward Leads To'), 'assignation_lines': fields.one2many('crm.lead.assignation', 'forward_id', 'Partner Assignation'), 'body': fields.html('Contents', help='Automatically sanitized HTML contents'), } _defaults = { 'forward_type': lambda self, cr, uid, c: c.get('forward_type') or 'single', } class crm_lead_assignation (osv.TransientModel): _name = 'crm.lead.assignation' _columns = { 'forward_id': fields.many2one('crm.lead.forward.to.partner', 'Partner Assignation'), 'lead_id': fields.many2one('crm.lead', 'Lead'), 'lead_location': fields.char('Lead Location', size=128), 'partner_assigned_id': fields.many2one('res.partner', 'Assigned Partner'), 'partner_location': fields.char('Partner Location', size=128), 'lead_link': fields.char('Lead Single Links', size=128), } def on_change_lead_id(self, cr, uid, ids, lead_id, context=None): if not context: context = {} if not lead_id: return {'value': {'lead_location': False}} lead = self.pool.get('crm.lead').browse(cr, uid, lead_id, context=context) lead_location = [] if lead.country_id: lead_location.append(lead.country_id.name) if lead.city: lead_location.append(lead.city) return {'value': {'lead_location': ", ".join(lead_location)}} def on_change_partner_assigned_id(self, cr, uid, ids, partner_assigned_id, context=None): if not context: context = {} if not partner_assigned_id: return {'value': {'lead_location': False}} partner = self.pool.get('res.partner').browse(cr, uid, partner_assigned_id, context=context) partner_location = [] if partner.country_id: partner_location.append(partner.country_id.name) if partner.city: partner_location.append(partner.city) return {'value': {'partner_location': ", ".join(partner_location)}} # # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
vladryk/horizon
openstack_dashboard/dashboards/project/routers/extensions/routerrules/tabs.py
36
8827
# Copyright 2013 # # 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 netaddr from django import template from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from horizon import tabs from openstack_dashboard import api from openstack_dashboard.dashboards.project.routers.extensions.routerrules\ import rulemanager from openstack_dashboard.dashboards.project.routers.extensions.routerrules\ import tables as rrtbl class RouterRulesTab(tabs.TableTab): table_classes = (rrtbl.RouterRulesTable,) name = _("Router Rules") slug = "routerrules" template_name = "horizon/common/_detail_table.html" def allowed(self, request): try: getattr(self.tab_group.kwargs['router'], 'router_rules') return True except Exception: return False def get_routerrules_data(self): try: routerrules = getattr(self.tab_group.kwargs['router'], 'router_rules') except Exception: routerrules = [] return [rulemanager.RuleObject(r) for r in routerrules] def post(self, request, *args, **kwargs): if request.POST['action'] == 'routerrules__resetrules': kwargs['reset_rules'] = True rulemanager.remove_rules(request, [], **kwargs) self.tab_group.kwargs['router'] = \ api.neutron.router_get(request, kwargs['router_id']) class RulesGridTab(tabs.Tab): name = _("Router Rules Grid") slug = "rulesgrid" template_name = ("project/routers/extensions/routerrules/grid.html") def allowed(self, request): try: getattr(self.tab_group.kwargs['router'], 'router_rules') return True except Exception: return False def render(self): context = template.RequestContext(self.request) return render_to_string(self.get_template_name(self.request), self.data, context_instance=context) def get_context_data(self, request, **kwargs): data = {'router': {'id': self.tab_group.kwargs['router_id']}} self.request = request rules, supported = self.get_routerrules_data(checksupport=True) if supported: data["rulesmatrix"] = self.get_routerrulesgrid_data(rules) return data def get_routerrulesgrid_data(self, rules): ports = self.tab_group.kwargs['ports'] networks = api.neutron.network_list_for_tenant( self.request, self.request.user.tenant_id) netnamemap = {} subnetmap = {} for n in networks: netnamemap[n['id']] = n.name_or_id for s in n.subnets: subnetmap[s.id] = {'name': s.name, 'cidr': s.cidr} matrix = [] subnets = [] for port in ports: for ip in port['fixed_ips']: if ip['subnet_id'] not in subnetmap: continue sub = {'ip': ip['ip_address'], 'subnetid': ip['subnet_id'], 'subnetname': subnetmap[ip['subnet_id']]['name'], 'networkid': port['network_id'], 'networkname': netnamemap[port['network_id']], 'cidr': subnetmap[ip['subnet_id']]['cidr']} subnets.append(sub) subnets.append({'ip': '0.0.0.0', 'subnetid': 'external', 'subnetname': '', 'networkname': 'external', 'networkid': 'external', 'cidr': '0.0.0.0/0'}) subnets.append({'ip': '0.0.0.0', 'subnetid': 'any', 'subnetname': '', 'networkname': 'any', 'networkid': 'any', 'cidr': '0.0.0.0/0'}) for source in subnets: row = {'source': dict(source), 'targets': []} for target in subnets: target.update(self._get_subnet_connectivity( source, target, rules)) row['targets'].append(dict(target)) matrix.append(row) return matrix def _get_subnet_connectivity(self, src_sub, dst_sub, rules): v4_any_words = ['external', 'any'] connectivity = {'reachable': '', 'inverse_rule': {}, 'rule_to_delete': False} src = src_sub['cidr'] dst = dst_sub['cidr'] # differentiate between external and any src_rulename = src_sub['subnetid'] if src == '0.0.0.0/0' else src dst_rulename = dst_sub['subnetid'] if dst == '0.0.0.0/0' else dst if str(src) == str(dst): connectivity['reachable'] = 'full' return connectivity matchingrules = [] for rule in rules: rd = rule['destination'] if rule['destination'] in v4_any_words: rd = '0.0.0.0/0' rs = rule['source'] if rule['source'] in v4_any_words: rs = '0.0.0.0/0' rs = netaddr.IPNetwork(rs) src = netaddr.IPNetwork(src) rd = netaddr.IPNetwork(rd) dst = netaddr.IPNetwork(dst) # check if cidrs are affected by rule first if (int(dst.network) >= int(rd.broadcast) or int(dst.broadcast) <= int(rd.network) or int(src.network) >= int(rs.broadcast) or int(src.broadcast) <= int(rs.network)): continue # skip matching rules for 'any' and 'external' networks if (str(dst) == '0.0.0.0/0' and str(rd) != '0.0.0.0/0'): continue if (str(src) == '0.0.0.0/0' and str(rs) != '0.0.0.0/0'): continue # external network rules only affect external traffic if (rule['source'] == 'external' and src_rulename not in v4_any_words): continue if (rule['destination'] == 'external' and dst_rulename not in v4_any_words): continue match = {'bitsinsrc': rs.prefixlen, 'bitsindst': rd.prefixlen, 'rule': rule} matchingrules.append(match) if not matchingrules: connectivity['reachable'] = 'none' connectivity['inverse_rule'] = {'source': src_rulename, 'destination': dst_rulename, 'action': 'permit'} return connectivity sortedrules = sorted(matchingrules, key=lambda k: (k['bitsinsrc'], k['bitsindst']), reverse=True) match = sortedrules[0] if (match['bitsinsrc'] > src.prefixlen or match['bitsindst'] > dst.prefixlen): connectivity['reachable'] = 'partial' connectivity['conflicting_rule'] = match['rule'] return connectivity if (match['rule']['source'] == src_rulename and match['rule']['destination'] == dst_rulename): connectivity['rule_to_delete'] = match['rule'] if match['rule']['action'] == 'permit': connectivity['reachable'] = 'full' inverseaction = 'deny' else: connectivity['reachable'] = 'none' inverseaction = 'permit' connectivity['inverse_rule'] = {'source': src_rulename, 'destination': dst_rulename, 'action': inverseaction} return connectivity def get_routerrules_data(self, checksupport=False): try: routerrules = getattr(self.tab_group.kwargs['router'], 'router_rules') supported = True except Exception: routerrules = [] supported = False if checksupport: return routerrules, supported return routerrules
apache-2.0
tomas-edwardsson/tommi-func
func/minion/modules/service.py
2
4641
## func ## ## Copyright 2007, Red Hat, Inc ## Michael DeHaan <mdehaan@redhat.com> ## ## This software may be freely redistributed under the terms of the GNU ## general public license. ## ## 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., 675 Mass Ave, Cambridge, MA 02139, USA. ## ## import codes import func_module import sub_process import os class Service(func_module.FuncModule): version = "0.0.1" api_version = "0.0.1" description = "Allows for service control via func." def __command(self, service_name, command): service_name = service_name.strip() # remove useless spaces filename = os.path.join("/etc/rc.d/init.d/",service_name) if os.path.exists(filename): return sub_process.call(["/sbin/service", service_name, command], close_fds=True) else: raise codes.FuncException("Service not installed: %s" % service_name) def start(self, service_name): return self.__command(service_name, "start") def stop(self, service_name): return self.__command(service_name, "stop") def restart(self, service_name): return self.__command(service_name, "restart") def reload(self, service_name): return self.__command(service_name, "reload") def status(self, service_name): return self.__command(service_name, "status") def inventory(self): return { "running" : self.get_running(), "enabled" : self.get_enabled() } def grep(self,word): """ Dig for some useful info in that module ... """ final_dict = {self.get_running:[], self.get_enabled:[] } running = self.get_running() enabled = self.get_enabled() #get enabled ones for e in enabled: if e[0].lower().find(word)!=-1: final_dict[self.get_enabled].append(e) #get running ones for e in running: if e[0].lower().find(word)!=-1: final_dict[self.get_running].append(e) return final_dict grep = func_module.findout(grep) def get_enabled(self): """ Get the list of services that are enabled at the various runlevels. Xinetd services only provide whether or not they are running, not specific runlevel info. """ chkconfig = sub_process.Popen(["/sbin/chkconfig", "--list"], stdout=sub_process.PIPE, close_fds=True) data = chkconfig.communicate()[0] results = [] for line in data.split("\n"): if line.find("0:") != -1: # regular services tokens = line.split() results.append((tokens[0],tokens[1:])) elif line.find(":") != -1 and not line.endswith(":"): # xinetd.d based services tokens = line.split() tokens[0] = tokens[0].replace(":","") results.append((tokens[0],tokens[1])) return results def get_running(self): """ Get a list of which services are running, stopped, or disabled. """ chkconfig = sub_process.Popen(["/sbin/service", "--status-all"], stdout=sub_process.PIPE, close_fds=True) data = chkconfig.communicate()[0] results = [] for line in data.split("\n"): if line.find(" is ") != -1: tokens = line.split() results.append((tokens[0], tokens[-1].replace("...",""))) return results def register_method_args(self): """ Implementing the argument getter """ #service_name options they are same so use only one service_name = { 'type':'string', 'optional':False, 'description':'The name of the running services', 'validator':'^[a-z\-\_0-9]+$'} return { 'get_running':{'args':{}}, 'get_enabled':{'args':{}}, 'inventory':{'args':{}}, 'status':{'args':{ 'service_name':service_name, }, 'description':'Getting the status of the service_name' }, 'reload':{'args':{'service_name':service_name}}, 'restart':{'args':{'service_name':service_name}}, 'stop':{'args':{'service_name':service_name}}, 'start':{'args':{'service_name':service_name}}, }
gpl-2.0
phw/weblate
weblate/trans/context_processors.py
1
2958
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import weblate from weblate import appsettings from datetime import datetime from weblate.trans.site import get_site_url from weblate.trans.models.project import Project from weblate.trans.models.translation import Translation URL_BASE = 'https://weblate.org/?utm_source=weblate&utm_term=%s' URL_DONATE = 'https://weblate.org/donate/?utm_source=weblate&utm_term=%s' def weblate_context(request): """ Context processor to inject various useful variables into context. """ if 'next' in request.GET: login_redirect_url = request.GET['next'] else: login_redirect_url = request.get_full_path() projects = Project.objects.all_acl(request.user) # Load user translations if user is authenticated usertranslations = None if request.user.is_authenticated(): usertranslations = Translation.objects.filter( language__in=request.user.profile.languages.all(), subproject__project__in=projects, ).order_by( 'subproject__project__name', 'subproject__name' ).select_related() return { 'version': weblate.VERSION, 'weblate_url': URL_BASE % weblate.VERSION, 'donate_url': URL_DONATE % weblate.VERSION, 'site_title': appsettings.SITE_TITLE, 'site_url': get_site_url(), 'offer_hosting': appsettings.OFFER_HOSTING, 'demo_server': appsettings.DEMO_SERVER, 'enable_avatars': appsettings.ENABLE_AVATARS, 'enable_sharing': appsettings.ENABLE_SHARING, 'piwik_site_id': appsettings.PIWIK_SITE_ID, 'piwik_url': appsettings.PIWIK_URL, 'google_analytics_id': appsettings.GOOGLE_ANALYTICS_ID, 'current_date': datetime.utcnow().strftime('%Y-%m-%d'), 'current_year': datetime.utcnow().strftime('%Y'), 'current_month': datetime.utcnow().strftime('%m'), 'login_redirect_url': login_redirect_url, 'hooks_enabled': appsettings.ENABLE_HOOKS, 'whiteboard_enabled': appsettings.ENABLE_WHITEBOARD, 'registration_open': appsettings.REGISTRATION_OPEN, 'acl_projects': projects, 'usertranslations': usertranslations, }
gpl-3.0
FlameDevelopment/Flamedevelopment.co.uk
node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/tools/pretty_gyp.py
2618
4756
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Pretty-prints the contents of a GYP file.""" import sys import re # Regex to remove comments when we're counting braces. COMMENT_RE = re.compile(r'\s*#.*') # Regex to remove quoted strings when we're counting braces. # It takes into account quoted quotes, and makes sure that the quotes match. # NOTE: It does not handle quotes that span more than one line, or # cases where an escaped quote is preceeded by an escaped backslash. QUOTE_RE_STR = r'(?P<q>[\'"])(.*?)(?<![^\\][\\])(?P=q)' QUOTE_RE = re.compile(QUOTE_RE_STR) def comment_replace(matchobj): return matchobj.group(1) + matchobj.group(2) + '#' * len(matchobj.group(3)) def mask_comments(input): """Mask the quoted strings so we skip braces inside quoted strings.""" search_re = re.compile(r'(.*?)(#)(.*)') return [search_re.sub(comment_replace, line) for line in input] def quote_replace(matchobj): return "%s%s%s%s" % (matchobj.group(1), matchobj.group(2), 'x'*len(matchobj.group(3)), matchobj.group(2)) def mask_quotes(input): """Mask the quoted strings so we skip braces inside quoted strings.""" search_re = re.compile(r'(.*?)' + QUOTE_RE_STR) return [search_re.sub(quote_replace, line) for line in input] def do_split(input, masked_input, search_re): output = [] mask_output = [] for (line, masked_line) in zip(input, masked_input): m = search_re.match(masked_line) while m: split = len(m.group(1)) line = line[:split] + r'\n' + line[split:] masked_line = masked_line[:split] + r'\n' + masked_line[split:] m = search_re.match(masked_line) output.extend(line.split(r'\n')) mask_output.extend(masked_line.split(r'\n')) return (output, mask_output) def split_double_braces(input): """Masks out the quotes and comments, and then splits appropriate lines (lines that matche the double_*_brace re's above) before indenting them below. These are used to split lines which have multiple braces on them, so that the indentation looks prettier when all laid out (e.g. closing braces make a nice diagonal line). """ double_open_brace_re = re.compile(r'(.*?[\[\{\(,])(\s*)([\[\{\(])') double_close_brace_re = re.compile(r'(.*?[\]\}\)],?)(\s*)([\]\}\)])') masked_input = mask_quotes(input) masked_input = mask_comments(masked_input) (output, mask_output) = do_split(input, masked_input, double_open_brace_re) (output, mask_output) = do_split(output, mask_output, double_close_brace_re) return output def count_braces(line): """keeps track of the number of braces on a given line and returns the result. It starts at zero and subtracts for closed braces, and adds for open braces. """ open_braces = ['[', '(', '{'] close_braces = [']', ')', '}'] closing_prefix_re = re.compile(r'(.*?[^\s\]\}\)]+.*?)([\]\}\)],?)\s*$') cnt = 0 stripline = COMMENT_RE.sub(r'', line) stripline = QUOTE_RE.sub(r"''", stripline) for char in stripline: for brace in open_braces: if char == brace: cnt += 1 for brace in close_braces: if char == brace: cnt -= 1 after = False if cnt > 0: after = True # This catches the special case of a closing brace having something # other than just whitespace ahead of it -- we don't want to # unindent that until after this line is printed so it stays with # the previous indentation level. if cnt < 0 and closing_prefix_re.match(stripline): after = True return (cnt, after) def prettyprint_input(lines): """Does the main work of indenting the input based on the brace counts.""" indent = 0 basic_offset = 2 last_line = "" for line in lines: if COMMENT_RE.match(line): print line else: line = line.strip('\r\n\t ') # Otherwise doesn't strip \r on Unix. if len(line) > 0: (brace_diff, after) = count_braces(line) if brace_diff != 0: if after: print " " * (basic_offset * indent) + line indent += brace_diff else: indent += brace_diff print " " * (basic_offset * indent) + line else: print " " * (basic_offset * indent) + line else: print "" last_line = line def main(): if len(sys.argv) > 1: data = open(sys.argv[1]).read().splitlines() else: data = sys.stdin.read().splitlines() # Split up the double braces. lines = split_double_braces(data) # Indent and print the output. prettyprint_input(lines) return 0 if __name__ == '__main__': sys.exit(main())
gpl-2.0
uber/pyro
examples/mixed_hmm/experiment.py
1
5663
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import argparse import os import json import uuid import functools import torch import pyro import pyro.poutine as poutine from pyro.infer import TraceEnum_ELBO from model import model_generic, guide_generic from seal_data import prepare_seal def aic_num_parameters(model, guide=None): """ hacky AIC param count that includes all parameters in the model and guide """ def _size(tensor): """product of shape""" s = 1 for d in tensor.shape: s = s * d return s with poutine.block(), poutine.trace(param_only=True) as param_capture: TraceEnum_ELBO(max_plate_nesting=2).differentiable_loss(model, guide) return sum(_size(node["value"]) for node in param_capture.trace.nodes.values()) def run_expt(args): data_dir = args["folder"] dataset = "seal" # args["dataset"] seed = args["seed"] optim = args["optim"] lr = args["learnrate"] timesteps = args["timesteps"] schedule = [] if not args["schedule"] else [int(i) for i in args["schedule"].split(",")] random_effects = {"group": args["group"], "individual": args["individual"]} pyro.set_rng_seed(seed) # reproducible random effect parameter init filename = os.path.join(data_dir, "prep_seal_data.csv") config = prepare_seal(filename, random_effects) model = functools.partial(model_generic, config) # for JITing guide = functools.partial(guide_generic, config) # count the number of parameters once num_parameters = aic_num_parameters(model, guide) losses = [] # SGD if optim == "sgd": loss_fn = TraceEnum_ELBO(max_plate_nesting=2).differentiable_loss with pyro.poutine.trace(param_only=True) as param_capture: loss_fn(model, guide) params = [site["value"].unconstrained() for site in param_capture.trace.nodes.values()] optimizer = torch.optim.Adam(params, lr=lr) if schedule: scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=schedule, gamma=0.5) schedule_step_loss = False else: scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min') schedule_step_loss = True for t in range(timesteps): optimizer.zero_grad() loss = loss_fn(model, guide) loss.backward() optimizer.step() scheduler.step(loss.item() if schedule_step_loss else t) losses.append(loss.item()) print("Loss: {}, AIC[{}]: ".format(loss.item(), t), 2. * loss + 2. * num_parameters) # LBFGS elif optim == "lbfgs": loss_fn = TraceEnum_ELBO(max_plate_nesting=2).differentiable_loss with pyro.poutine.trace(param_only=True) as param_capture: loss_fn(model, guide) params = [site["value"].unconstrained() for site in param_capture.trace.nodes.values()] optimizer = torch.optim.LBFGS(params, lr=lr) if schedule: scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=schedule, gamma=0.5) schedule_step_loss = False else: schedule_step_loss = True scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min') for t in range(timesteps): def closure(): optimizer.zero_grad() loss = loss_fn(model, guide) loss.backward() return loss loss = optimizer.step(closure) scheduler.step(loss.item() if schedule_step_loss else t) losses.append(loss.item()) print("Loss: {}, AIC[{}]: ".format(loss.item(), t), 2. * loss + 2. * num_parameters) else: raise ValueError("{} not supported optimizer".format(optim)) aic_final = 2. * losses[-1] + 2. * num_parameters print("AIC final: {}".format(aic_final)) results = {} results["args"] = args results["sizes"] = config["sizes"] results["likelihoods"] = losses results["likelihood_final"] = losses[-1] results["aic_final"] = aic_final results["aic_num_parameters"] = num_parameters if args["resultsdir"] is not None and os.path.exists(args["resultsdir"]): re_str = "g" + ("n" if args["group"] is None else "d" if args["group"] == "discrete" else "c") re_str += "i" + ("n" if args["individual"] is None else "d" if args["individual"] == "discrete" else "c") results_filename = "expt_{}_{}_{}.json".format(dataset, re_str, str(uuid.uuid4().hex)[0:5]) with open(os.path.join(args["resultsdir"], results_filename), "w") as f: json.dump(results, f) return results if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-g", "--group", default="none", type=str) parser.add_argument("-i", "--individual", default="none", type=str) parser.add_argument("-f", "--folder", default="./", type=str) parser.add_argument("-o", "--optim", default="sgd", type=str) parser.add_argument("-lr", "--learnrate", default=0.05, type=float) parser.add_argument("-t", "--timesteps", default=1000, type=int) parser.add_argument("-r", "--resultsdir", default="./results", type=str) parser.add_argument("-s", "--seed", default=101, type=int) parser.add_argument("--schedule", default="", type=str) args = parser.parse_args() if args.group == "none": args.group = None if args.individual == "none": args.individual = None run_expt(vars(args))
apache-2.0
GoogleCloudPlatform/gsutil
gslib/commands/version.py
1
7115
# -*- coding: utf-8 -*- # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of gsutil version command.""" from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals import os import platform import re import sys import six import boto import crcmod import gslib from gslib.command import Command from gslib.utils import system_util from gslib.utils.boto_util import GetFriendlyConfigFilePaths from gslib.utils.boto_util import UsingCrcmodExtension from gslib.utils.constants import UTF8 from gslib.utils.hashing_helper import GetMd5 from gslib.utils.parallelism_framework_util import CheckMultiprocessingAvailableAndInit _SYNOPSIS = """ gsutil version """ _DETAILED_HELP_TEXT = (""" <B>SYNOPSIS</B> """ + _SYNOPSIS + """ <B>DESCRIPTION</B> Prints information about the version of gsutil. <B>OPTIONS</B> -l Prints additional information, such as the version of Python being used, the version of the Boto library, a checksum of the code, the path to gsutil, and the path to gsutil's configuration file. """) class VersionCommand(Command): """Implementation of gsutil version command.""" # Command specification. See base class for documentation. command_spec = Command.CreateCommandSpec( 'version', command_name_aliases=['ver'], usage_synopsis=_SYNOPSIS, min_args=0, max_args=0, supported_sub_args='l', file_url_ok=False, provider_url_ok=False, urls_start_arg=0, ) # Help specification. See help_provider.py for documentation. help_spec = Command.HelpSpec( help_name='version', help_name_aliases=['ver'], help_type='command_help', help_one_line_summary='Print version info about gsutil', help_text=_DETAILED_HELP_TEXT, subcommand_help_text={}, ) def RunCommand(self): """Command entry point for the version command.""" long_form = False if self.sub_opts: for o, _ in self.sub_opts: if o == '-l': long_form = True config_paths = ', '.join(GetFriendlyConfigFilePaths()) shipped_checksum = gslib.CHECKSUM try: cur_checksum = self._ComputeCodeChecksum() except IOError: cur_checksum = 'MISSING FILES' if shipped_checksum == cur_checksum: checksum_ok_str = 'OK' else: checksum_ok_str = '!= %s' % shipped_checksum sys.stdout.write('gsutil version: %s\n' % gslib.VERSION) if long_form: long_form_output = ( 'checksum: {checksum} ({checksum_ok})\n' 'boto version: {boto_version}\n' 'python version: {python_version}\n' 'OS: {os_version}\n' 'multiprocessing available: {multiprocessing_available}\n' 'using cloud sdk: {cloud_sdk}\n' 'pass cloud sdk credentials to gsutil: {cloud_sdk_credentials}\n' 'config path(s): {config_paths}\n' 'gsutil path: {gsutil_path}\n' 'compiled crcmod: {compiled_crcmod}\n' 'installed via package manager: {is_package_install}\n' 'editable install: {is_editable_install}\n') sys.stdout.write( long_form_output.format( checksum=cur_checksum, checksum_ok=checksum_ok_str, boto_version=boto.__version__, python_version=sys.version.replace('\n', ''), os_version='%s %s' % (platform.system(), platform.release()), multiprocessing_available=( CheckMultiprocessingAvailableAndInit().is_available), cloud_sdk=system_util.InvokedViaCloudSdk(), cloud_sdk_credentials=system_util.CloudSdkCredPassingEnabled(), config_paths=config_paths, gsutil_path=(GetCloudSdkGsutilWrapperScriptPath() or gslib.GSUTIL_PATH), compiled_crcmod=UsingCrcmodExtension(), is_package_install=gslib.IS_PACKAGE_INSTALL, is_editable_install=gslib.IS_EDITABLE_INSTALL, )) return 0 def _ComputeCodeChecksum(self): """Computes a checksum of gsutil code. This checksum can be used to determine if users locally modified gsutil when requesting support. (It's fine for users to make local mods, but when users ask for support we ask them to run a stock version of gsutil so we can reduce possible variables.) Returns: MD5 checksum of gsutil code. """ if gslib.IS_PACKAGE_INSTALL: return 'PACKAGED_GSUTIL_INSTALLS_DO_NOT_HAVE_CHECKSUMS' m = GetMd5() # Checksum gsutil and all .py files under gslib directory. files_to_checksum = [gslib.GSUTIL_PATH] for root, _, files in os.walk(gslib.GSLIB_DIR): for filepath in files: if filepath.endswith('.py'): files_to_checksum.append(os.path.join(root, filepath)) # Sort to ensure consistent checksum build, no matter how os.walk # orders the list. for filepath in sorted(files_to_checksum): if six.PY2: f = open(filepath, 'rb') content = f.read() content = re.sub(r'(\r\n|\r|\n)', b'\n', content) m.update(content) f.close() else: f = open(filepath, 'r', encoding=UTF8) content = f.read() content = re.sub(r'(\r\n|\r|\n)', '\n', content) m.update(content.encode(UTF8)) f.close() return m.hexdigest() def GetCloudSdkGsutilWrapperScriptPath(): """If gsutil was invoked via the Cloud SDK, find its gsutil wrapper script. Returns: (str) The path to the Cloud SDK's gsutil wrapper script, or an empty string if gsutil was not invoked via the Cloud SDK or the wrapper script could not be found at its expected path. """ # If running via the Cloud SDK, the "real" gsutil script was probably invoked # indirectly through gcloud's gsutil wrapper script (the former is at # <sdk-root>/platform/gsutil/gsutil, while the latter is located at # <sdk-root>/bin/gsutil). We should print the wrapper script's path if it # exists and we were invoked via the Cloud SDK. gsutil_path = gslib.GSUTIL_PATH if system_util.InvokedViaCloudSdk(): platform_path_suffix = os.path.join('platform', 'gsutil', 'gsutil') if gsutil_path.endswith(platform_path_suffix): bin_path = os.path.join( gsutil_path[0:gsutil_path.rfind(platform_path_suffix)], 'bin', 'gsutil', ) if os.path.exists(bin_path): return bin_path return ''
apache-2.0
boompieman/iim_project
project_python2/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/compat.py
2943
1157
######################## BEGIN LICENSE BLOCK ######################## # Contributor(s): # Ian Cordasco - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import sys if sys.version_info < (3, 0): base_str = (str, unicode) else: base_str = (bytes, str) def wrap_ord(a): if sys.version_info < (3, 0) and isinstance(a, base_str): return ord(a) else: return a
gpl-3.0
lbishal/scikit-learn
sklearn/datasets/base.py
22
22973
""" Base IO code for all datasets """ # Copyright (c) 2007 David Cournapeau <cournape@gmail.com> # 2010 Fabian Pedregosa <fabian.pedregosa@inria.fr> # 2010 Olivier Grisel <olivier.grisel@ensta.org> # License: BSD 3 clause import os import csv import sys import shutil from os import environ from os.path import dirname from os.path import join from os.path import exists from os.path import expanduser from os.path import isdir from os.path import splitext from os import listdir from os import makedirs import numpy as np from ..utils import check_random_state class Bunch(dict): """Container object for datasets Dictionary-like object that exposes its keys as attributes. >>> b = Bunch(a=1, b=2) >>> b['b'] 2 >>> b.b 2 >>> b.a = 3 >>> b['a'] 3 >>> b.c = 6 >>> b['c'] 6 """ def __init__(self, **kwargs): super(Bunch, self).__init__(kwargs) def __setattr__(self, key, value): self[key] = value def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key) def __getstate__(self): return self.__dict__ def get_data_home(data_home=None): """Return the path of the scikit-learn data dir. This folder is used by some large dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'scikit_learn_data' in the user home folder. Alternatively, it can be set by the 'SCIKIT_LEARN_DATA' environment variable or programmatically by giving an explicit folder path. The '~' symbol is expanded to the user home folder. If the folder does not already exist, it is automatically created. """ if data_home is None: data_home = environ.get('SCIKIT_LEARN_DATA', join('~', 'scikit_learn_data')) data_home = expanduser(data_home) if not exists(data_home): makedirs(data_home) return data_home def clear_data_home(data_home=None): """Delete all the content of the data home cache.""" data_home = get_data_home(data_home) shutil.rmtree(data_home) def load_files(container_path, description=None, categories=None, load_content=True, shuffle=True, encoding=None, decode_error='strict', random_state=0): """Load text files with categories as subfolder names. Individual samples are assumed to be files stored a two levels folder structure such as the following: container_folder/ category_1_folder/ file_1.txt file_2.txt ... file_42.txt category_2_folder/ file_43.txt file_44.txt ... The folder names are used as supervised signal label names. The individual file names are not important. This function does not try to extract features into a numpy array or scipy sparse matrix. In addition, if load_content is false it does not try to load the files in memory. To use text files in a scikit-learn classification or clustering algorithm, you will need to use the `sklearn.feature_extraction.text` module to build a feature extraction transformer that suits your problem. If you set load_content=True, you should also specify the encoding of the text using the 'encoding' parameter. For many modern text files, 'utf-8' will be the correct encoding. If you leave encoding equal to None, then the content will be made of bytes instead of Unicode, and you will not be able to use most functions in `sklearn.feature_extraction.text`. Similar feature extractors should be built for other kind of unstructured data input such as images, audio, video, ... Read more in the :ref:`User Guide <datasets>`. Parameters ---------- container_path : string or unicode Path to the main folder holding one subfolder per category description: string or unicode, optional (default=None) A paragraph describing the characteristic of the dataset: its source, reference, etc. categories : A collection of strings or None, optional (default=None) If None (default), load all the categories. If not None, list of category names to load (other categories ignored). load_content : boolean, optional (default=True) Whether to load or not the content of the different files. If true a 'data' attribute containing the text information is present in the data structure returned. If not, a filenames attribute gives the path to the files. encoding : string or None (default is None) If None, do not try to decode the content of the files (e.g. for images or other non-text content). If not None, encoding to use to decode text files to Unicode if load_content is True. decode_error: {'strict', 'ignore', 'replace'}, optional Instruction on what to do if a byte sequence is given to analyze that contains characters not of the given `encoding`. Passed as keyword argument 'errors' to bytes.decode. shuffle : bool, optional (default=True) Whether or not to shuffle the data: might be important for models that make the assumption that the samples are independent and identically distributed (i.i.d.), such as stochastic gradient descent. random_state : int, RandomState instance or None, optional (default=0) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: either data, the raw text data to learn, or 'filenames', the files holding it, 'target', the classification labels (integer index), 'target_names', the meaning of the labels, and 'DESCR', the full description of the dataset. """ target = [] target_names = [] filenames = [] folders = [f for f in sorted(listdir(container_path)) if isdir(join(container_path, f))] if categories is not None: folders = [f for f in folders if f in categories] for label, folder in enumerate(folders): target_names.append(folder) folder_path = join(container_path, folder) documents = [join(folder_path, d) for d in sorted(listdir(folder_path))] target.extend(len(documents) * [label]) filenames.extend(documents) # convert to array for fancy indexing filenames = np.array(filenames) target = np.array(target) if shuffle: random_state = check_random_state(random_state) indices = np.arange(filenames.shape[0]) random_state.shuffle(indices) filenames = filenames[indices] target = target[indices] if load_content: data = [] for filename in filenames: with open(filename, 'rb') as f: data.append(f.read()) if encoding is not None: data = [d.decode(encoding, decode_error) for d in data] return Bunch(data=data, filenames=filenames, target_names=target_names, target=target, DESCR=description) return Bunch(filenames=filenames, target_names=target_names, target=target, DESCR=description) def load_iris(): """Load and return the iris dataset (classification). The iris dataset is a classic and very easy multi-class classification dataset. ================= ============== Classes 3 Samples per class 50 Samples total 150 Dimensionality 4 Features real, positive ================= ============== Read more in the :ref:`User Guide <datasets>`. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn, 'target', the classification labels, 'target_names', the meaning of the labels, 'feature_names', the meaning of the features, and 'DESCR', the full description of the dataset. Examples -------- Let's say you are interested in the samples 10, 25, and 50, and want to know their class name. >>> from sklearn.datasets import load_iris >>> data = load_iris() >>> data.target[[10, 25, 50]] array([0, 0, 1]) >>> list(data.target_names) ['setosa', 'versicolor', 'virginica'] """ module_path = dirname(__file__) with open(join(module_path, 'data', 'iris.csv')) as csv_file: data_file = csv.reader(csv_file) temp = next(data_file) n_samples = int(temp[0]) n_features = int(temp[1]) target_names = np.array(temp[2:]) data = np.empty((n_samples, n_features)) target = np.empty((n_samples,), dtype=np.int) for i, ir in enumerate(data_file): data[i] = np.asarray(ir[:-1], dtype=np.float64) target[i] = np.asarray(ir[-1], dtype=np.int) with open(join(module_path, 'descr', 'iris.rst')) as rst_file: fdescr = rst_file.read() return Bunch(data=data, target=target, target_names=target_names, DESCR=fdescr, feature_names=['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']) def load_breast_cancer(): """Load and return the breast cancer wisconsin dataset (classification). The breast cancer dataset is a classic and very easy binary classification dataset. ================= ============== Classes 2 Samples per class 212(M),357(B) Samples total 569 Dimensionality 30 Features real, positive ================= ============== Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn, 'target', the classification labels, 'target_names', the meaning of the labels, 'feature_names', the meaning of the features, and 'DESCR', the full description of the dataset. The copy of UCI ML Breast Cancer Wisconsin (Diagnostic) dataset is downloaded from: https://goo.gl/U2Uwz2 Examples -------- Let's say you are interested in the samples 10, 50, and 85, and want to know their class name. >>> from sklearn.datasets import load_breast_cancer >>> data = load_breast_cancer() >>> data.target[[10, 50, 85]] array([0, 1, 0]) >>> list(data.target_names) ['malignant', 'benign'] """ module_path = dirname(__file__) with open(join(module_path, 'data', 'breast_cancer.csv')) as csv_file: data_file = csv.reader(csv_file) first_line = next(data_file) n_samples = int(first_line[0]) n_features = int(first_line[1]) target_names = np.array(first_line[2:4]) data = np.empty((n_samples, n_features)) target = np.empty((n_samples,), dtype=np.int) for count, value in enumerate(data_file): data[count] = np.asarray(value[:-1], dtype=np.float64) target[count] = np.asarray(value[-1], dtype=np.int) with open(join(module_path, 'descr', 'breast_cancer.rst')) as rst_file: fdescr = rst_file.read() feature_names = np.array(['mean radius', 'mean texture', 'mean perimeter', 'mean area', 'mean smoothness', 'mean compactness', 'mean concavity', 'mean concave points', 'mean symmetry', 'mean fractal dimension', 'radius error', 'texture error', 'perimeter error', 'area error', 'smoothness error', 'compactness error', 'concavity error', 'concave points error', 'symmetry error', 'fractal dimension error', 'worst radius', 'worst texture', 'worst perimeter', 'worst area', 'worst smoothness', 'worst compactness', 'worst concavity', 'worst concave points', 'worst symmetry', 'worst fractal dimension']) return Bunch(data=data, target=target, target_names=target_names, DESCR=fdescr, feature_names=feature_names) def load_digits(n_class=10): """Load and return the digits dataset (classification). Each datapoint is a 8x8 image of a digit. ================= ============== Classes 10 Samples per class ~180 Samples total 1797 Dimensionality 64 Features integers 0-16 ================= ============== Read more in the :ref:`User Guide <datasets>`. Parameters ---------- n_class : integer, between 0 and 10, optional (default=10) The number of classes to return. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn, 'images', the images corresponding to each sample, 'target', the classification labels for each sample, 'target_names', the meaning of the labels, and 'DESCR', the full description of the dataset. Examples -------- To load the data and visualize the images:: >>> from sklearn.datasets import load_digits >>> digits = load_digits() >>> print(digits.data.shape) (1797, 64) >>> import pylab as pl #doctest: +SKIP >>> pl.gray() #doctest: +SKIP >>> pl.matshow(digits.images[0]) #doctest: +SKIP >>> pl.show() #doctest: +SKIP """ module_path = dirname(__file__) data = np.loadtxt(join(module_path, 'data', 'digits.csv.gz'), delimiter=',') with open(join(module_path, 'descr', 'digits.rst')) as f: descr = f.read() target = data[:, -1] flat_data = data[:, :-1] images = flat_data.view() images.shape = (-1, 8, 8) if n_class < 10: idx = target < n_class flat_data, target = flat_data[idx], target[idx] images = images[idx] return Bunch(data=flat_data, target=target.astype(np.int), target_names=np.arange(10), images=images, DESCR=descr) def load_diabetes(): """Load and return the diabetes dataset (regression). ============== ================== Samples total 442 Dimensionality 10 Features real, -.2 < x < .2 Targets integer 25 - 346 ============== ================== Read more in the :ref:`User Guide <datasets>`. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn and 'target', the regression target for each sample. """ base_dir = join(dirname(__file__), 'data') data = np.loadtxt(join(base_dir, 'diabetes_data.csv.gz')) target = np.loadtxt(join(base_dir, 'diabetes_target.csv.gz')) return Bunch(data=data, target=target) def load_linnerud(): """Load and return the linnerud dataset (multivariate regression). Samples total: 20 Dimensionality: 3 for both data and targets Features: integer Targets: integer Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data' and 'targets', the two multivariate datasets, with 'data' corresponding to the exercise and 'targets' corresponding to the physiological measurements, as well as 'feature_names' and 'target_names'. """ base_dir = join(dirname(__file__), 'data/') # Read data data_exercise = np.loadtxt(base_dir + 'linnerud_exercise.csv', skiprows=1) data_physiological = np.loadtxt(base_dir + 'linnerud_physiological.csv', skiprows=1) # Read header with open(base_dir + 'linnerud_exercise.csv') as f: header_exercise = f.readline().split() with open(base_dir + 'linnerud_physiological.csv') as f: header_physiological = f.readline().split() with open(dirname(__file__) + '/descr/linnerud.rst') as f: descr = f.read() return Bunch(data=data_exercise, feature_names=header_exercise, target=data_physiological, target_names=header_physiological, DESCR=descr) def load_boston(): """Load and return the boston house-prices dataset (regression). ============== ============== Samples total 506 Dimensionality 13 Features real, positive Targets real 5. - 50. ============== ============== Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn, 'target', the regression targets, and 'DESCR', the full description of the dataset. Examples -------- >>> from sklearn.datasets import load_boston >>> boston = load_boston() >>> print(boston.data.shape) (506, 13) """ module_path = dirname(__file__) fdescr_name = join(module_path, 'descr', 'boston_house_prices.rst') with open(fdescr_name) as f: descr_text = f.read() data_file_name = join(module_path, 'data', 'boston_house_prices.csv') with open(data_file_name) as f: data_file = csv.reader(f) temp = next(data_file) n_samples = int(temp[0]) n_features = int(temp[1]) data = np.empty((n_samples, n_features)) target = np.empty((n_samples,)) temp = next(data_file) # names of features feature_names = np.array(temp) for i, d in enumerate(data_file): data[i] = np.asarray(d[:-1], dtype=np.float64) target[i] = np.asarray(d[-1], dtype=np.float64) return Bunch(data=data, target=target, # last column is target value feature_names=feature_names[:-1], DESCR=descr_text) def load_sample_images(): """Load sample images for image manipulation. Loads both, ``china`` and ``flower``. Returns ------- data : Bunch Dictionary-like object with the following attributes : 'images', the two sample images, 'filenames', the file names for the images, and 'DESCR' the full description of the dataset. Examples -------- To load the data and visualize the images: >>> from sklearn.datasets import load_sample_images >>> dataset = load_sample_images() #doctest: +SKIP >>> len(dataset.images) #doctest: +SKIP 2 >>> first_img_data = dataset.images[0] #doctest: +SKIP >>> first_img_data.shape #doctest: +SKIP (427, 640, 3) >>> first_img_data.dtype #doctest: +SKIP dtype('uint8') """ # Try to import imread from scipy. We do this lazily here to prevent # this module from depending on PIL. try: try: from scipy.misc import imread except ImportError: from scipy.misc.pilutil import imread except ImportError: raise ImportError("The Python Imaging Library (PIL) " "is required to load data from jpeg files") module_path = join(dirname(__file__), "images") with open(join(module_path, 'README.txt')) as f: descr = f.read() filenames = [join(module_path, filename) for filename in os.listdir(module_path) if filename.endswith(".jpg")] # Load image data for each image in the source folder. images = [imread(filename) for filename in filenames] return Bunch(images=images, filenames=filenames, DESCR=descr) def load_sample_image(image_name): """Load the numpy array of a single sample image Parameters ----------- image_name: {`china.jpg`, `flower.jpg`} The name of the sample image loaded Returns ------- img: 3D array The image as a numpy array: height x width x color Examples --------- >>> from sklearn.datasets import load_sample_image >>> china = load_sample_image('china.jpg') # doctest: +SKIP >>> china.dtype # doctest: +SKIP dtype('uint8') >>> china.shape # doctest: +SKIP (427, 640, 3) >>> flower = load_sample_image('flower.jpg') # doctest: +SKIP >>> flower.dtype # doctest: +SKIP dtype('uint8') >>> flower.shape # doctest: +SKIP (427, 640, 3) """ images = load_sample_images() index = None for i, filename in enumerate(images.filenames): if filename.endswith(image_name): index = i break if index is None: raise AttributeError("Cannot find sample image: %s" % image_name) return images.images[index] def _pkl_filepath(*args, **kwargs): """Ensure different filenames for Python 2 and Python 3 pickles An object pickled under Python 3 cannot be loaded under Python 2. An object pickled under Python 2 can sometimes not be loaded loaded correctly under Python 3 because some Python 2 strings are decoded as Python 3 strings which can be problematic for objects that use Python 2 strings as byte buffers for numerical data instead of "real" strings. Therefore, dataset loaders in scikit-learn use different files for pickles manages by Python 2 and Python 3 in the same SCIKIT_LEARN_DATA folder so as to avoid conflicts. args[-1] is expected to be the ".pkl" filename. Under Python 3, a suffix is inserted before the extension to s _pkl_filepath('/path/to/folder', 'filename.pkl') returns: - /path/to/folder/filename.pkl under Python 2 - /path/to/folder/filename_py3.pkl under Python 3+ """ py3_suffix = kwargs.get("py3_suffix", "_py3") basename, ext = splitext(args[-1]) if sys.version_info[0] >= 3: basename += py3_suffix new_args = args[:-1] + (basename + ext,) return join(*new_args)
bsd-3-clause
cyc805/FR_Comparison_LRD
src/spectrum/bindings/modulegen__gcc_LP64.py
14
487084
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.spectrum', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::AdhocAlohaNoackIdealPhyHelper [class] module.add_class('AdhocAlohaNoackIdealPhyHelper') ## 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']) ## spectrum-model.h (module 'spectrum'): ns3::BandInfo [struct] module.add_class('BandInfo') ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## data-rate.h (module 'network'): ns3::DataRate [class] module.add_class('DataRate', import_from_module='ns.network') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac16-address.h (module 'network'): ns3::Mac16Address [class] module.add_class('Mac16Address', import_from_module='ns.network') ## mac16-address.h (module 'network'): ns3::Mac16Address [class] root_module['ns3::Mac16Address'].implicitly_converts_to(root_module['ns3::Address']) ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## mac64-address.h (module 'network'): ns3::Mac64Address [class] module.add_class('Mac64Address', import_from_module='ns.network') ## mac64-address.h (module 'network'): ns3::Mac64Address [class] root_module['ns3::Mac64Address'].implicitly_converts_to(root_module['ns3::Address']) ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): ns3::MicrowaveOvenSpectrumValueHelper [class] module.add_class('MicrowaveOvenSpectrumValueHelper') ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo [class] module.add_class('RxSpectrumModelInfo') ## 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')) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::SpectrumAnalyzerHelper [class] module.add_class('SpectrumAnalyzerHelper') ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumChannelHelper [class] module.add_class('SpectrumChannelHelper') ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumPhyHelper [class] module.add_class('SpectrumPhyHelper') ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class] module.add_class('SystemWallClockMs', import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo [class] module.add_class('TxSpectrumModelInfo') ## 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']) ## vector.h (module 'core'): ns3::Vector2D [class] module.add_class('Vector2D', import_from_module='ns.core') ## vector.h (module 'core'): ns3::Vector3D [class] module.add_class('Vector3D', import_from_module='ns.core') ## waveform-generator-helper.h (module 'spectrum'): ns3::WaveformGeneratorHelper [class] module.add_class('WaveformGeneratorHelper') ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValue5MhzFactory [class] module.add_class('WifiSpectrumValue5MhzFactory', allow_subclassing=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValueHelper [class] module.add_class('WifiSpectrumValueHelper', allow_subclassing=True) ## 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') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel [class] module.add_class('PropagationDelayModel', import_from_module='ns.propagation', 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']) ## queue.h (module 'network'): ns3::Queue [class] module.add_class('Queue', import_from_module='ns.network', parent=root_module['ns3::Object']) ## queue.h (module 'network'): ns3::Queue::QueueMode [enumeration] module.add_enum('QueueMode', ['QUEUE_MODE_PACKETS', 'QUEUE_MODE_BYTES'], outer_class=root_module['ns3::Queue'], import_from_module='ns.network') ## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel [class] module.add_class('RandomPropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationDelayModel']) ## propagation-loss-model.h (module 'propagation'): ns3::RandomPropagationLossModel [class] module.add_class('RandomPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## propagation-loss-model.h (module 'propagation'): ns3::RangePropagationLossModel [class] module.add_class('RangePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::SpectrumConverter', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SpectrumConverter>'], 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::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::SpectrumModel', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SpectrumModel>'], 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::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::SpectrumSignalParameters', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SpectrumSignalParameters>'], 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::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::SpectrumValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SpectrumValue>'], 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')) ## spectrum-converter.h (module 'spectrum'): ns3::SpectrumConverter [class] module.add_class('SpectrumConverter', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >']) ## spectrum-error-model.h (module 'spectrum'): ns3::SpectrumErrorModel [class] module.add_class('SpectrumErrorModel', parent=root_module['ns3::Object']) ## spectrum-interference.h (module 'spectrum'): ns3::SpectrumInterference [class] module.add_class('SpectrumInterference', parent=root_module['ns3::Object']) ## spectrum-model.h (module 'spectrum'): ns3::SpectrumModel [class] module.add_class('SpectrumModel', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >']) ## spectrum-phy.h (module 'spectrum'): ns3::SpectrumPhy [class] module.add_class('SpectrumPhy', parent=root_module['ns3::Object']) ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::SpectrumPropagationLossModel [class] module.add_class('SpectrumPropagationLossModel', parent=root_module['ns3::Object']) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters [struct] module.add_class('SpectrumSignalParameters', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >']) ## spectrum-value.h (module 'spectrum'): ns3::SpectrumValue [class] module.add_class('SpectrumValue', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >']) ## 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']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## propagation-loss-model.h (module 'propagation'): ns3::TwoRayGroundPropagationLossModel [class] module.add_class('TwoRayGroundPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## waveform-generator.h (module 'spectrum'): ns3::WaveformGenerator [class] module.add_class('WaveformGenerator', parent=root_module['ns3::SpectrumPhy']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::AlohaNoackMacHeader [class] module.add_class('AlohaNoackMacHeader', parent=root_module['ns3::Header']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## constant-spectrum-propagation-loss.h (module 'spectrum'): ns3::ConstantSpectrumPropagationLossModel [class] module.add_class('ConstantSpectrumPropagationLossModel', parent=root_module['ns3::SpectrumPropagationLossModel']) ## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel [class] module.add_class('ConstantSpeedPropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationDelayModel']) ## data-rate.h (module 'network'): ns3::DataRateChecker [class] module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## data-rate.h (module 'network'): ns3::DataRateValue [class] module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class] module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class] module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class] module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## propagation-loss-model.h (module 'propagation'): ns3::FixedRssLossModel [class] module.add_class('FixedRssLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## propagation-loss-model.h (module 'propagation'): ns3::FriisPropagationLossModel [class] module.add_class('FriisPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## friis-spectrum-propagation-loss.h (module 'spectrum'): ns3::FriisSpectrumPropagationLossModel [class] module.add_class('FriisSpectrumPropagationLossModel', parent=root_module['ns3::SpectrumPropagationLossModel']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::HalfDuplexIdealPhy [class] module.add_class('HalfDuplexIdealPhy', parent=root_module['ns3::SpectrumPhy']) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::HalfDuplexIdealPhy::State [enumeration] module.add_enum('State', ['IDLE', 'TX', 'RX'], outer_class=root_module['ns3::HalfDuplexIdealPhy']) ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::HalfDuplexIdealPhySignalParameters [struct] module.add_class('HalfDuplexIdealPhySignalParameters', parent=root_module['ns3::SpectrumSignalParameters']) ## 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']) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## mac16-address.h (module 'network'): ns3::Mac16AddressChecker [class] module.add_class('Mac16AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac16-address.h (module 'network'): ns3::Mac16AddressValue [class] module.add_class('Mac16AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mac64-address.h (module 'network'): ns3::Mac64AddressChecker [class] module.add_class('Mac64AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac64-address.h (module 'network'): ns3::Mac64AddressValue [class] module.add_class('Mac64AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## propagation-loss-model.h (module 'propagation'): ns3::MatrixPropagationLossModel [class] module.add_class('MatrixPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## mobility-model.h (module 'mobility'): ns3::MobilityModel [class] module.add_class('MobilityModel', import_from_module='ns.mobility', parent=root_module['ns3::Object']) ## 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']) ## non-communicating-net-device.h (module 'spectrum'): ns3::NonCommunicatingNetDevice [class] module.add_class('NonCommunicatingNetDevice', parent=root_module['ns3::NetDevice']) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class] module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## spectrum-error-model.h (module 'spectrum'): ns3::ShannonSpectrumErrorModel [class] module.add_class('ShannonSpectrumErrorModel', parent=root_module['ns3::SpectrumErrorModel']) ## spectrum-analyzer.h (module 'spectrum'): ns3::SpectrumAnalyzer [class] module.add_class('SpectrumAnalyzer', parent=root_module['ns3::SpectrumPhy']) ## spectrum-channel.h (module 'spectrum'): ns3::SpectrumChannel [class] module.add_class('SpectrumChannel', parent=root_module['ns3::Channel']) ## 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']) ## vector.h (module 'core'): ns3::Vector2DChecker [class] module.add_class('Vector2DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector2DValue [class] module.add_class('Vector2DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector3DChecker [class] module.add_class('Vector3DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector3DValue [class] module.add_class('Vector3DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## aloha-noack-net-device.h (module 'spectrum'): ns3::AlohaNoackNetDevice [class] module.add_class('AlohaNoackNetDevice', parent=root_module['ns3::NetDevice']) ## aloha-noack-net-device.h (module 'spectrum'): ns3::AlohaNoackNetDevice::State [enumeration] module.add_enum('State', ['IDLE', 'TX', 'RX'], outer_class=root_module['ns3::AlohaNoackNetDevice']) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::MultiModelSpectrumChannel [class] module.add_class('MultiModelSpectrumChannel', parent=root_module['ns3::SpectrumChannel']) ## single-model-spectrum-channel.h (module 'spectrum'): ns3::SingleModelSpectrumChannel [class] module.add_class('SingleModelSpectrumChannel', parent=root_module['ns3::SpectrumChannel']) module.add_container('std::set< ns3::Ptr< ns3::SpectrumPhy > >', 'ns3::Ptr< ns3::SpectrumPhy >', container_type='set') module.add_container('ns3::SpectrumConverterMap_t', ('unsigned int', 'ns3::SpectrumConverter'), container_type='map') module.add_container('std::vector< double >', 'double', container_type='vector') module.add_container('ns3::Bands', 'ns3::BandInfo', container_type='vector') module.add_container('std::vector< ns3::Ptr< ns3::SpectrumPhy > >', 'ns3::Ptr< ns3::SpectrumPhy >', container_type='vector') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyRxEndOkCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyRxEndOkCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyRxEndOkCallback&') typehandlers.add_type_alias('std::vector< ns3::BandInfo, std::allocator< ns3::BandInfo > >', 'ns3::Bands') typehandlers.add_type_alias('std::vector< ns3::BandInfo, std::allocator< ns3::BandInfo > >*', 'ns3::Bands*') typehandlers.add_type_alias('std::vector< ns3::BandInfo, std::allocator< ns3::BandInfo > >&', 'ns3::Bands&') typehandlers.add_type_alias('ns3::Vector3DValue', 'ns3::VectorValue') typehandlers.add_type_alias('ns3::Vector3DValue*', 'ns3::VectorValue*') typehandlers.add_type_alias('ns3::Vector3DValue&', 'ns3::VectorValue&') module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyRxStartCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyRxStartCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyRxStartCallback&') typehandlers.add_type_alias('std::map< unsigned int, ns3::RxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::RxSpectrumModelInfo > > >', 'ns3::RxSpectrumModelInfoMap_t') typehandlers.add_type_alias('std::map< unsigned int, ns3::RxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::RxSpectrumModelInfo > > >*', 'ns3::RxSpectrumModelInfoMap_t*') typehandlers.add_type_alias('std::map< unsigned int, ns3::RxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::RxSpectrumModelInfo > > >&', 'ns3::RxSpectrumModelInfoMap_t&') typehandlers.add_type_alias('uint32_t', 'ns3::SpectrumModelUid_t') typehandlers.add_type_alias('uint32_t*', 'ns3::SpectrumModelUid_t*') typehandlers.add_type_alias('uint32_t&', 'ns3::SpectrumModelUid_t&') typehandlers.add_type_alias('ns3::Vector3D', 'ns3::Vector') typehandlers.add_type_alias('ns3::Vector3D*', 'ns3::Vector*') typehandlers.add_type_alias('ns3::Vector3D&', 'ns3::Vector&') module.add_typedef(root_module['ns3::Vector3D'], 'Vector') typehandlers.add_type_alias('std::map< unsigned int, ns3::TxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::TxSpectrumModelInfo > > >', 'ns3::TxSpectrumModelInfoMap_t') typehandlers.add_type_alias('std::map< unsigned int, ns3::TxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::TxSpectrumModelInfo > > >*', 'ns3::TxSpectrumModelInfoMap_t*') typehandlers.add_type_alias('std::map< unsigned int, ns3::TxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::TxSpectrumModelInfo > > >&', 'ns3::TxSpectrumModelInfoMap_t&') typehandlers.add_type_alias('ns3::Vector3DChecker', 'ns3::VectorChecker') typehandlers.add_type_alias('ns3::Vector3DChecker*', 'ns3::VectorChecker*') typehandlers.add_type_alias('ns3::Vector3DChecker&', 'ns3::VectorChecker&') module.add_typedef(root_module['ns3::Vector3DChecker'], 'VectorChecker') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyTxStartCallback') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyTxStartCallback*') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyTxStartCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyRxEndErrorCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyRxEndErrorCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyRxEndErrorCallback&') typehandlers.add_type_alias('std::vector< double, std::allocator< double > >', 'ns3::Values') typehandlers.add_type_alias('std::vector< double, std::allocator< double > >*', 'ns3::Values*') typehandlers.add_type_alias('std::vector< double, std::allocator< double > >&', 'ns3::Values&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyTxEndCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyTxEndCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyTxEndCallback&') typehandlers.add_type_alias('std::map< unsigned int, ns3::SpectrumConverter, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::SpectrumConverter > > >', 'ns3::SpectrumConverterMap_t') typehandlers.add_type_alias('std::map< unsigned int, ns3::SpectrumConverter, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::SpectrumConverter > > >*', 'ns3::SpectrumConverterMap_t*') typehandlers.add_type_alias('std::map< unsigned int, ns3::SpectrumConverter, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::SpectrumConverter > > >&', 'ns3::SpectrumConverterMap_t&') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace addressUtils nested_module = module.add_cpp_namespace('addressUtils') register_types_ns3_addressUtils(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_addressUtils(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AdhocAlohaNoackIdealPhyHelper_methods(root_module, root_module['ns3::AdhocAlohaNoackIdealPhyHelper']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3BandInfo_methods(root_module, root_module['ns3::BandInfo']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac16Address_methods(root_module, root_module['ns3::Mac16Address']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3Mac64Address_methods(root_module, root_module['ns3::Mac64Address']) register_Ns3MicrowaveOvenSpectrumValueHelper_methods(root_module, root_module['ns3::MicrowaveOvenSpectrumValueHelper']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3RxSpectrumModelInfo_methods(root_module, root_module['ns3::RxSpectrumModelInfo']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3SpectrumAnalyzerHelper_methods(root_module, root_module['ns3::SpectrumAnalyzerHelper']) register_Ns3SpectrumChannelHelper_methods(root_module, root_module['ns3::SpectrumChannelHelper']) register_Ns3SpectrumPhyHelper_methods(root_module, root_module['ns3::SpectrumPhyHelper']) register_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TxSpectrumModelInfo_methods(root_module, root_module['ns3::TxSpectrumModelInfo']) 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_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D']) register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D']) register_Ns3WaveformGeneratorHelper_methods(root_module, root_module['ns3::WaveformGeneratorHelper']) register_Ns3WifiSpectrumValue5MhzFactory_methods(root_module, root_module['ns3::WifiSpectrumValue5MhzFactory']) register_Ns3WifiSpectrumValueHelper_methods(root_module, root_module['ns3::WifiSpectrumValueHelper']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PropagationDelayModel_methods(root_module, root_module['ns3::PropagationDelayModel']) register_Ns3PropagationLossModel_methods(root_module, root_module['ns3::PropagationLossModel']) register_Ns3Queue_methods(root_module, root_module['ns3::Queue']) register_Ns3RandomPropagationDelayModel_methods(root_module, root_module['ns3::RandomPropagationDelayModel']) register_Ns3RandomPropagationLossModel_methods(root_module, root_module['ns3::RandomPropagationLossModel']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3RangePropagationLossModel_methods(root_module, root_module['ns3::RangePropagationLossModel']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3SpectrumConverter_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumConverter__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >']) register_Ns3SimpleRefCount__Ns3SpectrumModel_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumModel__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >']) register_Ns3SimpleRefCount__Ns3SpectrumSignalParameters_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumSignalParameters__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >']) register_Ns3SimpleRefCount__Ns3SpectrumValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3SpectrumConverter_methods(root_module, root_module['ns3::SpectrumConverter']) register_Ns3SpectrumErrorModel_methods(root_module, root_module['ns3::SpectrumErrorModel']) register_Ns3SpectrumInterference_methods(root_module, root_module['ns3::SpectrumInterference']) register_Ns3SpectrumModel_methods(root_module, root_module['ns3::SpectrumModel']) register_Ns3SpectrumPhy_methods(root_module, root_module['ns3::SpectrumPhy']) register_Ns3SpectrumPropagationLossModel_methods(root_module, root_module['ns3::SpectrumPropagationLossModel']) register_Ns3SpectrumSignalParameters_methods(root_module, root_module['ns3::SpectrumSignalParameters']) register_Ns3SpectrumValue_methods(root_module, root_module['ns3::SpectrumValue']) register_Ns3ThreeLogDistancePropagationLossModel_methods(root_module, root_module['ns3::ThreeLogDistancePropagationLossModel']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3TwoRayGroundPropagationLossModel_methods(root_module, root_module['ns3::TwoRayGroundPropagationLossModel']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WaveformGenerator_methods(root_module, root_module['ns3::WaveformGenerator']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_Ns3AlohaNoackMacHeader_methods(root_module, root_module['ns3::AlohaNoackMacHeader']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3ConstantSpectrumPropagationLossModel_methods(root_module, root_module['ns3::ConstantSpectrumPropagationLossModel']) register_Ns3ConstantSpeedPropagationDelayModel_methods(root_module, root_module['ns3::ConstantSpeedPropagationDelayModel']) register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker']) register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3FixedRssLossModel_methods(root_module, root_module['ns3::FixedRssLossModel']) register_Ns3FriisPropagationLossModel_methods(root_module, root_module['ns3::FriisPropagationLossModel']) register_Ns3FriisSpectrumPropagationLossModel_methods(root_module, root_module['ns3::FriisSpectrumPropagationLossModel']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3HalfDuplexIdealPhy_methods(root_module, root_module['ns3::HalfDuplexIdealPhy']) register_Ns3HalfDuplexIdealPhySignalParameters_methods(root_module, root_module['ns3::HalfDuplexIdealPhySignalParameters']) 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_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) register_Ns3Mac16AddressChecker_methods(root_module, root_module['ns3::Mac16AddressChecker']) register_Ns3Mac16AddressValue_methods(root_module, root_module['ns3::Mac16AddressValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3Mac64AddressChecker_methods(root_module, root_module['ns3::Mac64AddressChecker']) register_Ns3Mac64AddressValue_methods(root_module, root_module['ns3::Mac64AddressValue']) register_Ns3MatrixPropagationLossModel_methods(root_module, root_module['ns3::MatrixPropagationLossModel']) register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel']) 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_Ns3NonCommunicatingNetDevice_methods(root_module, root_module['ns3::NonCommunicatingNetDevice']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3ShannonSpectrumErrorModel_methods(root_module, root_module['ns3::ShannonSpectrumErrorModel']) register_Ns3SpectrumAnalyzer_methods(root_module, root_module['ns3::SpectrumAnalyzer']) register_Ns3SpectrumChannel_methods(root_module, root_module['ns3::SpectrumChannel']) 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_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker']) register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue']) register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker']) register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3AlohaNoackNetDevice_methods(root_module, root_module['ns3::AlohaNoackNetDevice']) register_Ns3MultiModelSpectrumChannel_methods(root_module, root_module['ns3::MultiModelSpectrumChannel']) register_Ns3SingleModelSpectrumChannel_methods(root_module, root_module['ns3::SingleModelSpectrumChannel']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AdhocAlohaNoackIdealPhyHelper_methods(root_module, cls): ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::AdhocAlohaNoackIdealPhyHelper::AdhocAlohaNoackIdealPhyHelper(ns3::AdhocAlohaNoackIdealPhyHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::AdhocAlohaNoackIdealPhyHelper const &', 'arg0')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::AdhocAlohaNoackIdealPhyHelper::AdhocAlohaNoackIdealPhyHelper() [constructor] cls.add_constructor([]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::AdhocAlohaNoackIdealPhyHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::AdhocAlohaNoackIdealPhyHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::AdhocAlohaNoackIdealPhyHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'nodeName')], is_const=True) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetAntenna(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetAntenna', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetChannel(ns3::Ptr<ns3::SpectrumChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'channel')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetChannel(std::string channelName) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'channelName')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetNoisePowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> noisePsd) [member function] cls.add_method('SetNoisePowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'noisePsd')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetPhyAttribute(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('SetPhyAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetTxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> txPsd) [member function] cls.add_method('SetTxPowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'txPsd')]) 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_Ns3BandInfo_methods(root_module, cls): ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::BandInfo() [constructor] cls.add_constructor([]) ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::BandInfo(ns3::BandInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::BandInfo const &', 'arg0')]) ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::fc [variable] cls.add_instance_attribute('fc', 'double', is_const=False) ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::fh [variable] cls.add_instance_attribute('fh', 'double', is_const=False) ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::fl [variable] cls.add_instance_attribute('fl', 'double', 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_Ns3DataRate_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('>=') ## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRate const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor] cls.add_constructor([param('uint64_t', 'bps')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor] cls.add_constructor([param('std::string', 'rate')]) ## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateTxTime', 'double', [param('uint32_t', 'bytes')], is_const=True) ## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function] cls.add_method('GetBitRate', 'uint64_t', [], is_const=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function] cls.add_method('IsIpv4MappedAddress', 'bool', []) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac16Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(ns3::Mac16Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac16Address const &', 'arg0')]) ## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address() [constructor] cls.add_constructor([]) ## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac16Address', [], is_static=True) ## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac16Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac16-address.h (module 'network'): static bool ns3::Mac16Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3Mac64Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(ns3::Mac64Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac64Address const &', 'arg0')]) ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address() [constructor] cls.add_constructor([]) ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac64Address', [], is_static=True) ## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac64Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac64-address.h (module 'network'): static bool ns3::Mac64Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3MicrowaveOvenSpectrumValueHelper_methods(root_module, cls): ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): ns3::MicrowaveOvenSpectrumValueHelper::MicrowaveOvenSpectrumValueHelper() [constructor] cls.add_constructor([]) ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): ns3::MicrowaveOvenSpectrumValueHelper::MicrowaveOvenSpectrumValueHelper(ns3::MicrowaveOvenSpectrumValueHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::MicrowaveOvenSpectrumValueHelper const &', 'arg0')]) ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::MicrowaveOvenSpectrumValueHelper::CreatePowerSpectralDensityMwo1() [member function] cls.add_method('CreatePowerSpectralDensityMwo1', 'ns3::Ptr< ns3::SpectrumValue >', [], is_static=True) ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::MicrowaveOvenSpectrumValueHelper::CreatePowerSpectralDensityMwo2() [member function] cls.add_method('CreatePowerSpectralDensityMwo2', 'ns3::Ptr< ns3::SpectrumValue >', [], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3RxSpectrumModelInfo_methods(root_module, cls): ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo::RxSpectrumModelInfo(ns3::RxSpectrumModelInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::RxSpectrumModelInfo const &', 'arg0')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo::RxSpectrumModelInfo(ns3::Ptr<ns3::SpectrumModel const> rxSpectrumModel) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::SpectrumModel const >', 'rxSpectrumModel')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo::m_rxPhySet [variable] cls.add_instance_attribute('m_rxPhySet', 'std::set< ns3::Ptr< ns3::SpectrumPhy > >', is_const=False) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo::m_rxSpectrumModel [variable] cls.add_instance_attribute('m_rxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SpectrumAnalyzerHelper_methods(root_module, cls): ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::SpectrumAnalyzerHelper::SpectrumAnalyzerHelper(ns3::SpectrumAnalyzerHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumAnalyzerHelper const &', 'arg0')]) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::SpectrumAnalyzerHelper::SpectrumAnalyzerHelper() [constructor] cls.add_constructor([]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::EnableAsciiAll(std::string prefix) [member function] cls.add_method('EnableAsciiAll', 'void', [param('std::string', 'prefix')]) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::SpectrumAnalyzerHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::SpectrumAnalyzerHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::SpectrumAnalyzerHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'nodeName')], is_const=True) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetAntenna(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetAntenna', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetChannel(ns3::Ptr<ns3::SpectrumChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'channel')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetChannel(std::string channelName) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'channelName')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetPhyAttribute(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('SetPhyAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetRxSpectrumModel(ns3::Ptr<ns3::SpectrumModel> m) [member function] cls.add_method('SetRxSpectrumModel', 'void', [param('ns3::Ptr< ns3::SpectrumModel >', 'm')]) return def register_Ns3SpectrumChannelHelper_methods(root_module, cls): ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumChannelHelper::SpectrumChannelHelper() [constructor] cls.add_constructor([]) ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumChannelHelper::SpectrumChannelHelper(ns3::SpectrumChannelHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumChannelHelper const &', 'arg0')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::AddPropagationLoss(std::string name, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('AddPropagationLoss', 'void', [param('std::string', 'name'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::AddPropagationLoss(ns3::Ptr<ns3::PropagationLossModel> m) [member function] cls.add_method('AddPropagationLoss', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'm')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::AddSpectrumPropagationLoss(std::string name, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('AddSpectrumPropagationLoss', 'void', [param('std::string', 'name'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::AddSpectrumPropagationLoss(ns3::Ptr<ns3::SpectrumPropagationLossModel> m) [member function] cls.add_method('AddSpectrumPropagationLoss', 'void', [param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'm')]) ## spectrum-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumChannel> ns3::SpectrumChannelHelper::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::SpectrumChannel >', [], is_const=True) ## spectrum-helper.h (module 'spectrum'): static ns3::SpectrumChannelHelper ns3::SpectrumChannelHelper::Default() [member function] cls.add_method('Default', 'ns3::SpectrumChannelHelper', [], is_static=True) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::SetChannel(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::SetPropagationDelay(std::string name, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetPropagationDelay', 'void', [param('std::string', 'name'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) return def register_Ns3SpectrumPhyHelper_methods(root_module, cls): ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumPhyHelper::SpectrumPhyHelper() [constructor] cls.add_constructor([]) ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumPhyHelper::SpectrumPhyHelper(ns3::SpectrumPhyHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumPhyHelper const &', 'arg0')]) ## spectrum-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumPhy> ns3::SpectrumPhyHelper::Create(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::NetDevice> device) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::SpectrumPhy >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::NetDevice >', 'device')], is_const=True) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumPhyHelper::SetChannel(ns3::Ptr<ns3::SpectrumChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'channel')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumPhyHelper::SetChannel(std::string channelName) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'channelName')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumPhyHelper::SetPhy(std::string name, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetPhy', 'void', [param('std::string', 'name'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumPhyHelper::SetPhyAttribute(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('SetPhyAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')]) return def register_Ns3SystemWallClockMs_methods(root_module, cls): ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [copy constructor] cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')]) ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor] cls.add_constructor([]) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function] cls.add_method('End', 'int64_t', []) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function] cls.add_method('GetElapsedReal', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function] cls.add_method('GetElapsedSystem', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function] cls.add_method('GetElapsedUser', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function] cls.add_method('Start', 'void', []) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TxSpectrumModelInfo_methods(root_module, cls): ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo::TxSpectrumModelInfo(ns3::TxSpectrumModelInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::TxSpectrumModelInfo const &', 'arg0')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo::TxSpectrumModelInfo(ns3::Ptr<ns3::SpectrumModel const> txSpectrumModel) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::SpectrumModel const >', 'txSpectrumModel')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo::m_spectrumConverterMap [variable] cls.add_instance_attribute('m_spectrumConverterMap', 'ns3::SpectrumConverterMap_t', is_const=False) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo::m_txSpectrumModel [variable] cls.add_instance_attribute('m_txSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', is_const=False) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Vector2D_methods(root_module, cls): cls.add_output_stream_operator() ## vector.h (module 'core'): ns3::Vector2D::Vector2D(ns3::Vector2D const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2D const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2D::Vector2D(double _x, double _y) [constructor] cls.add_constructor([param('double', '_x'), param('double', '_y')]) ## vector.h (module 'core'): ns3::Vector2D::Vector2D() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2D::x [variable] cls.add_instance_attribute('x', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector2D::y [variable] cls.add_instance_attribute('y', 'double', is_const=False) return def register_Ns3Vector3D_methods(root_module, cls): cls.add_output_stream_operator() ## vector.h (module 'core'): ns3::Vector3D::Vector3D(ns3::Vector3D const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3D const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3D::Vector3D(double _x, double _y, double _z) [constructor] cls.add_constructor([param('double', '_x'), param('double', '_y'), param('double', '_z')]) ## vector.h (module 'core'): ns3::Vector3D::Vector3D() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3D::x [variable] cls.add_instance_attribute('x', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector3D::y [variable] cls.add_instance_attribute('y', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector3D::z [variable] cls.add_instance_attribute('z', 'double', is_const=False) return def register_Ns3WaveformGeneratorHelper_methods(root_module, cls): ## waveform-generator-helper.h (module 'spectrum'): ns3::WaveformGeneratorHelper::WaveformGeneratorHelper(ns3::WaveformGeneratorHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::WaveformGeneratorHelper const &', 'arg0')]) ## waveform-generator-helper.h (module 'spectrum'): ns3::WaveformGeneratorHelper::WaveformGeneratorHelper() [constructor] cls.add_constructor([]) ## waveform-generator-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::WaveformGeneratorHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## waveform-generator-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::WaveformGeneratorHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## waveform-generator-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::WaveformGeneratorHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'nodeName')], is_const=True) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetAntenna(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetAntenna', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetChannel(ns3::Ptr<ns3::SpectrumChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'channel')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetChannel(std::string channelName) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'channelName')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetPhyAttribute(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('SetPhyAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetTxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> txPsd) [member function] cls.add_method('SetTxPowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'txPsd')]) return def register_Ns3WifiSpectrumValue5MhzFactory_methods(root_module, cls): ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValue5MhzFactory::WifiSpectrumValue5MhzFactory() [constructor] cls.add_constructor([]) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValue5MhzFactory::WifiSpectrumValue5MhzFactory(ns3::WifiSpectrumValue5MhzFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiSpectrumValue5MhzFactory const &', 'arg0')]) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValue5MhzFactory::CreateConstant(double psd) [member function] cls.add_method('CreateConstant', 'ns3::Ptr< ns3::SpectrumValue >', [param('double', 'psd')], is_virtual=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValue5MhzFactory::CreateRfFilter(uint32_t channel) [member function] cls.add_method('CreateRfFilter', 'ns3::Ptr< ns3::SpectrumValue >', [param('uint32_t', 'channel')], is_virtual=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValue5MhzFactory::CreateTxPowerSpectralDensity(double txPower, uint32_t channel) [member function] cls.add_method('CreateTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('double', 'txPower'), param('uint32_t', 'channel')], is_virtual=True) return def register_Ns3WifiSpectrumValueHelper_methods(root_module, cls): ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValueHelper::WifiSpectrumValueHelper() [constructor] cls.add_constructor([]) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValueHelper::WifiSpectrumValueHelper(ns3::WifiSpectrumValueHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiSpectrumValueHelper const &', 'arg0')]) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateConstant(double psd) [member function] cls.add_method('CreateConstant', 'ns3::Ptr< ns3::SpectrumValue >', [param('double', 'psd')], is_pure_virtual=True, is_virtual=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateRfFilter(uint32_t channel) [member function] cls.add_method('CreateRfFilter', 'ns3::Ptr< ns3::SpectrumValue >', [param('uint32_t', 'channel')], is_pure_virtual=True, is_virtual=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateTxPowerSpectralDensity(double txPower, uint32_t channel) [member function] cls.add_method('CreateTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('double', 'txPower'), param('uint32_t', 'channel')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('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_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_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_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3PropagationDelayModel_methods(root_module, cls): ## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel::PropagationDelayModel() [constructor] cls.add_constructor([]) ## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel::PropagationDelayModel(ns3::PropagationDelayModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::PropagationDelayModel const &', 'arg0')]) ## propagation-delay-model.h (module 'propagation'): int64_t ns3::PropagationDelayModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::PropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('GetDelay', 'ns3::Time', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_pure_virtual=True, is_const=True, is_virtual=True) ## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::PropagationDelayModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-delay-model.h (module 'propagation'): int64_t ns3::PropagationDelayModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, visibility='private', is_virtual=True) 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'): ns3::Ptr<ns3::PropagationLossModel> ns3::PropagationLossModel::GetNext() [member function] cls.add_method('GetNext', 'ns3::Ptr< ns3::PropagationLossModel >', []) ## 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'): int64_t ns3::PropagationLossModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## 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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::PropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Queue_methods(root_module, cls): ## queue.h (module 'network'): ns3::Queue::Queue(ns3::Queue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Queue const &', 'arg0')]) ## queue.h (module 'network'): ns3::Queue::Queue() [constructor] cls.add_constructor([]) ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', []) ## queue.h (module 'network'): void ns3::Queue::DequeueAll() [member function] cls.add_method('DequeueAll', 'void', []) ## queue.h (module 'network'): bool ns3::Queue::Enqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## queue.h (module 'network'): uint32_t ns3::Queue::GetNBytes() const [member function] cls.add_method('GetNBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedBytes() const [member function] cls.add_method('GetTotalDroppedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedPackets() const [member function] cls.add_method('GetTotalDroppedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedBytes() const [member function] cls.add_method('GetTotalReceivedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedPackets() const [member function] cls.add_method('GetTotalReceivedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): static ns3::TypeId ns3::Queue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue.h (module 'network'): bool ns3::Queue::IsEmpty() const [member function] cls.add_method('IsEmpty', 'bool', [], is_const=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::Queue::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet const >', [], is_const=True) ## queue.h (module 'network'): void ns3::Queue::ResetStatistics() [member function] cls.add_method('ResetStatistics', 'void', []) ## queue.h (module 'network'): void ns3::Queue::Drop(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('Drop', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue::DoDequeue() [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::Packet >', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h (module 'network'): bool ns3::Queue::DoEnqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::Queue::DoPeek() const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::Packet const >', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3RandomPropagationDelayModel_methods(root_module, cls): ## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel::RandomPropagationDelayModel(ns3::RandomPropagationDelayModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomPropagationDelayModel const &', 'arg0')]) ## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel::RandomPropagationDelayModel() [constructor] cls.add_constructor([]) ## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::RandomPropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('GetDelay', 'ns3::Time', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, is_virtual=True) ## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::RandomPropagationDelayModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-delay-model.h (module 'propagation'): int64_t ns3::RandomPropagationDelayModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', 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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::RandomPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3RandomVariableStream_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function] cls.add_method('SetStream', 'void', [param('int64_t', 'stream')]) ## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function] cls.add_method('GetStream', 'int64_t', [], is_const=True) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function] cls.add_method('SetAntithetic', 'void', [param('bool', 'isAntithetic')]) ## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function] cls.add_method('IsAntithetic', 'bool', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function] cls.add_method('Peek', 'ns3::RngStream *', [], is_const=True, visibility='protected') return def register_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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::RangePropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3SequentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function] cls.add_method('GetIncrement', 'ns3::Ptr< ns3::RandomVariableStream >', [], is_const=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function] cls.add_method('GetConsecutive', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__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__Ns3SpectrumConverter_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumConverter__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter< ns3::SpectrumConverter > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3SpectrumModel_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumModel__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter< ns3::SpectrumModel > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3SpectrumSignalParameters_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumSignalParameters__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter< ns3::SpectrumSignalParameters > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3SpectrumValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter< ns3::SpectrumValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >::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_Ns3SpectrumConverter_methods(root_module, cls): ## spectrum-converter.h (module 'spectrum'): ns3::SpectrumConverter::SpectrumConverter(ns3::SpectrumConverter const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumConverter const &', 'arg0')]) ## spectrum-converter.h (module 'spectrum'): ns3::SpectrumConverter::SpectrumConverter(ns3::Ptr<ns3::SpectrumModel const> fromSpectrumModel, ns3::Ptr<ns3::SpectrumModel const> toSpectrumModel) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::SpectrumModel const >', 'fromSpectrumModel'), param('ns3::Ptr< ns3::SpectrumModel const >', 'toSpectrumModel')]) ## spectrum-converter.h (module 'spectrum'): ns3::SpectrumConverter::SpectrumConverter() [constructor] cls.add_constructor([]) ## spectrum-converter.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumConverter::Convert(ns3::Ptr<ns3::SpectrumValue const> vvf) const [member function] cls.add_method('Convert', 'ns3::Ptr< ns3::SpectrumValue >', [param('ns3::Ptr< ns3::SpectrumValue const >', 'vvf')], is_const=True) return def register_Ns3SpectrumErrorModel_methods(root_module, cls): ## spectrum-error-model.h (module 'spectrum'): ns3::SpectrumErrorModel::SpectrumErrorModel() [constructor] cls.add_constructor([]) ## spectrum-error-model.h (module 'spectrum'): ns3::SpectrumErrorModel::SpectrumErrorModel(ns3::SpectrumErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumErrorModel const &', 'arg0')]) ## spectrum-error-model.h (module 'spectrum'): void ns3::SpectrumErrorModel::EvaluateChunk(ns3::SpectrumValue const & sinr, ns3::Time duration) [member function] cls.add_method('EvaluateChunk', 'void', [param('ns3::SpectrumValue const &', 'sinr'), param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): bool ns3::SpectrumErrorModel::IsRxCorrect() [member function] cls.add_method('IsRxCorrect', 'bool', [], is_pure_virtual=True, is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): void ns3::SpectrumErrorModel::StartRx(ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')], is_pure_virtual=True, is_virtual=True) return def register_Ns3SpectrumInterference_methods(root_module, cls): ## spectrum-interference.h (module 'spectrum'): ns3::SpectrumInterference::SpectrumInterference(ns3::SpectrumInterference const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumInterference const &', 'arg0')]) ## spectrum-interference.h (module 'spectrum'): ns3::SpectrumInterference::SpectrumInterference() [constructor] cls.add_constructor([]) ## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::AbortRx() [member function] cls.add_method('AbortRx', 'void', []) ## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::AddSignal(ns3::Ptr<ns3::SpectrumValue const> spd, ns3::Time const duration) [member function] cls.add_method('AddSignal', 'void', [param('ns3::Ptr< ns3::SpectrumValue const >', 'spd'), param('ns3::Time const', 'duration')]) ## spectrum-interference.h (module 'spectrum'): bool ns3::SpectrumInterference::EndRx() [member function] cls.add_method('EndRx', 'bool', []) ## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::SetErrorModel(ns3::Ptr<ns3::SpectrumErrorModel> e) [member function] cls.add_method('SetErrorModel', 'void', [param('ns3::Ptr< ns3::SpectrumErrorModel >', 'e')]) ## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::SetNoisePowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> noisePsd) [member function] cls.add_method('SetNoisePowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue const >', 'noisePsd')]) ## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::StartRx(ns3::Ptr<const ns3::Packet> p, ns3::Ptr<ns3::SpectrumValue const> rxPsd) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ptr< ns3::SpectrumValue const >', 'rxPsd')]) ## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3SpectrumModel_methods(root_module, cls): cls.add_binary_comparison_operator('==') ## spectrum-model.h (module 'spectrum'): ns3::SpectrumModel::SpectrumModel(ns3::SpectrumModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumModel const &', 'arg0')]) ## spectrum-model.h (module 'spectrum'): ns3::SpectrumModel::SpectrumModel(std::vector<double, std::allocator<double> > centerFreqs) [constructor] cls.add_constructor([param('std::vector< double >', 'centerFreqs')]) ## spectrum-model.h (module 'spectrum'): ns3::SpectrumModel::SpectrumModel(ns3::Bands bands) [constructor] cls.add_constructor([param('ns3::Bands', 'bands')]) ## spectrum-model.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const ns3::BandInfo*,std::vector<ns3::BandInfo, std::allocator<ns3::BandInfo> > > ns3::SpectrumModel::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::BandInfo const *, std::vector< ns3::BandInfo > >', [], is_const=True) ## spectrum-model.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const ns3::BandInfo*,std::vector<ns3::BandInfo, std::allocator<ns3::BandInfo> > > ns3::SpectrumModel::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::BandInfo const *, std::vector< ns3::BandInfo > >', [], is_const=True) ## spectrum-model.h (module 'spectrum'): size_t ns3::SpectrumModel::GetNumBands() const [member function] cls.add_method('GetNumBands', 'size_t', [], is_const=True) ## spectrum-model.h (module 'spectrum'): ns3::SpectrumModelUid_t ns3::SpectrumModel::GetUid() const [member function] cls.add_method('GetUid', 'ns3::SpectrumModelUid_t', [], is_const=True) return def register_Ns3SpectrumPhy_methods(root_module, cls): ## spectrum-phy.h (module 'spectrum'): ns3::SpectrumPhy::SpectrumPhy() [constructor] cls.add_constructor([]) ## spectrum-phy.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'd')], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::SpectrumPhy::GetDevice() [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'm')], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::SpectrumPhy::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::MobilityModel >', [], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::SpectrumPhy::GetRxSpectrumModel() const [member function] cls.add_method('GetRxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::SpectrumPhy::GetRxAntenna() [member function] cls.add_method('GetRxAntenna', 'ns3::Ptr< ns3::AntennaModel >', [], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_pure_virtual=True, is_virtual=True) return def register_Ns3SpectrumPropagationLossModel_methods(root_module, cls): ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::SpectrumPropagationLossModel::SpectrumPropagationLossModel(ns3::SpectrumPropagationLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumPropagationLossModel const &', 'arg0')]) ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::SpectrumPropagationLossModel::SpectrumPropagationLossModel() [constructor] cls.add_constructor([]) ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumPropagationLossModel::CalcRxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> txPsd, ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function] cls.add_method('CalcRxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('ns3::Ptr< ns3::SpectrumValue const >', 'txPsd'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')], is_const=True) ## spectrum-propagation-loss-model.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## spectrum-propagation-loss-model.h (module 'spectrum'): void ns3::SpectrumPropagationLossModel::SetNext(ns3::Ptr<ns3::SpectrumPropagationLossModel> next) [member function] cls.add_method('SetNext', 'void', [param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'next')]) ## spectrum-propagation-loss-model.h (module 'spectrum'): void ns3::SpectrumPropagationLossModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumPropagationLossModel::DoCalcRxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> txPsd, ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('ns3::Ptr< ns3::SpectrumValue const >', 'txPsd'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3SpectrumSignalParameters_methods(root_module, cls): ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::SpectrumSignalParameters() [constructor] cls.add_constructor([]) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::SpectrumSignalParameters(ns3::SpectrumSignalParameters const & p) [copy constructor] cls.add_constructor([param('ns3::SpectrumSignalParameters const &', 'p')]) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumSignalParameters> ns3::SpectrumSignalParameters::Copy() [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::SpectrumSignalParameters >', [], is_virtual=True) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::duration [variable] cls.add_instance_attribute('duration', 'ns3::Time', is_const=False) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::psd [variable] cls.add_instance_attribute('psd', 'ns3::Ptr< ns3::SpectrumValue >', is_const=False) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::txAntenna [variable] cls.add_instance_attribute('txAntenna', 'ns3::Ptr< ns3::AntennaModel >', is_const=False) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::txPhy [variable] cls.add_instance_attribute('txPhy', 'ns3::Ptr< ns3::SpectrumPhy >', is_const=False) return def register_Ns3SpectrumValue_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', 'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('-', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', 'right')) cls.add_output_stream_operator() cls.add_inplace_numeric_operator('*=', param('ns3::SpectrumValue const &', 'right')) cls.add_inplace_numeric_operator('*=', param('double', 'right')) cls.add_inplace_numeric_operator('+=', param('ns3::SpectrumValue const &', 'right')) cls.add_inplace_numeric_operator('+=', param('double', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::SpectrumValue const &', 'right')) cls.add_inplace_numeric_operator('-=', param('double', 'right')) cls.add_inplace_numeric_operator('/=', param('ns3::SpectrumValue const &', 'right')) cls.add_inplace_numeric_operator('/=', param('double', 'right')) ## spectrum-value.h (module 'spectrum'): ns3::SpectrumValue::SpectrumValue(ns3::SpectrumValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumValue const &', 'arg0')]) ## spectrum-value.h (module 'spectrum'): ns3::SpectrumValue::SpectrumValue(ns3::Ptr<ns3::SpectrumModel const> sm) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::SpectrumModel const >', 'sm')]) ## spectrum-value.h (module 'spectrum'): ns3::SpectrumValue::SpectrumValue() [constructor] cls.add_constructor([]) ## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const ns3::BandInfo*,std::vector<ns3::BandInfo, std::allocator<ns3::BandInfo> > > ns3::SpectrumValue::ConstBandsBegin() const [member function] cls.add_method('ConstBandsBegin', '__gnu_cxx::__normal_iterator< ns3::BandInfo const *, std::vector< ns3::BandInfo > >', [], is_const=True) ## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const ns3::BandInfo*,std::vector<ns3::BandInfo, std::allocator<ns3::BandInfo> > > ns3::SpectrumValue::ConstBandsEnd() const [member function] cls.add_method('ConstBandsEnd', '__gnu_cxx::__normal_iterator< ns3::BandInfo const *, std::vector< ns3::BandInfo > >', [], is_const=True) ## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const double*,std::vector<double, std::allocator<double> > > ns3::SpectrumValue::ConstValuesBegin() const [member function] cls.add_method('ConstValuesBegin', '__gnu_cxx::__normal_iterator< double const *, std::vector< double > >', [], is_const=True) ## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const double*,std::vector<double, std::allocator<double> > > ns3::SpectrumValue::ConstValuesEnd() const [member function] cls.add_method('ConstValuesEnd', '__gnu_cxx::__normal_iterator< double const *, std::vector< double > >', [], is_const=True) ## spectrum-value.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::SpectrumValue >', [], is_const=True) ## spectrum-value.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::SpectrumValue::GetSpectrumModel() const [member function] cls.add_method('GetSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_const=True) ## spectrum-value.h (module 'spectrum'): ns3::SpectrumModelUid_t ns3::SpectrumValue::GetSpectrumModelUid() const [member function] cls.add_method('GetSpectrumModelUid', 'ns3::SpectrumModelUid_t', [], is_const=True) ## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<double*,std::vector<double, std::allocator<double> > > ns3::SpectrumValue::ValuesBegin() [member function] cls.add_method('ValuesBegin', '__gnu_cxx::__normal_iterator< double *, std::vector< double > >', []) ## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<double*,std::vector<double, std::allocator<double> > > ns3::SpectrumValue::ValuesEnd() [member function] cls.add_method('ValuesEnd', '__gnu_cxx::__normal_iterator< double *, std::vector< double > >', []) 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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::ThreeLogDistancePropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3Time_methods(root_module, cls): 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_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) 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 ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TriangularRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_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::SetFrequency(double frequency) [member function] cls.add_method('SetFrequency', 'void', [param('double', 'frequency')]) ## 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::GetFrequency() const [member function] cls.add_method('GetFrequency', '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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::TwoRayGroundPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WaveformGenerator_methods(root_module, cls): ## waveform-generator.h (module 'spectrum'): ns3::WaveformGenerator::WaveformGenerator() [constructor] cls.add_constructor([]) ## waveform-generator.h (module 'spectrum'): static ns3::TypeId ns3::WaveformGenerator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'm')], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'd')], is_virtual=True) ## waveform-generator.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::WaveformGenerator::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::MobilityModel >', [], is_virtual=True) ## waveform-generator.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::WaveformGenerator::GetDevice() [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_virtual=True) ## waveform-generator.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::WaveformGenerator::GetRxSpectrumModel() const [member function] cls.add_method('GetRxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_const=True, is_virtual=True) ## waveform-generator.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::WaveformGenerator::GetRxAntenna() [member function] cls.add_method('GetRxAntenna', 'ns3::Ptr< ns3::AntennaModel >', [], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetTxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> txs) [member function] cls.add_method('SetTxPowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'txs')]) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetPeriod(ns3::Time period) [member function] cls.add_method('SetPeriod', 'void', [param('ns3::Time', 'period')]) ## waveform-generator.h (module 'spectrum'): ns3::Time ns3::WaveformGenerator::GetPeriod() const [member function] cls.add_method('GetPeriod', 'ns3::Time', [], is_const=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetDutyCycle(double value) [member function] cls.add_method('SetDutyCycle', 'void', [param('double', 'value')]) ## waveform-generator.h (module 'spectrum'): double ns3::WaveformGenerator::GetDutyCycle() const [member function] cls.add_method('GetDutyCycle', 'double', [], is_const=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetAntenna(ns3::Ptr<ns3::AntennaModel> a) [member function] cls.add_method('SetAntenna', 'void', [param('ns3::Ptr< ns3::AntennaModel >', 'a')]) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::GenerateWaveform() [member function] cls.add_method('GenerateWaveform', 'void', [], visibility='private', is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3AlohaNoackMacHeader_methods(root_module, cls): ## aloha-noack-mac-header.h (module 'spectrum'): ns3::AlohaNoackMacHeader::AlohaNoackMacHeader() [constructor] cls.add_constructor([]) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::AlohaNoackMacHeader::AlohaNoackMacHeader(ns3::AlohaNoackMacHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::AlohaNoackMacHeader const &', 'arg0')]) ## aloha-noack-mac-header.h (module 'spectrum'): uint32_t ns3::AlohaNoackMacHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::Mac48Address ns3::AlohaNoackMacHeader::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Mac48Address', [], is_const=True) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::TypeId ns3::AlohaNoackMacHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): uint32_t ns3::AlohaNoackMacHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::Mac48Address ns3::AlohaNoackMacHeader::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Mac48Address', [], is_const=True) ## aloha-noack-mac-header.h (module 'spectrum'): static ns3::TypeId ns3::AlohaNoackMacHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aloha-noack-mac-header.h (module 'spectrum'): void ns3::AlohaNoackMacHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): void ns3::AlohaNoackMacHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): void ns3::AlohaNoackMacHeader::SetDestination(ns3::Mac48Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Mac48Address', 'destination')]) ## aloha-noack-mac-header.h (module 'spectrum'): void ns3::AlohaNoackMacHeader::SetSource(ns3::Mac48Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Mac48Address', 'source')]) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3ConstantRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function] cls.add_method('GetConstant', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function] cls.add_method('GetValue', 'double', [param('double', 'constant')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'constant')]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ConstantSpectrumPropagationLossModel_methods(root_module, cls): ## constant-spectrum-propagation-loss.h (module 'spectrum'): ns3::ConstantSpectrumPropagationLossModel::ConstantSpectrumPropagationLossModel(ns3::ConstantSpectrumPropagationLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantSpectrumPropagationLossModel const &', 'arg0')]) ## constant-spectrum-propagation-loss.h (module 'spectrum'): ns3::ConstantSpectrumPropagationLossModel::ConstantSpectrumPropagationLossModel() [constructor] cls.add_constructor([]) ## constant-spectrum-propagation-loss.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::ConstantSpectrumPropagationLossModel::DoCalcRxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> txPsd, ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('ns3::Ptr< ns3::SpectrumValue const >', 'txPsd'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')], is_const=True, is_virtual=True) ## constant-spectrum-propagation-loss.h (module 'spectrum'): double ns3::ConstantSpectrumPropagationLossModel::GetLossDb() const [member function] cls.add_method('GetLossDb', 'double', [], is_const=True) ## constant-spectrum-propagation-loss.h (module 'spectrum'): static ns3::TypeId ns3::ConstantSpectrumPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## constant-spectrum-propagation-loss.h (module 'spectrum'): void ns3::ConstantSpectrumPropagationLossModel::SetLossDb(double lossDb) [member function] cls.add_method('SetLossDb', 'void', [param('double', 'lossDb')]) return def register_Ns3ConstantSpeedPropagationDelayModel_methods(root_module, cls): ## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel::ConstantSpeedPropagationDelayModel(ns3::ConstantSpeedPropagationDelayModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantSpeedPropagationDelayModel const &', 'arg0')]) ## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel::ConstantSpeedPropagationDelayModel() [constructor] cls.add_constructor([]) ## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::ConstantSpeedPropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('GetDelay', 'ns3::Time', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, is_virtual=True) ## propagation-delay-model.h (module 'propagation'): double ns3::ConstantSpeedPropagationDelayModel::GetSpeed() const [member function] cls.add_method('GetSpeed', 'double', [], is_const=True) ## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::ConstantSpeedPropagationDelayModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-delay-model.h (module 'propagation'): void ns3::ConstantSpeedPropagationDelayModel::SetSpeed(double speed) [member function] cls.add_method('SetSpeed', 'void', [param('double', 'speed')]) ## propagation-delay-model.h (module 'propagation'): int64_t ns3::ConstantSpeedPropagationDelayModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3DataRateChecker_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')]) return def register_Ns3DataRateValue_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor] cls.add_constructor([param('ns3::DataRate const &', 'value')]) ## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): bool ns3::DataRateValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function] cls.add_method('Get', 'ns3::DataRate', [], is_const=True) ## data-rate.h (module 'network'): std::string ns3::DataRateValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function] cls.add_method('Set', 'void', [param('ns3::DataRate const &', 'value')]) return def register_Ns3DeterministicRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function] cls.add_method('SetValueArray', 'void', [param('double *', 'values'), param('uint64_t', 'length')]) ## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3EmpiricalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function] cls.add_method('CDF', 'void', [param('double', 'v'), param('double', 'c')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double arg0, double arg1, double arg2, double arg3, double arg4) [member function] cls.add_method('Interpolate', 'double', [param('double', 'arg0'), param('double', 'arg1'), param('double', 'arg2'), param('double', 'arg3'), param('double', 'arg4')], visibility='private', is_virtual=True) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function] cls.add_method('Validate', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3ErlangRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function] cls.add_method('GetK', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function] cls.add_method('GetLambda', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'k'), param('double', 'lambda')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'k'), param('uint32_t', 'lambda')]) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3ExponentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::FixedRssLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) 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::SetFrequency(double frequency) [member function] cls.add_method('SetFrequency', 'void', [param('double', 'frequency')]) ## 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::GetFrequency() const [member function] cls.add_method('GetFrequency', '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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::FriisPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3FriisSpectrumPropagationLossModel_methods(root_module, cls): ## friis-spectrum-propagation-loss.h (module 'spectrum'): ns3::FriisSpectrumPropagationLossModel::FriisSpectrumPropagationLossModel(ns3::FriisSpectrumPropagationLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::FriisSpectrumPropagationLossModel const &', 'arg0')]) ## friis-spectrum-propagation-loss.h (module 'spectrum'): ns3::FriisSpectrumPropagationLossModel::FriisSpectrumPropagationLossModel() [constructor] cls.add_constructor([]) ## friis-spectrum-propagation-loss.h (module 'spectrum'): double ns3::FriisSpectrumPropagationLossModel::CalculateLoss(double f, double d) const [member function] cls.add_method('CalculateLoss', 'double', [param('double', 'f'), param('double', 'd')], is_const=True) ## friis-spectrum-propagation-loss.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::FriisSpectrumPropagationLossModel::DoCalcRxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> txPsd, ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('ns3::Ptr< ns3::SpectrumValue const >', 'txPsd'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')], is_const=True, is_virtual=True) ## friis-spectrum-propagation-loss.h (module 'spectrum'): static ns3::TypeId ns3::FriisSpectrumPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3GammaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function] cls.add_method('GetBeta', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha'), param('double', 'beta')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha'), param('uint32_t', 'beta')]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3HalfDuplexIdealPhy_methods(root_module, cls): ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::HalfDuplexIdealPhy::HalfDuplexIdealPhy() [constructor] cls.add_constructor([]) ## half-duplex-ideal-phy.h (module 'spectrum'): static ns3::TypeId ns3::HalfDuplexIdealPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'm')], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'd')], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::HalfDuplexIdealPhy::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::MobilityModel >', [], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::HalfDuplexIdealPhy::GetDevice() [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::HalfDuplexIdealPhy::GetRxSpectrumModel() const [member function] cls.add_method('GetRxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_const=True, is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::HalfDuplexIdealPhy::GetRxAntenna() [member function] cls.add_method('GetRxAntenna', 'ns3::Ptr< ns3::AntennaModel >', [], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetTxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> txPsd) [member function] cls.add_method('SetTxPowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'txPsd')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetNoisePowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> noisePsd) [member function] cls.add_method('SetNoisePowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue const >', 'noisePsd')]) ## half-duplex-ideal-phy.h (module 'spectrum'): bool ns3::HalfDuplexIdealPhy::StartTx(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('StartTx', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetRate(ns3::DataRate rate) [member function] cls.add_method('SetRate', 'void', [param('ns3::DataRate', 'rate')]) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::DataRate ns3::HalfDuplexIdealPhy::GetRate() const [member function] cls.add_method('GetRate', 'ns3::DataRate', [], is_const=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetGenericPhyTxEndCallback(ns3::GenericPhyTxEndCallback c) [member function] cls.add_method('SetGenericPhyTxEndCallback', 'void', [param('ns3::GenericPhyTxEndCallback', 'c')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetGenericPhyRxStartCallback(ns3::GenericPhyRxStartCallback c) [member function] cls.add_method('SetGenericPhyRxStartCallback', 'void', [param('ns3::GenericPhyRxStartCallback', 'c')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetGenericPhyRxEndErrorCallback(ns3::GenericPhyRxEndErrorCallback c) [member function] cls.add_method('SetGenericPhyRxEndErrorCallback', 'void', [param('ns3::GenericPhyRxEndErrorCallback', 'c')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetGenericPhyRxEndOkCallback(ns3::GenericPhyRxEndOkCallback c) [member function] cls.add_method('SetGenericPhyRxEndOkCallback', 'void', [param('ns3::GenericPhyRxEndOkCallback', 'c')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetAntenna(ns3::Ptr<ns3::AntennaModel> a) [member function] cls.add_method('SetAntenna', 'void', [param('ns3::Ptr< ns3::AntennaModel >', 'a')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3HalfDuplexIdealPhySignalParameters_methods(root_module, cls): ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::HalfDuplexIdealPhySignalParameters::HalfDuplexIdealPhySignalParameters() [constructor] cls.add_constructor([]) ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::HalfDuplexIdealPhySignalParameters::HalfDuplexIdealPhySignalParameters(ns3::HalfDuplexIdealPhySignalParameters const & p) [copy constructor] cls.add_constructor([param('ns3::HalfDuplexIdealPhySignalParameters const &', 'p')]) ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumSignalParameters> ns3::HalfDuplexIdealPhySignalParameters::Copy() [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::SpectrumSignalParameters >', [], is_virtual=True) ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::HalfDuplexIdealPhySignalParameters::data [variable] cls.add_instance_attribute('data', 'ns3::Ptr< ns3::Packet >', is_const=False) 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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::LogDistancePropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3LogNormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function] cls.add_method('GetMu', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function] cls.add_method('GetSigma', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function] cls.add_method('GetValue', 'double', [param('double', 'mu'), param('double', 'sigma')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mu'), param('uint32_t', 'sigma')]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3Mac16AddressChecker_methods(root_module, cls): ## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker() [constructor] cls.add_constructor([]) ## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker(ns3::Mac16AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac16AddressChecker const &', 'arg0')]) return def register_Ns3Mac16AddressValue_methods(root_module, cls): ## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue() [constructor] cls.add_constructor([]) ## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac16AddressValue const &', 'arg0')]) ## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16Address const & value) [constructor] cls.add_constructor([param('ns3::Mac16Address const &', 'value')]) ## mac16-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac16AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac16-address.h (module 'network'): bool ns3::Mac16AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac16-address.h (module 'network'): ns3::Mac16Address ns3::Mac16AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac16Address', [], is_const=True) ## mac16-address.h (module 'network'): std::string ns3::Mac16AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac16-address.h (module 'network'): void ns3::Mac16AddressValue::Set(ns3::Mac16Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac16Address const &', 'value')]) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3Mac64AddressChecker_methods(root_module, cls): ## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker() [constructor] cls.add_constructor([]) ## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker(ns3::Mac64AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac64AddressChecker const &', 'arg0')]) return def register_Ns3Mac64AddressValue_methods(root_module, cls): ## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue() [constructor] cls.add_constructor([]) ## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac64AddressValue const &', 'arg0')]) ## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64Address const & value) [constructor] cls.add_constructor([param('ns3::Mac64Address const &', 'value')]) ## mac64-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac64AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac64-address.h (module 'network'): bool ns3::Mac64AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac64-address.h (module 'network'): ns3::Mac64Address ns3::Mac64AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac64Address', [], is_const=True) ## mac64-address.h (module 'network'): std::string ns3::Mac64AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac64-address.h (module 'network'): void ns3::Mac64AddressValue::Set(ns3::Mac64Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac64Address const &', 'value')]) return def register_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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::MatrixPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3MobilityModel_methods(root_module, cls): ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel(ns3::MobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::MobilityModel const &', 'arg0')]) ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel() [constructor] cls.add_constructor([]) ## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr<const ns3::MobilityModel> position) const [member function] cls.add_method('GetDistanceFrom', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'position')], is_const=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetPosition() const [member function] cls.add_method('GetPosition', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetRelativeSpeed(ns3::Ptr<const ns3::MobilityModel> other) const [member function] cls.add_method('GetRelativeSpeed', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'other')], is_const=True) ## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function] cls.add_method('GetVelocity', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function] cls.add_method('SetPosition', 'void', [param('ns3::Vector const &', 'position')]) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function] cls.add_method('NotifyCourseChange', 'void', [], is_const=True, visibility='protected') ## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::DoAssignStreams(int64_t start) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'start')], visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], is_pure_virtual=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) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::NakagamiPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], 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::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NonCommunicatingNetDevice_methods(root_module, cls): ## non-communicating-net-device.h (module 'spectrum'): ns3::NonCommunicatingNetDevice::NonCommunicatingNetDevice(ns3::NonCommunicatingNetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NonCommunicatingNetDevice const &', 'arg0')]) ## non-communicating-net-device.h (module 'spectrum'): ns3::NonCommunicatingNetDevice::NonCommunicatingNetDevice() [constructor] cls.add_constructor([]) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): ns3::Address ns3::NonCommunicatingNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Address ns3::NonCommunicatingNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Channel> ns3::NonCommunicatingNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): uint32_t ns3::NonCommunicatingNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): uint16_t ns3::NonCommunicatingNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Address ns3::NonCommunicatingNetDevice::GetMulticast(ns3::Ipv4Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Address ns3::NonCommunicatingNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Node> ns3::NonCommunicatingNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Object> ns3::NonCommunicatingNetDevice::GetPhy() const [member function] cls.add_method('GetPhy', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## non-communicating-net-device.h (module 'spectrum'): static ns3::TypeId ns3::NonCommunicatingNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetChannel(ns3::Ptr<ns3::Channel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::Channel >', 'c')]) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetPhy(ns3::Ptr<ns3::Object> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::Object >', 'phy')]) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3NormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable] cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function] cls.add_method('GetVariance', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) return def register_Ns3ParetoRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ShannonSpectrumErrorModel_methods(root_module, cls): ## spectrum-error-model.h (module 'spectrum'): ns3::ShannonSpectrumErrorModel::ShannonSpectrumErrorModel() [constructor] cls.add_constructor([]) ## spectrum-error-model.h (module 'spectrum'): ns3::ShannonSpectrumErrorModel::ShannonSpectrumErrorModel(ns3::ShannonSpectrumErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ShannonSpectrumErrorModel const &', 'arg0')]) ## spectrum-error-model.h (module 'spectrum'): void ns3::ShannonSpectrumErrorModel::EvaluateChunk(ns3::SpectrumValue const & sinr, ns3::Time duration) [member function] cls.add_method('EvaluateChunk', 'void', [param('ns3::SpectrumValue const &', 'sinr'), param('ns3::Time', 'duration')], is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): bool ns3::ShannonSpectrumErrorModel::IsRxCorrect() [member function] cls.add_method('IsRxCorrect', 'bool', [], is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): void ns3::ShannonSpectrumErrorModel::StartRx(ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')], is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): void ns3::ShannonSpectrumErrorModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3SpectrumAnalyzer_methods(root_module, cls): ## spectrum-analyzer.h (module 'spectrum'): ns3::SpectrumAnalyzer::SpectrumAnalyzer() [constructor] cls.add_constructor([]) ## spectrum-analyzer.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumAnalyzer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'm')], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'd')], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::SpectrumAnalyzer::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::MobilityModel >', [], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::SpectrumAnalyzer::GetDevice() [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::SpectrumAnalyzer::GetRxSpectrumModel() const [member function] cls.add_method('GetRxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_const=True, is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::SpectrumAnalyzer::GetRxAntenna() [member function] cls.add_method('GetRxAntenna', 'ns3::Ptr< ns3::AntennaModel >', [], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetRxSpectrumModel(ns3::Ptr<ns3::SpectrumModel> m) [member function] cls.add_method('SetRxSpectrumModel', 'void', [param('ns3::Ptr< ns3::SpectrumModel >', 'm')]) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetAntenna(ns3::Ptr<ns3::AntennaModel> a) [member function] cls.add_method('SetAntenna', 'void', [param('ns3::Ptr< ns3::AntennaModel >', 'a')]) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::GenerateReport() [member function] cls.add_method('GenerateReport', 'void', [], visibility='private', is_virtual=True) return def register_Ns3SpectrumChannel_methods(root_module, cls): ## spectrum-channel.h (module 'spectrum'): ns3::SpectrumChannel::SpectrumChannel() [constructor] cls.add_constructor([]) ## spectrum-channel.h (module 'spectrum'): ns3::SpectrumChannel::SpectrumChannel(ns3::SpectrumChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumChannel const &', 'arg0')]) ## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::AddPropagationLossModel(ns3::Ptr<ns3::PropagationLossModel> loss) [member function] cls.add_method('AddPropagationLossModel', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'loss')], is_pure_virtual=True, is_virtual=True) ## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::AddRx(ns3::Ptr<ns3::SpectrumPhy> phy) [member function] cls.add_method('AddRx', 'void', [param('ns3::Ptr< ns3::SpectrumPhy >', 'phy')], is_pure_virtual=True, is_virtual=True) ## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::AddSpectrumPropagationLossModel(ns3::Ptr<ns3::SpectrumPropagationLossModel> loss) [member function] cls.add_method('AddSpectrumPropagationLossModel', 'void', [param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'loss')], is_pure_virtual=True, is_virtual=True) ## spectrum-channel.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::SetPropagationDelayModel(ns3::Ptr<ns3::PropagationDelayModel> delay) [member function] cls.add_method('SetPropagationDelayModel', 'void', [param('ns3::Ptr< ns3::PropagationDelayModel >', 'delay')], is_pure_virtual=True, is_virtual=True) ## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::StartTx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartTx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_pure_virtual=True, is_virtual=True) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3Vector2DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')]) return def register_Ns3Vector2DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor] cls.add_constructor([param('ns3::Vector2D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector2DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector2DValue::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) ## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector2D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector2DValue::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) ## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector2D const &', 'value')]) return def register_Ns3Vector3DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')]) return def register_Ns3Vector3DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor] cls.add_constructor([param('ns3::Vector3D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector3DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector3DValue::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) ## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector3D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector3DValue::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) ## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector3D const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3AlohaNoackNetDevice_methods(root_module, cls): ## aloha-noack-net-device.h (module 'spectrum'): ns3::AlohaNoackNetDevice::AlohaNoackNetDevice(ns3::AlohaNoackNetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::AlohaNoackNetDevice const &', 'arg0')]) ## aloha-noack-net-device.h (module 'spectrum'): ns3::AlohaNoackNetDevice::AlohaNoackNetDevice() [constructor] cls.add_constructor([]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Address ns3::AlohaNoackNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Address ns3::AlohaNoackNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Channel> ns3::AlohaNoackNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): uint32_t ns3::AlohaNoackNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): uint16_t ns3::AlohaNoackNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Address ns3::AlohaNoackNetDevice::GetMulticast(ns3::Ipv4Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Address ns3::AlohaNoackNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Node> ns3::AlohaNoackNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Object> ns3::AlohaNoackNetDevice::GetPhy() const [member function] cls.add_method('GetPhy', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## aloha-noack-net-device.h (module 'spectrum'): static ns3::TypeId ns3::AlohaNoackNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::NotifyReceptionEndError() [member function] cls.add_method('NotifyReceptionEndError', 'void', []) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::NotifyReceptionEndOk(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('NotifyReceptionEndOk', 'void', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::NotifyReceptionStart() [member function] cls.add_method('NotifyReceptionStart', 'void', []) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::NotifyTransmissionEnd(ns3::Ptr<const ns3::Packet> arg0) [member function] cls.add_method('NotifyTransmissionEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'arg0')]) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetChannel(ns3::Ptr<ns3::Channel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::Channel >', 'c')]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetGenericPhyTxStartCallback(ns3::GenericPhyTxStartCallback c) [member function] cls.add_method('SetGenericPhyTxStartCallback', 'void', [param('ns3::GenericPhyTxStartCallback', 'c')]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetPhy(ns3::Ptr<ns3::Object> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::Object >', 'phy')]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetQueue(ns3::Ptr<ns3::Queue> queue) [member function] cls.add_method('SetQueue', 'void', [param('ns3::Ptr< ns3::Queue >', 'queue')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3MultiModelSpectrumChannel_methods(root_module, cls): ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::MultiModelSpectrumChannel::MultiModelSpectrumChannel(ns3::MultiModelSpectrumChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::MultiModelSpectrumChannel const &', 'arg0')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::MultiModelSpectrumChannel::MultiModelSpectrumChannel() [constructor] cls.add_constructor([]) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::AddPropagationLossModel(ns3::Ptr<ns3::PropagationLossModel> loss) [member function] cls.add_method('AddPropagationLossModel', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'loss')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::AddRx(ns3::Ptr<ns3::SpectrumPhy> phy) [member function] cls.add_method('AddRx', 'void', [param('ns3::Ptr< ns3::SpectrumPhy >', 'phy')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::AddSpectrumPropagationLossModel(ns3::Ptr<ns3::SpectrumPropagationLossModel> loss) [member function] cls.add_method('AddSpectrumPropagationLossModel', 'void', [param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'loss')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::MultiModelSpectrumChannel::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) ## multi-model-spectrum-channel.h (module 'spectrum'): uint32_t ns3::MultiModelSpectrumChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumPropagationLossModel> ns3::MultiModelSpectrumChannel::GetSpectrumPropagationLossModel() [member function] cls.add_method('GetSpectrumPropagationLossModel', 'ns3::Ptr< ns3::SpectrumPropagationLossModel >', [], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): static ns3::TypeId ns3::MultiModelSpectrumChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::SetPropagationDelayModel(ns3::Ptr<ns3::PropagationDelayModel> delay) [member function] cls.add_method('SetPropagationDelayModel', 'void', [param('ns3::Ptr< ns3::PropagationDelayModel >', 'delay')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::StartTx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartTx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params, ns3::Ptr<ns3::SpectrumPhy> receiver) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params'), param('ns3::Ptr< ns3::SpectrumPhy >', 'receiver')], visibility='private', is_virtual=True) return def register_Ns3SingleModelSpectrumChannel_methods(root_module, cls): ## single-model-spectrum-channel.h (module 'spectrum'): ns3::SingleModelSpectrumChannel::SingleModelSpectrumChannel(ns3::SingleModelSpectrumChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SingleModelSpectrumChannel const &', 'arg0')]) ## single-model-spectrum-channel.h (module 'spectrum'): ns3::SingleModelSpectrumChannel::SingleModelSpectrumChannel() [constructor] cls.add_constructor([]) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::AddPropagationLossModel(ns3::Ptr<ns3::PropagationLossModel> loss) [member function] cls.add_method('AddPropagationLossModel', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'loss')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::AddRx(ns3::Ptr<ns3::SpectrumPhy> phy) [member function] cls.add_method('AddRx', 'void', [param('ns3::Ptr< ns3::SpectrumPhy >', 'phy')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::AddSpectrumPropagationLossModel(ns3::Ptr<ns3::SpectrumPropagationLossModel> loss) [member function] cls.add_method('AddSpectrumPropagationLossModel', 'void', [param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'loss')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::SingleModelSpectrumChannel::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) ## single-model-spectrum-channel.h (module 'spectrum'): uint32_t ns3::SingleModelSpectrumChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumPropagationLossModel> ns3::SingleModelSpectrumChannel::GetSpectrumPropagationLossModel() [member function] cls.add_method('GetSpectrumPropagationLossModel', 'ns3::Ptr< ns3::SpectrumPropagationLossModel >', [], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): static ns3::TypeId ns3::SingleModelSpectrumChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::SetPropagationDelayModel(ns3::Ptr<ns3::PropagationDelayModel> delay) [member function] cls.add_method('SetPropagationDelayModel', 'void', [param('ns3::Ptr< ns3::PropagationDelayModel >', 'delay')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::StartTx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartTx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module ## spectrum-value.h (module 'spectrum'): extern double ns3::Integral(ns3::SpectrumValue const & arg) [free function] module.add_function('Integral', 'double', [param('ns3::SpectrumValue const &', 'arg')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Log(ns3::SpectrumValue const & arg) [free function] module.add_function('Log', 'ns3::SpectrumValue', [param('ns3::SpectrumValue const &', 'arg')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Log10(ns3::SpectrumValue const & arg) [free function] module.add_function('Log10', 'ns3::SpectrumValue', [param('ns3::SpectrumValue const &', 'arg')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Log2(ns3::SpectrumValue const & arg) [free function] module.add_function('Log2', 'ns3::SpectrumValue', [param('ns3::SpectrumValue const &', 'arg')]) ## spectrum-value.h (module 'spectrum'): extern double ns3::Norm(ns3::SpectrumValue const & x) [free function] module.add_function('Norm', 'double', [param('ns3::SpectrumValue const &', 'x')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Pow(ns3::SpectrumValue const & lhs, double rhs) [free function] module.add_function('Pow', 'ns3::SpectrumValue', [param('ns3::SpectrumValue const &', 'lhs'), param('double', 'rhs')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Pow(double lhs, ns3::SpectrumValue const & rhs) [free function] module.add_function('Pow', 'ns3::SpectrumValue', [param('double', 'lhs'), param('ns3::SpectrumValue const &', 'rhs')]) ## spectrum-value.h (module 'spectrum'): extern double ns3::Prod(ns3::SpectrumValue const & x) [free function] module.add_function('Prod', 'double', [param('ns3::SpectrumValue const &', 'x')]) ## spectrum-value.h (module 'spectrum'): extern double ns3::Sum(ns3::SpectrumValue const & x) [free function] module.add_function('Sum', 'double', [param('ns3::SpectrumValue const &', 'x')]) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_addressUtils(module, root_module): 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
VinceZK/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/extensions.py
119
31715
# Copyright 2012, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from mod_pywebsocket import common from mod_pywebsocket import util from mod_pywebsocket.http_header_util import quote_if_necessary _available_processors = {} _compression_extension_names = [] class ExtensionProcessorInterface(object): def __init__(self, request): self._request = request self._active = True def request(self): return self._request def name(self): return None def check_consistency_with_other_processors(self, processors): pass def set_active(self, active): self._active = active def is_active(self): return self._active def _get_extension_response_internal(self): return None def get_extension_response(self): if self._active: response = self._get_extension_response_internal() if response is None: self._active = False return response return None def _setup_stream_options_internal(self, stream_options): pass def setup_stream_options(self, stream_options): if self._active: self._setup_stream_options_internal(stream_options) def _log_outgoing_compression_ratio( logger, original_bytes, filtered_bytes, average_ratio): # Print inf when ratio is not available. ratio = float('inf') if original_bytes != 0: ratio = float(filtered_bytes) / original_bytes logger.debug('Outgoing compression ratio: %f (average: %f)' % (ratio, average_ratio)) def _log_incoming_compression_ratio( logger, received_bytes, filtered_bytes, average_ratio): # Print inf when ratio is not available. ratio = float('inf') if filtered_bytes != 0: ratio = float(received_bytes) / filtered_bytes logger.debug('Incoming compression ratio: %f (average: %f)' % (ratio, average_ratio)) def _parse_window_bits(bits): """Return parsed integer value iff the given string conforms to the grammar of the window bits extension parameters. """ if bits is None: raise ValueError('Value is required') # For non integer values such as "10.0", ValueError will be raised. int_bits = int(bits) # First condition is to drop leading zero case e.g. "08". if bits != str(int_bits) or int_bits < 8 or int_bits > 15: raise ValueError('Invalid value: %r' % bits) return int_bits class _AverageRatioCalculator(object): """Stores total bytes of original and result data, and calculates average result / original ratio. """ def __init__(self): self._total_original_bytes = 0 self._total_result_bytes = 0 def add_original_bytes(self, value): self._total_original_bytes += value def add_result_bytes(self, value): self._total_result_bytes += value def get_average_ratio(self): if self._total_original_bytes != 0: return (float(self._total_result_bytes) / self._total_original_bytes) else: return float('inf') class DeflateFrameExtensionProcessor(ExtensionProcessorInterface): """deflate-frame extension processor. Specification: http://tools.ietf.org/html/draft-tyoshino-hybi-websocket-perframe-deflate """ _WINDOW_BITS_PARAM = 'max_window_bits' _NO_CONTEXT_TAKEOVER_PARAM = 'no_context_takeover' def __init__(self, request): ExtensionProcessorInterface.__init__(self, request) self._logger = util.get_class_logger(self) self._response_window_bits = None self._response_no_context_takeover = False self._bfinal = False # Calculates # (Total outgoing bytes supplied to this filter) / # (Total bytes sent to the network after applying this filter) self._outgoing_average_ratio_calculator = _AverageRatioCalculator() # Calculates # (Total bytes received from the network) / # (Total incoming bytes obtained after applying this filter) self._incoming_average_ratio_calculator = _AverageRatioCalculator() def name(self): return common.DEFLATE_FRAME_EXTENSION def _get_extension_response_internal(self): # Any unknown parameter will be just ignored. window_bits = None if self._request.has_parameter(self._WINDOW_BITS_PARAM): window_bits = self._request.get_parameter_value( self._WINDOW_BITS_PARAM) try: window_bits = _parse_window_bits(window_bits) except ValueError, e: return None no_context_takeover = self._request.has_parameter( self._NO_CONTEXT_TAKEOVER_PARAM) if (no_context_takeover and self._request.get_parameter_value( self._NO_CONTEXT_TAKEOVER_PARAM) is not None): return None self._rfc1979_deflater = util._RFC1979Deflater( window_bits, no_context_takeover) self._rfc1979_inflater = util._RFC1979Inflater() self._compress_outgoing = True response = common.ExtensionParameter(self._request.name()) if self._response_window_bits is not None: response.add_parameter( self._WINDOW_BITS_PARAM, str(self._response_window_bits)) if self._response_no_context_takeover: response.add_parameter( self._NO_CONTEXT_TAKEOVER_PARAM, None) self._logger.debug( 'Enable %s extension (' 'request: window_bits=%s; no_context_takeover=%r, ' 'response: window_wbits=%s; no_context_takeover=%r)' % (self._request.name(), window_bits, no_context_takeover, self._response_window_bits, self._response_no_context_takeover)) return response def _setup_stream_options_internal(self, stream_options): class _OutgoingFilter(object): def __init__(self, parent): self._parent = parent def filter(self, frame): self._parent._outgoing_filter(frame) class _IncomingFilter(object): def __init__(self, parent): self._parent = parent def filter(self, frame): self._parent._incoming_filter(frame) stream_options.outgoing_frame_filters.append( _OutgoingFilter(self)) stream_options.incoming_frame_filters.insert( 0, _IncomingFilter(self)) def set_response_window_bits(self, value): self._response_window_bits = value def set_response_no_context_takeover(self, value): self._response_no_context_takeover = value def set_bfinal(self, value): self._bfinal = value def enable_outgoing_compression(self): self._compress_outgoing = True def disable_outgoing_compression(self): self._compress_outgoing = False def _outgoing_filter(self, frame): """Transform outgoing frames. This method is called only by an _OutgoingFilter instance. """ original_payload_size = len(frame.payload) self._outgoing_average_ratio_calculator.add_original_bytes( original_payload_size) if (not self._compress_outgoing or common.is_control_opcode(frame.opcode)): self._outgoing_average_ratio_calculator.add_result_bytes( original_payload_size) return frame.payload = self._rfc1979_deflater.filter( frame.payload, bfinal=self._bfinal) frame.rsv1 = 1 filtered_payload_size = len(frame.payload) self._outgoing_average_ratio_calculator.add_result_bytes( filtered_payload_size) _log_outgoing_compression_ratio( self._logger, original_payload_size, filtered_payload_size, self._outgoing_average_ratio_calculator.get_average_ratio()) def _incoming_filter(self, frame): """Transform incoming frames. This method is called only by an _IncomingFilter instance. """ received_payload_size = len(frame.payload) self._incoming_average_ratio_calculator.add_result_bytes( received_payload_size) if frame.rsv1 != 1 or common.is_control_opcode(frame.opcode): self._incoming_average_ratio_calculator.add_original_bytes( received_payload_size) return frame.payload = self._rfc1979_inflater.filter(frame.payload) frame.rsv1 = 0 filtered_payload_size = len(frame.payload) self._incoming_average_ratio_calculator.add_original_bytes( filtered_payload_size) _log_incoming_compression_ratio( self._logger, received_payload_size, filtered_payload_size, self._incoming_average_ratio_calculator.get_average_ratio()) _available_processors[common.DEFLATE_FRAME_EXTENSION] = ( DeflateFrameExtensionProcessor) _compression_extension_names.append(common.DEFLATE_FRAME_EXTENSION) _available_processors[common.X_WEBKIT_DEFLATE_FRAME_EXTENSION] = ( DeflateFrameExtensionProcessor) _compression_extension_names.append(common.X_WEBKIT_DEFLATE_FRAME_EXTENSION) def _parse_compression_method(data): """Parses the value of "method" extension parameter.""" return common.parse_extensions(data, allow_quoted_string=True) def _create_accepted_method_desc(method_name, method_params): """Creates accepted-method-desc from given method name and parameters""" extension = common.ExtensionParameter(method_name) for name, value in method_params: extension.add_parameter(name, value) return common.format_extension(extension) class CompressionExtensionProcessorBase(ExtensionProcessorInterface): """Base class for perframe-compress and permessage-compress extension.""" _METHOD_PARAM = 'method' def __init__(self, request): ExtensionProcessorInterface.__init__(self, request) self._logger = util.get_class_logger(self) self._compression_method_name = None self._compression_processor = None self._compression_processor_hook = None def name(self): return '' def _lookup_compression_processor(self, method_desc): return None def _get_compression_processor_response(self): """Looks up the compression processor based on the self._request and returns the compression processor's response. """ method_list = self._request.get_parameter_value(self._METHOD_PARAM) if method_list is None: return None methods = _parse_compression_method(method_list) if methods is None: return None comression_processor = None # The current implementation tries only the first method that matches # supported algorithm. Following methods aren't tried even if the # first one is rejected. # TODO(bashi): Need to clarify this behavior. for method_desc in methods: compression_processor = self._lookup_compression_processor( method_desc) if compression_processor is not None: self._compression_method_name = method_desc.name() break if compression_processor is None: return None if self._compression_processor_hook: self._compression_processor_hook(compression_processor) processor_response = compression_processor.get_extension_response() if processor_response is None: return None self._compression_processor = compression_processor return processor_response def _get_extension_response_internal(self): processor_response = self._get_compression_processor_response() if processor_response is None: return None response = common.ExtensionParameter(self._request.name()) accepted_method_desc = _create_accepted_method_desc( self._compression_method_name, processor_response.get_parameters()) response.add_parameter(self._METHOD_PARAM, accepted_method_desc) self._logger.debug( 'Enable %s extension (method: %s)' % (self._request.name(), self._compression_method_name)) return response def _setup_stream_options_internal(self, stream_options): if self._compression_processor is None: return self._compression_processor.setup_stream_options(stream_options) def set_compression_processor_hook(self, hook): self._compression_processor_hook = hook def get_compression_processor(self): return self._compression_processor class PerFrameCompressExtensionProcessor(CompressionExtensionProcessorBase): """perframe-compress processor. Specification: http://tools.ietf.org/html/draft-ietf-hybi-websocket-perframe-compression """ _DEFLATE_METHOD = 'deflate' def __init__(self, request): CompressionExtensionProcessorBase.__init__(self, request) def name(self): return common.PERFRAME_COMPRESSION_EXTENSION def _lookup_compression_processor(self, method_desc): if method_desc.name() == self._DEFLATE_METHOD: return DeflateFrameExtensionProcessor(method_desc) return None _available_processors[common.PERFRAME_COMPRESSION_EXTENSION] = ( PerFrameCompressExtensionProcessor) _compression_extension_names.append(common.PERFRAME_COMPRESSION_EXTENSION) class PerMessageDeflateExtensionProcessor(ExtensionProcessorInterface): """permessage-deflate extension processor. It's also used for permessage-compress extension when the deflate method is chosen. Specification: http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression-08 """ _S2C_MAX_WINDOW_BITS_PARAM = 's2c_max_window_bits' _S2C_NO_CONTEXT_TAKEOVER_PARAM = 's2c_no_context_takeover' _C2S_MAX_WINDOW_BITS_PARAM = 'c2s_max_window_bits' _C2S_NO_CONTEXT_TAKEOVER_PARAM = 'c2s_no_context_takeover' def __init__(self, request, draft08=True): """Construct PerMessageDeflateExtensionProcessor Args: draft08: Follow the constraints on the parameters that were not specified for permessage-compress but are specified for permessage-deflate as on draft-ietf-hybi-permessage-compression-08. """ ExtensionProcessorInterface.__init__(self, request) self._logger = util.get_class_logger(self) self._c2s_max_window_bits = None self._c2s_no_context_takeover = False self._draft08 = draft08 def name(self): return 'deflate' def _get_extension_response_internal(self): if self._draft08: for name in self._request.get_parameter_names(): if name not in [self._S2C_MAX_WINDOW_BITS_PARAM, self._S2C_NO_CONTEXT_TAKEOVER_PARAM, self._C2S_MAX_WINDOW_BITS_PARAM]: self._logger.debug('Unknown parameter: %r', name) return None else: # Any unknown parameter will be just ignored. pass s2c_max_window_bits = None if self._request.has_parameter(self._S2C_MAX_WINDOW_BITS_PARAM): s2c_max_window_bits = self._request.get_parameter_value( self._S2C_MAX_WINDOW_BITS_PARAM) try: s2c_max_window_bits = _parse_window_bits(s2c_max_window_bits) except ValueError, e: self._logger.debug('Bad %s parameter: %r', self._S2C_MAX_WINDOW_BITS_PARAM, e) return None s2c_no_context_takeover = self._request.has_parameter( self._S2C_NO_CONTEXT_TAKEOVER_PARAM) if (s2c_no_context_takeover and self._request.get_parameter_value( self._S2C_NO_CONTEXT_TAKEOVER_PARAM) is not None): self._logger.debug('%s parameter must not have a value: %r', self._S2C_NO_CONTEXT_TAKEOVER_PARAM, s2c_no_context_takeover) return None c2s_max_window_bits = self._request.has_parameter( self._C2S_MAX_WINDOW_BITS_PARAM) if (self._draft08 and c2s_max_window_bits and self._request.get_parameter_value( self._C2S_MAX_WINDOW_BITS_PARAM) is not None): self._logger.debug('%s parameter must not have a value in a ' 'client\'s opening handshake: %r', self._C2S_MAX_WINDOW_BITS_PARAM, c2s_max_window_bits) return None self._rfc1979_deflater = util._RFC1979Deflater( s2c_max_window_bits, s2c_no_context_takeover) self._rfc1979_inflater = util._RFC1979Inflater() self._framer = _PerMessageDeflateFramer( s2c_max_window_bits, s2c_no_context_takeover) self._framer.set_bfinal(False) self._framer.set_compress_outgoing_enabled(True) response = common.ExtensionParameter(self._request.name()) if s2c_max_window_bits is not None: response.add_parameter( self._S2C_MAX_WINDOW_BITS_PARAM, str(s2c_max_window_bits)) if s2c_no_context_takeover: response.add_parameter( self._S2C_NO_CONTEXT_TAKEOVER_PARAM, None) if self._c2s_max_window_bits is not None: if self._draft08 and c2s_max_window_bits: self._logger.debug('Processor is configured to use %s but ' 'the client cannot accept it', self._C2S_MAX_WINDOW_BITS_PARAM) return None response.add_parameter( self._C2S_MAX_WINDOW_BITS_PARAM, str(self._c2s_max_window_bits)) if self._c2s_no_context_takeover: response.add_parameter( self._C2S_NO_CONTEXT_TAKEOVER_PARAM, None) self._logger.debug( 'Enable %s extension (' 'request: s2c_max_window_bits=%s; s2c_no_context_takeover=%r, ' 'response: c2s_max_window_bits=%s; c2s_no_context_takeover=%r)' % (self._request.name(), s2c_max_window_bits, s2c_no_context_takeover, self._c2s_max_window_bits, self._c2s_no_context_takeover)) return response def _setup_stream_options_internal(self, stream_options): self._framer.setup_stream_options(stream_options) def set_c2s_max_window_bits(self, value): """If this option is specified, this class adds the c2s_max_window_bits extension parameter to the handshake response, but doesn't reduce the LZ77 sliding window size of its inflater. I.e., you can use this for testing client implementation but cannot reduce memory usage of this class. If this method has been called with True and an offer without the c2s_max_window_bits extension parameter is received, - (When processing the permessage-deflate extension) this processor declines the request. - (When processing the permessage-compress extension) this processor accepts the request. """ self._c2s_max_window_bits = value def set_c2s_no_context_takeover(self, value): """If this option is specified, this class adds the c2s_no_context_takeover extension parameter to the handshake response, but doesn't reset inflater for each message. I.e., you can use this for testing client implementation but cannot reduce memory usage of this class. """ self._c2s_no_context_takeover = value def set_bfinal(self, value): self._framer.set_bfinal(value) def enable_outgoing_compression(self): self._framer.set_compress_outgoing_enabled(True) def disable_outgoing_compression(self): self._framer.set_compress_outgoing_enabled(False) class _PerMessageDeflateFramer(object): """A framer for extensions with per-message DEFLATE feature.""" def __init__(self, deflate_max_window_bits, deflate_no_context_takeover): self._logger = util.get_class_logger(self) self._rfc1979_deflater = util._RFC1979Deflater( deflate_max_window_bits, deflate_no_context_takeover) self._rfc1979_inflater = util._RFC1979Inflater() self._bfinal = False self._compress_outgoing_enabled = False # True if a message is fragmented and compression is ongoing. self._compress_ongoing = False # Calculates # (Total outgoing bytes supplied to this filter) / # (Total bytes sent to the network after applying this filter) self._outgoing_average_ratio_calculator = _AverageRatioCalculator() # Calculates # (Total bytes received from the network) / # (Total incoming bytes obtained after applying this filter) self._incoming_average_ratio_calculator = _AverageRatioCalculator() def set_bfinal(self, value): self._bfinal = value def set_compress_outgoing_enabled(self, value): self._compress_outgoing_enabled = value def _process_incoming_message(self, message, decompress): if not decompress: return message received_payload_size = len(message) self._incoming_average_ratio_calculator.add_result_bytes( received_payload_size) message = self._rfc1979_inflater.filter(message) filtered_payload_size = len(message) self._incoming_average_ratio_calculator.add_original_bytes( filtered_payload_size) _log_incoming_compression_ratio( self._logger, received_payload_size, filtered_payload_size, self._incoming_average_ratio_calculator.get_average_ratio()) return message def _process_outgoing_message(self, message, end, binary): if not binary: message = message.encode('utf-8') if not self._compress_outgoing_enabled: return message original_payload_size = len(message) self._outgoing_average_ratio_calculator.add_original_bytes( original_payload_size) message = self._rfc1979_deflater.filter( message, flush=end, bfinal=self._bfinal) filtered_payload_size = len(message) self._outgoing_average_ratio_calculator.add_result_bytes( filtered_payload_size) _log_outgoing_compression_ratio( self._logger, original_payload_size, filtered_payload_size, self._outgoing_average_ratio_calculator.get_average_ratio()) if not self._compress_ongoing: self._outgoing_frame_filter.set_compression_bit() self._compress_ongoing = not end return message def _process_incoming_frame(self, frame): if frame.rsv1 == 1 and not common.is_control_opcode(frame.opcode): self._incoming_message_filter.decompress_next_message() frame.rsv1 = 0 def _process_outgoing_frame(self, frame, compression_bit): if (not compression_bit or common.is_control_opcode(frame.opcode)): return frame.rsv1 = 1 def setup_stream_options(self, stream_options): """Creates filters and sets them to the StreamOptions.""" class _OutgoingMessageFilter(object): def __init__(self, parent): self._parent = parent def filter(self, message, end=True, binary=False): return self._parent._process_outgoing_message( message, end, binary) class _IncomingMessageFilter(object): def __init__(self, parent): self._parent = parent self._decompress_next_message = False def decompress_next_message(self): self._decompress_next_message = True def filter(self, message): message = self._parent._process_incoming_message( message, self._decompress_next_message) self._decompress_next_message = False return message self._outgoing_message_filter = _OutgoingMessageFilter(self) self._incoming_message_filter = _IncomingMessageFilter(self) stream_options.outgoing_message_filters.append( self._outgoing_message_filter) stream_options.incoming_message_filters.append( self._incoming_message_filter) class _OutgoingFrameFilter(object): def __init__(self, parent): self._parent = parent self._set_compression_bit = False def set_compression_bit(self): self._set_compression_bit = True def filter(self, frame): self._parent._process_outgoing_frame( frame, self._set_compression_bit) self._set_compression_bit = False class _IncomingFrameFilter(object): def __init__(self, parent): self._parent = parent def filter(self, frame): self._parent._process_incoming_frame(frame) self._outgoing_frame_filter = _OutgoingFrameFilter(self) self._incoming_frame_filter = _IncomingFrameFilter(self) stream_options.outgoing_frame_filters.append( self._outgoing_frame_filter) stream_options.incoming_frame_filters.append( self._incoming_frame_filter) stream_options.encode_text_message_to_utf8 = False _available_processors[common.PERMESSAGE_DEFLATE_EXTENSION] = ( PerMessageDeflateExtensionProcessor) # TODO(tyoshino): Reorganize class names. _compression_extension_names.append('deflate') class PerMessageCompressExtensionProcessor( CompressionExtensionProcessorBase): """permessage-compress extension processor. Specification: http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression """ _DEFLATE_METHOD = 'deflate' def __init__(self, request): CompressionExtensionProcessorBase.__init__(self, request) def name(self): return common.PERMESSAGE_COMPRESSION_EXTENSION def _lookup_compression_processor(self, method_desc): if method_desc.name() == self._DEFLATE_METHOD: return PerMessageDeflateExtensionProcessor(method_desc, False) return None _available_processors[common.PERMESSAGE_COMPRESSION_EXTENSION] = ( PerMessageCompressExtensionProcessor) _compression_extension_names.append(common.PERMESSAGE_COMPRESSION_EXTENSION) class MuxExtensionProcessor(ExtensionProcessorInterface): """WebSocket multiplexing extension processor.""" _QUOTA_PARAM = 'quota' def __init__(self, request): ExtensionProcessorInterface.__init__(self, request) self._quota = 0 self._extensions = [] def name(self): return common.MUX_EXTENSION def check_consistency_with_other_processors(self, processors): before_mux = True for processor in processors: name = processor.name() if name == self.name(): before_mux = False continue if not processor.is_active(): continue if before_mux: # Mux extension cannot be used after extensions # that depend on frame boundary, extension data field, or any # reserved bits which are attributed to each frame. if (name == common.PERFRAME_COMPRESSION_EXTENSION or name == common.DEFLATE_FRAME_EXTENSION or name == common.X_WEBKIT_DEFLATE_FRAME_EXTENSION): self.set_active(False) return else: # Mux extension should not be applied before any history-based # compression extension. if (name == common.PERFRAME_COMPRESSION_EXTENSION or name == common.DEFLATE_FRAME_EXTENSION or name == common.X_WEBKIT_DEFLATE_FRAME_EXTENSION or name == common.PERMESSAGE_COMPRESSION_EXTENSION or name == common.X_WEBKIT_PERMESSAGE_COMPRESSION_EXTENSION): self.set_active(False) return def _get_extension_response_internal(self): self._active = False quota = self._request.get_parameter_value(self._QUOTA_PARAM) if quota is not None: try: quota = int(quota) except ValueError, e: return None if quota < 0 or quota >= 2 ** 32: return None self._quota = quota self._active = True return common.ExtensionParameter(common.MUX_EXTENSION) def _setup_stream_options_internal(self, stream_options): pass def set_quota(self, quota): self._quota = quota def quota(self): return self._quota def set_extensions(self, extensions): self._extensions = extensions def extensions(self): return self._extensions _available_processors[common.MUX_EXTENSION] = MuxExtensionProcessor def get_extension_processor(extension_request): processor_class = _available_processors.get(extension_request.name()) if processor_class is None: return None return processor_class(extension_request) def is_compression_extension(extension_name): return extension_name in _compression_extension_names # vi:sts=4 sw=4 et
bsd-3-clause
benzkji/django-formfieldstash
formfieldstash/tests/utils/selenium_utils.py
1
2419
from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support.expected_conditions import _element_if_visible from selenium import webdriver # compat import django if django.VERSION[:2] < (1, 10): from django.core.urlresolvers import reverse else: from django.urls import reverse class invisibility_of(object): def __init__(self, element): self.element = element def __call__(self, ignored): return not _element_if_visible(self.element) class CustomWebDriver(webdriver.Firefox): """Our own WebDriver with some helpers added""" def find_css(self, css_selector): """Shortcut to find elements by CSS. Returns either a list or singleton""" elems = self.find_elements_by_css_selector(css_selector) found = len(elems) if found == 1: return elems[0] elif not elems: raise NoSuchElementException(css_selector) return elems def wait_for_css(self, css_selector, timeout=7): """ Shortcut for WebDriverWait""" return WebDriverWait(self, timeout).until(lambda driver: driver.find_css(css_selector)) class SeleniumTestCase(StaticLiveServerTestCase): """ A base test case for Selenium, providing hepler methods for generating clients and logging in profiles. """ def open(self, url): self.webdriver.get("%s%s" % (self.live_server_url, url)) def login(self): self.open(reverse('admin:index')) # Selenium knows it has to wait for page loads (except for AJAX requests) # so we don't need to do anything about that, and can just # call find_css. Since we can chain methods, we can # call the built-in send_keys method right away to change the # value of the field self.webdriver.find_css('#id_username').send_keys("admin") # for the password, we can now just call find_css since we know the page # has been rendered self.webdriver.find_css("#id_password").send_keys('secret') # You're not limited to CSS selectors only, check # http://seleniumhq.org/docs/03_webdriver.html for # a more compreehensive documentation. self.webdriver.find_element_by_xpath('//input[@type="submit"]').click()
mit
kivatu/kivy_old
kivy/tests/common.py
20
10004
''' This is a extended unittest module for Kivy, to make unittest based on graphics with OpenGL context. The idea is to let user render a Widget tree, and after 1, 2 or x frame, a screenshot will be done, and be compared to the original one. If no screenshot exist for the current test, the very first one will be used. The screenshots lives in kivy/tests/results, in PNG format, 320x240. ''' __all__ = ('GraphicUnitTest', ) import unittest import logging log = logging.getLogger('unittest') class GraphicUnitTest(unittest.TestCase): def render(self, root, framecount=1): '''Call rendering process using the `root` widget. The screenshot will be done in `framecount` frames. ''' from kivy.base import runTouchApp self.framecount = framecount runTouchApp(root) # reset for the next test, but nobody will know if it will be used :/ if self.test_counter != 0: self.tearDown(fake=True) self.setUp() def run(self, name): '''Extend the run of unittest, to check if results directory have been found. If no results directory exists, the test will be ignored. ''' from os.path import join, dirname, exists results_dir = join(dirname(__file__), 'results') if not exists(results_dir): log.warning('No result directory found, cancel test.') return self.test_counter = 0 self.results_dir = results_dir self.test_failed = False return super(GraphicUnitTest, self).run(name) def setUp(self): '''Prepare the graphic test, with: - Window size fixed to 320x240 - Default kivy configuration - Without any kivy input ''' # use default kivy configuration (don't load user file.) from os import environ environ['KIVY_USE_DEFAULTCONFIG'] = '1' # force window size + remove all inputs from kivy.config import Config Config.set('graphics', 'width', '320') Config.set('graphics', 'height', '240') for items in Config.items('input'): Config.remove_option('input', items[0]) # bind ourself for the later screenshot from kivy.core.window import Window Window.bind(on_flip=self.on_window_flip) # ensure our window is correcly created Window.create_window() def on_window_flip(self, window): '''Internal method to be called when the window have just displayed an image. When an image is showed, we decrement our framecount. If framecount is come to 0, we are taking the screenshot. The screenshot is done in a temporary place, and is compared to the original one -> test ok/ko. If no screenshot is available in the results directory, a new one will be created. ''' from kivy.base import EventLoop from tempfile import mkstemp from os.path import join, exists from os import unlink, close from shutil import move, copy # don't save screenshot until we have enough frames. #log.debug('framecount %d' % self.framecount) self.framecount -= 1 if self.framecount > 0: return reffn = None match = False try: # just get a temporary name fd, tmpfn = mkstemp(suffix='.png', prefix='kivyunit-') close(fd) unlink(tmpfn) # get a filename for the current unit test self.test_counter += 1 test_uid = '%s-%d.png' % ( '_'.join(self.id().split('.')[-2:]), self.test_counter) # capture the screen log.info('Capturing screenshot for %s' % test_uid) tmpfn = window.screenshot(tmpfn) log.info('Capture saved at %s' % tmpfn) # search the file to compare to reffn = join(self.results_dir, test_uid) log.info('Compare with %s' % reffn) # get sourcecode import inspect frame = inspect.getouterframes(inspect.currentframe())[6] sourcecodetab, line = inspect.getsourcelines(frame[0]) line = frame[2] - line currentline = sourcecodetab[line] sourcecodetab[line] = '<span style="color: red;">%s</span>' % ( currentline) sourcecode = ''.join(sourcecodetab) sourcecodetab[line] = '>>>>>>>>\n%s<<<<<<<<\n' % currentline sourcecodeask = ''.join(sourcecodetab) if not exists(reffn): log.info('No image reference, move %s as ref ?' % test_uid) if self.interactive_ask_ref(sourcecodeask, tmpfn, self.id()): move(tmpfn, reffn) tmpfn = reffn log.info('Image used as reference') match = True else: log.info('Image discarded') else: import pygame s1 = pygame.image.load(tmpfn) s2 = pygame.image.load(reffn) sd1 = pygame.image.tostring(s1, 'RGB') sd2 = pygame.image.tostring(s2, 'RGB') if sd1 != sd2: log.critical( '%s at render() #%d, images are different.' % ( self.id(), self.test_counter)) if self.interactive_ask_diff(sourcecodeask, tmpfn, reffn, self.id()): log.critical('user ask to use it as ref.') move(tmpfn, reffn) tmpfn = reffn match = True else: self.test_failed = True else: match = True # generate html from os.path import join, dirname, exists, basename from os import mkdir build_dir = join(dirname(__file__), 'build') if not exists(build_dir): mkdir(build_dir) copy(reffn, join(build_dir, 'ref_%s' % basename(reffn))) if tmpfn != reffn: copy(tmpfn, join(build_dir, 'test_%s' % basename(reffn))) with open(join(build_dir, 'index.html'), 'at') as fd: color = '#ffdddd' if not match else '#ffffff' fd.write('<div style="background-color: %s">' % color) fd.write('<h2>%s #%d</h2>' % (self.id(), self.test_counter)) fd.write('<table><tr><th>Reference</th>' '<th>Test</th>' '<th>Comment</th>') fd.write('<tr><td><img src="ref_%s"/></td>' % basename(reffn)) if tmpfn != reffn: fd.write('<td><img src="test_%s"/></td>' % basename(reffn)) else: fd.write('<td>First time, no comparaison.</td>') fd.write('<td><pre>%s</pre></td>' % sourcecode) fd.write('</table></div>') finally: try: if reffn != tmpfn: unlink(tmpfn) except: pass EventLoop.stop() def tearDown(self, fake=False): '''When the test is finished, stop the application, and unbind our current flip callback. ''' from kivy.base import stopTouchApp from kivy.core.window import Window Window.unbind(on_flip=self.on_window_flip) stopTouchApp() if not fake and self.test_failed: self.assertTrue(False) super(GraphicUnitTest, self).tearDown() def interactive_ask_ref(self, code, imagefn, testid): from os import environ if 'UNITTEST_INTERACTIVE' not in environ: return True from tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button from PIL import Image, ImageTk self.retval = False root = Tk() def do_close(): root.destroy() def do_yes(): self.retval = True do_close() image = Image.open(imagefn) photo = ImageTk.PhotoImage(image) Label(root, text='The test %s\nhave no reference.' % testid).pack() Label(root, text='Use this image as a reference ?').pack() Label(root, text=code, justify=LEFT).pack(side=RIGHT) Label(root, image=photo).pack(side=LEFT) Button(root, text='Use as reference', command=do_yes).pack(side=BOTTOM) Button(root, text='Discard', command=do_close).pack(side=BOTTOM) root.mainloop() return self.retval def interactive_ask_diff(self, code, tmpfn, reffn, testid): from os import environ if 'UNITTEST_INTERACTIVE' not in environ: return False from tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button from PIL import Image, ImageTk self.retval = False root = Tk() def do_close(): root.destroy() def do_yes(): self.retval = True do_close() phototmp = ImageTk.PhotoImage(Image.open(tmpfn)) photoref = ImageTk.PhotoImage(Image.open(reffn)) Label(root, text='The test %s\nhave generated an different' 'image as the reference one..' % testid).pack() Label(root, text='Which one is good ?').pack() Label(root, text=code, justify=LEFT).pack(side=RIGHT) Label(root, image=phototmp).pack(side=RIGHT) Label(root, image=photoref).pack(side=LEFT) Button(root, text='Use the new image -->', command=do_yes).pack(side=BOTTOM) Button(root, text='<-- Use the reference', command=do_close).pack(side=BOTTOM) root.mainloop() return self.retval
mit
sallaire/Sick-Beard
sickbeard/clients/requests/auth.py
38
5460
# -*- coding: utf-8 -*- """ requests.auth ~~~~~~~~~~~~~ This module contains the authentication handlers for Requests. """ import os import time import hashlib import logging from base64 import b64encode from .compat import urlparse, str from .utils import parse_dict_header log = logging.getLogger(__name__) CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded' CONTENT_TYPE_MULTI_PART = 'multipart/form-data' def _basic_auth_str(username, password): """Returns a Basic Auth string.""" return 'Basic ' + b64encode(('%s:%s' % (username, password)).encode('latin1')).strip().decode('latin1') class AuthBase(object): """Base class that all auth implementations derive from""" def __call__(self, r): raise NotImplementedError('Auth hooks must be callable.') class HTTPBasicAuth(AuthBase): """Attaches HTTP Basic Authentication to the given Request object.""" def __init__(self, username, password): self.username = username self.password = password def __call__(self, r): r.headers['Authorization'] = _basic_auth_str(self.username, self.password) return r class HTTPProxyAuth(HTTPBasicAuth): """Attaches HTTP Proxy Authentication to a given Request object.""" def __call__(self, r): r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password) return r class HTTPDigestAuth(AuthBase): """Attaches HTTP Digest Authentication to the given Request object.""" def __init__(self, username, password): self.username = username self.password = password self.last_nonce = '' self.nonce_count = 0 self.chal = {} def build_digest_header(self, method, url): realm = self.chal['realm'] nonce = self.chal['nonce'] qop = self.chal.get('qop') algorithm = self.chal.get('algorithm') opaque = self.chal.get('opaque') if algorithm is None: _algorithm = 'MD5' else: _algorithm = algorithm.upper() # lambdas assume digest modules are imported at the top level if _algorithm == 'MD5': def md5_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.md5(x).hexdigest() hash_utf8 = md5_utf8 elif _algorithm == 'SHA': def sha_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.sha1(x).hexdigest() hash_utf8 = sha_utf8 # XXX MD5-sess KD = lambda s, d: hash_utf8("%s:%s" % (s, d)) if hash_utf8 is None: return None # XXX not implemented yet entdig = None p_parsed = urlparse(url) path = p_parsed.path if p_parsed.query: path += '?' + p_parsed.query A1 = '%s:%s:%s' % (self.username, realm, self.password) A2 = '%s:%s' % (method, path) if qop == 'auth': if nonce == self.last_nonce: self.nonce_count += 1 else: self.nonce_count = 1 ncvalue = '%08x' % self.nonce_count s = str(self.nonce_count).encode('utf-8') s += nonce.encode('utf-8') s += time.ctime().encode('utf-8') s += os.urandom(8) cnonce = (hashlib.sha1(s).hexdigest()[:16]) noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, hash_utf8(A2)) respdig = KD(hash_utf8(A1), noncebit) elif qop is None: respdig = KD(hash_utf8(A1), "%s:%s" % (nonce, hash_utf8(A2))) else: # XXX handle auth-int. return None self.last_nonce = nonce # XXX should the partial digests be encoded too? base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \ 'response="%s"' % (self.username, realm, nonce, path, respdig) if opaque: base += ', opaque="%s"' % opaque if algorithm: base += ', algorithm="%s"' % algorithm if entdig: base += ', digest="%s"' % entdig if qop: base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce) return 'Digest %s' % (base) def handle_401(self, r, **kwargs): """Takes the given response and tries digest-auth, if needed.""" num_401_calls = getattr(self, 'num_401_calls', 1) s_auth = r.headers.get('www-authenticate', '') if 'digest' in s_auth.lower() and num_401_calls < 2: setattr(self, 'num_401_calls', num_401_calls + 1) self.chal = parse_dict_header(s_auth.replace('Digest ', '')) # Consume content and release the original connection # to allow our new request to reuse the same one. r.content r.raw.release_conn() r.request.headers['Authorization'] = self.build_digest_header(r.request.method, r.request.url) _r = r.connection.send(r.request, **kwargs) _r.history.append(r) return _r setattr(self, 'num_401_calls', 1) return r def __call__(self, r): # If we have a saved nonce, skip the 401 if self.last_nonce: r.headers['Authorization'] = self.build_digest_header(r.method, r.url) r.register_hook('response', self.handle_401) return r
gpl-3.0
denzp/cef3
tools/make_gypi_file.py
15
3367
# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights # reserved. Use of this source code is governed by a BSD-style license that # can be found in the LICENSE file. from cef_parser import * def make_gypi_file(header): # header string result = \ """# Copyright (c) $YEAR$ The Chromium Embedded Framework Authors. All rights # reserved. Use of this source code is governed by a BSD-style license that # can be found in the LICENSE file. # # --------------------------------------------------------------------------- # # This file was generated by the CEF translator tool and should not edited # by hand. See the translator.README.txt file in the tools directory for # more information. # { 'variables': { """ filenames = sorted(header.get_file_names()) # cpp includes result += " 'autogen_cpp_includes': [\n" for filename in filenames: result += " 'include/"+filename+"',\n" result += " ],\n" # capi includes result += " 'autogen_capi_includes': [\n" for filename in filenames: result += " 'include/capi/"+get_capi_file_name(filename)+"',\n" result += " ],\n" classes = sorted(header.get_class_names()) # library side includes result += " 'autogen_library_side': [\n" for clsname in classes: cls = header.get_class(clsname) filename = get_capi_name(clsname[3:], False) if cls.is_library_side(): result += " 'libcef_dll/cpptoc/"+filename+"_cpptoc.cc',\n" \ " 'libcef_dll/cpptoc/"+filename+"_cpptoc.h',\n" else: result += " 'libcef_dll/ctocpp/"+filename+"_ctocpp.cc',\n" \ " 'libcef_dll/ctocpp/"+filename+"_ctocpp.h',\n" result += " ],\n" # client side includes result += " 'autogen_client_side': [\n" for clsname in classes: cls = header.get_class(clsname) filename = get_capi_name(clsname[3:], False) if cls.is_library_side(): result += " 'libcef_dll/ctocpp/"+filename+"_ctocpp.cc',\n" \ " 'libcef_dll/ctocpp/"+filename+"_ctocpp.h',\n" else: result += " 'libcef_dll/cpptoc/"+filename+"_cpptoc.cc',\n" \ " 'libcef_dll/cpptoc/"+filename+"_cpptoc.h',\n" result += " ],\n" # footer string result += \ """ }, } """ # add the copyright year result = result.replace('$YEAR$', get_year()) return result def write_gypi_file(header, file, backup): if path_exists(file): oldcontents = read_file(file) else: oldcontents = '' newcontents = make_gypi_file(header) if newcontents != oldcontents: if backup and oldcontents != '': backup_file(file) write_file(file, newcontents) return True return False # test the module if __name__ == "__main__": import sys # verify that the correct number of command-line arguments are provided if len(sys.argv) < 2: sys.stderr.write('Usage: '+sys.argv[0]+' <infile>') sys.exit() # create the header object header = obj_header() header.add_file(sys.argv[1]) # dump the result to stdout sys.stdout.write(make_gypi_file(header))
bsd-3-clause
gangadhar-kadam/smrterp
erpnext/stock/report/supplier_wise_sales_analytics/supplier_wise_sales_analytics.py
12
3471
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt def execute(filters=None): columns = get_columns(filters) consumed_details = get_consumed_details(filters) supplier_details = get_suppliers_details(filters) material_transfer_vouchers = get_material_transfer_vouchers() data = [] for item_code, suppliers in supplier_details.items(): consumed_qty = consumed_amount = delivered_qty = delivered_amount = 0.0 total_qty = total_amount = 0.0 if consumed_details.get(item_code): for cd in consumed_details.get(item_code): if (cd.voucher_no not in material_transfer_vouchers): if cd.voucher_type=="Delivery Note": delivered_qty += abs(flt(cd.actual_qty)) delivered_amount += abs(flt(cd.stock_value_difference)) elif cd.voucher_type!="Delivery Note": consumed_qty += abs(flt(cd.actual_qty)) consumed_amount += abs(flt(cd.stock_value_difference)) if consumed_qty or consumed_amount or delivered_qty or delivered_amount: total_qty += delivered_qty + consumed_qty total_amount += delivered_amount + consumed_amount row = [cd.item_code, cd.item_name, cd.description, cd.stock_uom, \ consumed_qty, consumed_amount, delivered_qty, delivered_amount, \ total_qty, total_amount, list(set(suppliers))] data.append(row) return columns, data def get_columns(filters): """return columns based on filters""" columns = ["Item:Link/Item:100"] + ["Item Name::100"] + \ ["Description::150"] + ["UOM:Link/UOM:90"] + \ ["Consumed Qty:Float:110"] + ["Consumed Amount:Currency:130"] + \ ["Delivered Qty:Float:110"] + ["Delivered Amount:Currency:130"] + \ ["Total Qty:Float:110"] + ["Total Amount:Currency:130"] + \ ["Supplier(s)::250"] return columns def get_conditions(filters): conditions = "" values = [] if filters.get('from_date') and filters.get('to_date'): conditions = "and sle.posting_date>=%s and sle.posting_date<=%s" values = [filters.get('from_date'), filters.get('to_date')] return conditions, values def get_consumed_details(filters): conditions, values = get_conditions(filters) consumed_details = {} for d in frappe.db.sql("""select sle.item_code, i.item_name, i.description, i.stock_uom, sle.actual_qty, sle.stock_value_difference, sle.voucher_no, sle.voucher_type from `tabStock Ledger Entry` sle, `tabItem` i where sle.item_code=i.name and sle.actual_qty < 0 %s""" % conditions, values, as_dict=1): consumed_details.setdefault(d.item_code, []).append(d) return consumed_details def get_suppliers_details(filters): item_supplier_map = {} supplier = filters.get('supplier') for d in frappe.db.sql("""select pr.supplier, pri.item_code from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pri where pr.name=pri.parent and pr.docstatus=1 and pri.item_code=(select name from `tabItem` where ifnull(is_stock_item, 'Yes')='Yes' and name=pri.item_code)""", as_dict=1): item_supplier_map.setdefault(d.item_code, []).append(d.supplier) if supplier: for item_code, suppliers in item_supplier_map.items(): if supplier not in suppliers: del item_supplier_map[item_code] return item_supplier_map def get_material_transfer_vouchers(): return frappe.db.sql_list("""select name from `tabStock Entry` where purpose='Material Transfer' and docstatus=1""")
agpl-3.0
bop/rango
lib/python2.7/site-packages/django/contrib/admin/forms.py
97
1449
from __future__ import unicode_literals from django import forms from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy ERROR_MESSAGE = ugettext_lazy("Please enter the correct %(username)s and password " "for a staff account. Note that both fields may be case-sensitive.") class AdminAuthenticationForm(AuthenticationForm): """ A custom authentication form used in the admin app. """ this_is_the_login_form = forms.BooleanField(widget=forms.HiddenInput, initial=1, error_messages={'required': ugettext_lazy("Please log in again, because your session has expired.")}) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: raise forms.ValidationError(message % { 'username': self.username_field.verbose_name }) elif not self.user_cache.is_active or not self.user_cache.is_staff: raise forms.ValidationError(message % { 'username': self.username_field.verbose_name }) self.check_for_test_cookie() return self.cleaned_data
gpl-2.0
glennw/servo
tests/wpt/web-platform-tests/tools/html5lib/html5lib/tokenizer.py
1710
76929
from __future__ import absolute_import, division, unicode_literals try: chr = unichr # flake8: noqa except NameError: pass from collections import deque from .constants import spaceCharacters from .constants import entities from .constants import asciiLetters, asciiUpper2Lower from .constants import digits, hexDigits, EOF from .constants import tokenTypes, tagTokenTypes from .constants import replacementCharacters from .inputstream import HTMLInputStream from .trie import Trie entitiesTrie = Trie(entities) class HTMLTokenizer(object): """ This class takes care of tokenizing HTML. * self.currentToken Holds the token that is currently being processed. * self.state Holds a reference to the method to be invoked... XXX * self.stream Points to HTMLInputStream object. """ def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True, lowercaseElementName=True, lowercaseAttrName=True, parser=None): self.stream = HTMLInputStream(stream, encoding, parseMeta, useChardet) self.parser = parser # Perform case conversions? self.lowercaseElementName = lowercaseElementName self.lowercaseAttrName = lowercaseAttrName # Setup the initial tokenizer state self.escapeFlag = False self.lastFourChars = [] self.state = self.dataState self.escape = False # The current token being created self.currentToken = None super(HTMLTokenizer, self).__init__() def __iter__(self): """ This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested. """ self.tokenQueue = deque([]) # Start processing. When EOF is reached self.state will return False # instead of True and the loop will terminate. while self.state(): while self.stream.errors: yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)} while self.tokenQueue: yield self.tokenQueue.popleft() def consumeNumberEntity(self, isHex): """This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked. """ allowed = digits radix = 10 if isHex: allowed = hexDigits radix = 16 charStack = [] # Consume all the characters that are in range while making sure we # don't hit an EOF. c = self.stream.char() while c in allowed and c is not EOF: charStack.append(c) c = self.stream.char() # Convert the set of characters consumed to an int. charAsInt = int("".join(charStack), radix) # Certain characters get replaced with others if charAsInt in replacementCharacters: char = replacementCharacters[charAsInt] self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) elif ((0xD800 <= charAsInt <= 0xDFFF) or (charAsInt > 0x10FFFF)): char = "\uFFFD" self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) else: # Should speed up this check somehow (e.g. move the set to a constant) if ((0x0001 <= charAsInt <= 0x0008) or (0x000E <= charAsInt <= 0x001F) or (0x007F <= charAsInt <= 0x009F) or (0xFDD0 <= charAsInt <= 0xFDEF) or charAsInt in frozenset([0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, 0x10FFFF])): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) try: # Try/except needed as UCS-2 Python builds' unichar only works # within the BMP. char = chr(charAsInt) except ValueError: v = charAsInt - 0x10000 char = chr(0xD800 | (v >> 10)) + chr(0xDC00 | (v & 0x3FF)) # Discard the ; if present. Otherwise, put it back on the queue and # invoke parseError on parser. if c != ";": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "numeric-entity-without-semicolon"}) self.stream.unget(c) return char def consumeEntity(self, allowedChar=None, fromAttribute=False): # Initialise to the default output for when no entity is matched output = "&" charStack = [self.stream.char()] if (charStack[0] in spaceCharacters or charStack[0] in (EOF, "<", "&") or (allowedChar is not None and allowedChar == charStack[0])): self.stream.unget(charStack[0]) elif charStack[0] == "#": # Read the next character to see if it's hex or decimal hex = False charStack.append(self.stream.char()) if charStack[-1] in ("x", "X"): hex = True charStack.append(self.stream.char()) # charStack[-1] should be the first digit if (hex and charStack[-1] in hexDigits) \ or (not hex and charStack[-1] in digits): # At least one digit found, so consume the whole number self.stream.unget(charStack[-1]) output = self.consumeNumberEntity(hex) else: # No digits found self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-numeric-entity"}) self.stream.unget(charStack.pop()) output = "&" + "".join(charStack) else: # At this point in the process might have named entity. Entities # are stored in the global variable "entities". # # Consume characters and compare to these to a substring of the # entity names in the list until the substring no longer matches. while (charStack[-1] is not EOF): if not entitiesTrie.has_keys_with_prefix("".join(charStack)): break charStack.append(self.stream.char()) # At this point we have a string that starts with some characters # that may match an entity # Try to find the longest entity the string will match to take care # of &noti for instance. try: entityName = entitiesTrie.longest_prefix("".join(charStack[:-1])) entityLength = len(entityName) except KeyError: entityName = None if entityName is not None: if entityName[-1] != ";": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "named-entity-without-semicolon"}) if (entityName[-1] != ";" and fromAttribute and (charStack[entityLength] in asciiLetters or charStack[entityLength] in digits or charStack[entityLength] == "=")): self.stream.unget(charStack.pop()) output = "&" + "".join(charStack) else: output = entities[entityName] self.stream.unget(charStack.pop()) output += "".join(charStack[entityLength:]) else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-named-entity"}) self.stream.unget(charStack.pop()) output = "&" + "".join(charStack) if fromAttribute: self.currentToken["data"][-1][1] += output else: if output in spaceCharacters: tokenType = "SpaceCharacters" else: tokenType = "Characters" self.tokenQueue.append({"type": tokenTypes[tokenType], "data": output}) def processEntityInAttribute(self, allowedChar): """This method replaces the need for "entityInAttributeValueState". """ self.consumeEntity(allowedChar=allowedChar, fromAttribute=True) def emitCurrentToken(self): """This method is a generic handler for emitting the tags. It also sets the state to "data" because that's what's needed after a token has been emitted. """ token = self.currentToken # Add token to the queue to be yielded if (token["type"] in tagTokenTypes): if self.lowercaseElementName: token["name"] = token["name"].translate(asciiUpper2Lower) if token["type"] == tokenTypes["EndTag"]: if token["data"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "attributes-in-end-tag"}) if token["selfClosing"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "self-closing-flag-on-end-tag"}) self.tokenQueue.append(token) self.state = self.dataState # Below are the various tokenizer states worked out. def dataState(self): data = self.stream.char() if data == "&": self.state = self.entityDataState elif data == "<": self.state = self.tagOpenState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\u0000"}) elif data is EOF: # Tokenization ends. return False elif data in spaceCharacters: # Directly after emitting a token you switch back to the "data # state". At that point spaceCharacters are important so they are # emitted separately. self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data": data + self.stream.charsUntil(spaceCharacters, True)}) # No need to update lastFourChars here, since the first space will # have already been appended to lastFourChars and will have broken # any <!-- or --> sequences else: chars = self.stream.charsUntil(("&", "<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def entityDataState(self): self.consumeEntity() self.state = self.dataState return True def rcdataState(self): data = self.stream.char() if data == "&": self.state = self.characterReferenceInRcdata elif data == "<": self.state = self.rcdataLessThanSignState elif data == EOF: # Tokenization ends. return False elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data in spaceCharacters: # Directly after emitting a token you switch back to the "data # state". At that point spaceCharacters are important so they are # emitted separately. self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data": data + self.stream.charsUntil(spaceCharacters, True)}) # No need to update lastFourChars here, since the first space will # have already been appended to lastFourChars and will have broken # any <!-- or --> sequences else: chars = self.stream.charsUntil(("&", "<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def characterReferenceInRcdata(self): self.consumeEntity() self.state = self.rcdataState return True def rawtextState(self): data = self.stream.char() if data == "<": self.state = self.rawtextLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: # Tokenization ends. return False else: chars = self.stream.charsUntil(("<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def scriptDataState(self): data = self.stream.char() if data == "<": self.state = self.scriptDataLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: # Tokenization ends. return False else: chars = self.stream.charsUntil(("<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def plaintextState(self): data = self.stream.char() if data == EOF: # Tokenization ends. return False elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + self.stream.charsUntil("\u0000")}) return True def tagOpenState(self): data = self.stream.char() if data == "!": self.state = self.markupDeclarationOpenState elif data == "/": self.state = self.closeTagOpenState elif data in asciiLetters: self.currentToken = {"type": tokenTypes["StartTag"], "name": data, "data": [], "selfClosing": False, "selfClosingAcknowledged": False} self.state = self.tagNameState elif data == ">": # XXX In theory it could be something besides a tag name. But # do we really care? self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-tag-name-but-got-right-bracket"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<>"}) self.state = self.dataState elif data == "?": # XXX In theory it could be something besides a tag name. But # do we really care? self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-tag-name-but-got-question-mark"}) self.stream.unget(data) self.state = self.bogusCommentState else: # XXX self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-tag-name"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.dataState return True def closeTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.currentToken = {"type": tokenTypes["EndTag"], "name": data, "data": [], "selfClosing": False} self.state = self.tagNameState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-closing-tag-but-got-right-bracket"}) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-closing-tag-but-got-eof"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.state = self.dataState else: # XXX data can be _'_... self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-closing-tag-but-got-char", "datavars": {"data": data}}) self.stream.unget(data) self.state = self.bogusCommentState return True def tagNameState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeAttributeNameState elif data == ">": self.emitCurrentToken() elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-tag-name"}) self.state = self.dataState elif data == "/": self.state = self.selfClosingStartTagState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["name"] += "\uFFFD" else: self.currentToken["name"] += data # (Don't use charsUntil here, because tag names are # very short and it's faster to not do anything fancy) return True def rcdataLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.rcdataEndTagOpenState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.rcdataState return True def rcdataEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.rcdataEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.rcdataState return True def rcdataEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.rcdataState return True def rawtextLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.rawtextEndTagOpenState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.rawtextState return True def rawtextEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.rawtextEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.rawtextState return True def rawtextEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.rawtextState return True def scriptDataLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.scriptDataEndTagOpenState elif data == "!": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<!"}) self.state = self.scriptDataEscapeStartState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.scriptDataEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEscapeStartState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapeStartDashState else: self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEscapeStartDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapedDashDashState else: self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEscapedState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapedDashState elif data == "<": self.state = self.scriptDataEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: self.state = self.dataState else: chars = self.stream.charsUntil(("<", "-", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def scriptDataEscapedDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapedDashDashState elif data == "<": self.state = self.scriptDataEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataEscapedState elif data == EOF: self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataEscapedState return True def scriptDataEscapedDashDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) elif data == "<": self.state = self.scriptDataEscapedLessThanSignState elif data == ">": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"}) self.state = self.scriptDataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataEscapedState elif data == EOF: self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataEscapedState return True def scriptDataEscapedLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.scriptDataEscapedEndTagOpenState elif data in asciiLetters: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<" + data}) self.temporaryBuffer = data self.state = self.scriptDataDoubleEscapeStartState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataEscapedEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer = data self.state = self.scriptDataEscapedEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataEscapedEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataDoubleEscapeStartState(self): data = self.stream.char() if data in (spaceCharacters | frozenset(("/", ">"))): self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) if self.temporaryBuffer.lower() == "script": self.state = self.scriptDataDoubleEscapedState else: self.state = self.scriptDataEscapedState elif data in asciiLetters: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.temporaryBuffer += data else: self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataDoubleEscapedState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataDoubleEscapedDashState elif data == "<": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.state = self.scriptDataDoubleEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-script-in-script"}) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) return True def scriptDataDoubleEscapedDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataDoubleEscapedDashDashState elif data == "<": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.state = self.scriptDataDoubleEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataDoubleEscapedState elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-script-in-script"}) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataDoubleEscapedState return True def scriptDataDoubleEscapedDashDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) elif data == "<": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.state = self.scriptDataDoubleEscapedLessThanSignState elif data == ">": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"}) self.state = self.scriptDataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataDoubleEscapedState elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-script-in-script"}) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataDoubleEscapedState return True def scriptDataDoubleEscapedLessThanSignState(self): data = self.stream.char() if data == "/": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "/"}) self.temporaryBuffer = "" self.state = self.scriptDataDoubleEscapeEndState else: self.stream.unget(data) self.state = self.scriptDataDoubleEscapedState return True def scriptDataDoubleEscapeEndState(self): data = self.stream.char() if data in (spaceCharacters | frozenset(("/", ">"))): self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) if self.temporaryBuffer.lower() == "script": self.state = self.scriptDataEscapedState else: self.state = self.scriptDataDoubleEscapedState elif data in asciiLetters: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.temporaryBuffer += data else: self.stream.unget(data) self.state = self.scriptDataDoubleEscapedState return True def beforeAttributeNameState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data in asciiLetters: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data == ">": self.emitCurrentToken() elif data == "/": self.state = self.selfClosingStartTagState elif data in ("'", '"', "=", "<"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-character-in-attribute-name"}) self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"].append(["\uFFFD", ""]) self.state = self.attributeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-name-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState return True def attributeNameState(self): data = self.stream.char() leavingThisState = True emitToken = False if data == "=": self.state = self.beforeAttributeValueState elif data in asciiLetters: self.currentToken["data"][-1][0] += data +\ self.stream.charsUntil(asciiLetters, True) leavingThisState = False elif data == ">": # XXX If we emit here the attributes are converted to a dict # without being checked and when the code below runs we error # because data is a dict not a list emitToken = True elif data in spaceCharacters: self.state = self.afterAttributeNameState elif data == "/": self.state = self.selfClosingStartTagState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][0] += "\uFFFD" leavingThisState = False elif data in ("'", '"', "<"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-character-in-attribute-name"}) self.currentToken["data"][-1][0] += data leavingThisState = False elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-name"}) self.state = self.dataState else: self.currentToken["data"][-1][0] += data leavingThisState = False if leavingThisState: # Attributes are not dropped at this stage. That happens when the # start tag token is emitted so values can still be safely appended # to attributes, but we do want to report the parse error in time. if self.lowercaseAttrName: self.currentToken["data"][-1][0] = ( self.currentToken["data"][-1][0].translate(asciiUpper2Lower)) for name, value in self.currentToken["data"][:-1]: if self.currentToken["data"][-1][0] == name: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "duplicate-attribute"}) break # XXX Fix for above XXX if emitToken: self.emitCurrentToken() return True def afterAttributeNameState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data == "=": self.state = self.beforeAttributeValueState elif data == ">": self.emitCurrentToken() elif data in asciiLetters: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data == "/": self.state = self.selfClosingStartTagState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"].append(["\uFFFD", ""]) self.state = self.attributeNameState elif data in ("'", '"', "<"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-character-after-attribute-name"}) self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-end-of-tag-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState return True def beforeAttributeValueState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data == "\"": self.state = self.attributeValueDoubleQuotedState elif data == "&": self.state = self.attributeValueUnQuotedState self.stream.unget(data) elif data == "'": self.state = self.attributeValueSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-value-but-got-right-bracket"}) self.emitCurrentToken() elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" self.state = self.attributeValueUnQuotedState elif data in ("=", "<", "`"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "equals-in-unquoted-attribute-value"}) self.currentToken["data"][-1][1] += data self.state = self.attributeValueUnQuotedState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-value-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data self.state = self.attributeValueUnQuotedState return True def attributeValueDoubleQuotedState(self): data = self.stream.char() if data == "\"": self.state = self.afterAttributeValueState elif data == "&": self.processEntityInAttribute('"') elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-value-double-quote"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data +\ self.stream.charsUntil(("\"", "&", "\u0000")) return True def attributeValueSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterAttributeValueState elif data == "&": self.processEntityInAttribute("'") elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-value-single-quote"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data +\ self.stream.charsUntil(("'", "&", "\u0000")) return True def attributeValueUnQuotedState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeAttributeNameState elif data == "&": self.processEntityInAttribute(">") elif data == ">": self.emitCurrentToken() elif data in ('"', "'", "=", "<", "`"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-character-in-unquoted-attribute-value"}) self.currentToken["data"][-1][1] += data elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-value-no-quotes"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data + self.stream.charsUntil( frozenset(("&", ">", '"', "'", "=", "<", "`", "\u0000")) | spaceCharacters) return True def afterAttributeValueState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeAttributeNameState elif data == ">": self.emitCurrentToken() elif data == "/": self.state = self.selfClosingStartTagState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-EOF-after-attribute-value"}) self.stream.unget(data) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-character-after-attribute-value"}) self.stream.unget(data) self.state = self.beforeAttributeNameState return True def selfClosingStartTagState(self): data = self.stream.char() if data == ">": self.currentToken["selfClosing"] = True self.emitCurrentToken() elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-EOF-after-solidus-in-tag"}) self.stream.unget(data) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-character-after-solidus-in-tag"}) self.stream.unget(data) self.state = self.beforeAttributeNameState return True def bogusCommentState(self): # Make a new comment token and give it as value all the characters # until the first > or EOF (charsUntil checks for EOF automatically) # and emit it. data = self.stream.charsUntil(">") data = data.replace("\u0000", "\uFFFD") self.tokenQueue.append( {"type": tokenTypes["Comment"], "data": data}) # Eat the character directly after the bogus comment which is either a # ">" or an EOF. self.stream.char() self.state = self.dataState return True def markupDeclarationOpenState(self): charStack = [self.stream.char()] if charStack[-1] == "-": charStack.append(self.stream.char()) if charStack[-1] == "-": self.currentToken = {"type": tokenTypes["Comment"], "data": ""} self.state = self.commentStartState return True elif charStack[-1] in ('d', 'D'): matched = True for expected in (('o', 'O'), ('c', 'C'), ('t', 'T'), ('y', 'Y'), ('p', 'P'), ('e', 'E')): charStack.append(self.stream.char()) if charStack[-1] not in expected: matched = False break if matched: self.currentToken = {"type": tokenTypes["Doctype"], "name": "", "publicId": None, "systemId": None, "correct": True} self.state = self.doctypeState return True elif (charStack[-1] == "[" and self.parser is not None and self.parser.tree.openElements and self.parser.tree.openElements[-1].namespace != self.parser.tree.defaultNamespace): matched = True for expected in ["C", "D", "A", "T", "A", "["]: charStack.append(self.stream.char()) if charStack[-1] != expected: matched = False break if matched: self.state = self.cdataSectionState return True self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-dashes-or-doctype"}) while charStack: self.stream.unget(charStack.pop()) self.state = self.bogusCommentState return True def commentStartState(self): data = self.stream.char() if data == "-": self.state = self.commentStartDashState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "incorrect-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += data self.state = self.commentState return True def commentStartDashState(self): data = self.stream.char() if data == "-": self.state = self.commentEndState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "-\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "incorrect-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += "-" + data self.state = self.commentState return True def commentState(self): data = self.stream.char() if data == "-": self.state = self.commentEndDashState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += data + \ self.stream.charsUntil(("-", "\u0000")) return True def commentEndDashState(self): data = self.stream.char() if data == "-": self.state = self.commentEndState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "-\uFFFD" self.state = self.commentState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment-end-dash"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += "-" + data self.state = self.commentState return True def commentEndState(self): data = self.stream.char() if data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "--\uFFFD" self.state = self.commentState elif data == "!": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-bang-after-double-dash-in-comment"}) self.state = self.commentEndBangState elif data == "-": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-dash-after-double-dash-in-comment"}) self.currentToken["data"] += data elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment-double-dash"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: # XXX self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-comment"}) self.currentToken["data"] += "--" + data self.state = self.commentState return True def commentEndBangState(self): data = self.stream.char() if data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "-": self.currentToken["data"] += "--!" self.state = self.commentEndDashState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "--!\uFFFD" self.state = self.commentState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment-end-bang-state"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += "--!" + data self.state = self.commentState return True def doctypeState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeDoctypeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-doctype-name-but-got-eof"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "need-space-after-doctype"}) self.stream.unget(data) self.state = self.beforeDoctypeNameState return True def beforeDoctypeNameState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-doctype-name-but-got-right-bracket"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["name"] = "\uFFFD" self.state = self.doctypeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-doctype-name-but-got-eof"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["name"] = data self.state = self.doctypeNameState return True def doctypeNameState(self): data = self.stream.char() if data in spaceCharacters: self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) self.state = self.afterDoctypeNameState elif data == ">": self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["name"] += "\uFFFD" self.state = self.doctypeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype-name"}) self.currentToken["correct"] = False self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["name"] += data return True def afterDoctypeNameState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.currentToken["correct"] = False self.stream.unget(data) self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: if data in ("p", "P"): matched = True for expected in (("u", "U"), ("b", "B"), ("l", "L"), ("i", "I"), ("c", "C")): data = self.stream.char() if data not in expected: matched = False break if matched: self.state = self.afterDoctypePublicKeywordState return True elif data in ("s", "S"): matched = True for expected in (("y", "Y"), ("s", "S"), ("t", "T"), ("e", "E"), ("m", "M")): data = self.stream.char() if data not in expected: matched = False break if matched: self.state = self.afterDoctypeSystemKeywordState return True # All the characters read before the current 'data' will be # [a-zA-Z], so they're garbage in the bogus doctype and can be # discarded; only the latest character might be '>' or EOF # and needs to be ungetted self.stream.unget(data) self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-space-or-right-bracket-in-doctype", "datavars": {"data": data}}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def afterDoctypePublicKeywordState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeDoctypePublicIdentifierState elif data in ("'", '"'): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.stream.unget(data) self.state = self.beforeDoctypePublicIdentifierState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.stream.unget(data) self.state = self.beforeDoctypePublicIdentifierState return True def beforeDoctypePublicIdentifierState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == "\"": self.currentToken["publicId"] = "" self.state = self.doctypePublicIdentifierDoubleQuotedState elif data == "'": self.currentToken["publicId"] = "" self.state = self.doctypePublicIdentifierSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def doctypePublicIdentifierDoubleQuotedState(self): data = self.stream.char() if data == "\"": self.state = self.afterDoctypePublicIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["publicId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["publicId"] += data return True def doctypePublicIdentifierSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterDoctypePublicIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["publicId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["publicId"] += data return True def afterDoctypePublicIdentifierState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.betweenDoctypePublicAndSystemIdentifiersState elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == '"': self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierDoubleQuotedState elif data == "'": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierSingleQuotedState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def betweenDoctypePublicAndSystemIdentifiersState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == '"': self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierDoubleQuotedState elif data == "'": self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierSingleQuotedState elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def afterDoctypeSystemKeywordState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeDoctypeSystemIdentifierState elif data in ("'", '"'): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.stream.unget(data) self.state = self.beforeDoctypeSystemIdentifierState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.stream.unget(data) self.state = self.beforeDoctypeSystemIdentifierState return True def beforeDoctypeSystemIdentifierState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == "\"": self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierDoubleQuotedState elif data == "'": self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def doctypeSystemIdentifierDoubleQuotedState(self): data = self.stream.char() if data == "\"": self.state = self.afterDoctypeSystemIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["systemId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["systemId"] += data return True def doctypeSystemIdentifierSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterDoctypeSystemIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["systemId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["systemId"] += data return True def afterDoctypeSystemIdentifierState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.state = self.bogusDoctypeState return True def bogusDoctypeState(self): data = self.stream.char() if data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: # XXX EMIT self.stream.unget(data) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: pass return True def cdataSectionState(self): data = [] while True: data.append(self.stream.charsUntil("]")) data.append(self.stream.charsUntil(">")) char = self.stream.char() if char == EOF: break else: assert char == ">" if data[-1][-2:] == "]]": data[-1] = data[-1][:-2] break else: data.append(char) data = "".join(data) # Deal with null here rather than in the parser nullCount = data.count("\u0000") if nullCount > 0: for i in range(nullCount): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) data = data.replace("\u0000", "\uFFFD") if data: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.dataState return True
mpl-2.0
SANBI-SA/tools-iuc
deprecated/tools/gatk2/gatk2_wrapper.py
29
7403
#!/usr/bin/env python # David Hoover, based on gatk by Dan Blankenberg """ A wrapper script for running the GenomeAnalysisTK.jar commands. """ import optparse import os import shutil import subprocess import sys import tempfile from binascii import unhexlify GALAXY_EXT_TO_GATK_EXT = { 'gatk_interval': 'intervals', 'bam_index': 'bam.bai', 'gatk_dbsnp': 'dbSNP', 'picard_interval_list': 'interval_list' } # items not listed here will use the galaxy extension as-is GALAXY_EXT_TO_GATK_FILE_TYPE = GALAXY_EXT_TO_GATK_EXT # for now, these are the same, but could be different if needed DEFAULT_GATK_PREFIX = "gatk_file" CHUNK_SIZE = 2**20 # 1mb def cleanup_before_exit( tmp_dir ): if tmp_dir and os.path.exists( tmp_dir ): shutil.rmtree( tmp_dir ) def gatk_filename_from_galaxy( galaxy_filename, galaxy_ext, target_dir=None, prefix=None ): suffix = GALAXY_EXT_TO_GATK_EXT.get( galaxy_ext, galaxy_ext ) if prefix is None: prefix = DEFAULT_GATK_PREFIX if target_dir is None: target_dir = os.getcwd() gatk_filename = os.path.join( target_dir, "%s.%s" % ( prefix, suffix ) ) os.symlink( galaxy_filename, gatk_filename ) return gatk_filename def gatk_filetype_argument_substitution( argument, galaxy_ext ): return argument % dict( file_type=GALAXY_EXT_TO_GATK_FILE_TYPE.get( galaxy_ext, galaxy_ext ) ) def open_file_from_option( filename, mode='rb' ): if filename: return open( filename, mode=mode ) return None def html_report_from_directory( html_out, dir ): html_out.write( '<html>\n<head>\n<title>Galaxy - GATK Output</title>\n</head>\n<body>\n<p/>\n<ul>\n' ) for fname in sorted( os.listdir( dir ) ): html_out.write( '<li><a href="%s">%s</a></li>\n' % ( fname, fname ) ) html_out.write( '</ul>\n</body>\n</html>\n' ) def index_bam_files( bam_filenames ): for bam_filename in bam_filenames: bam_index_filename = "%s.bai" % bam_filename if not os.path.exists( bam_index_filename ): # need to index this bam file stderr_name = tempfile.NamedTemporaryFile( prefix="bam_index_stderr" ).name command = 'samtools index %s %s' % ( bam_filename, bam_index_filename ) try: subprocess.check_call( args=command, shell=True, stderr=open( stderr_name, 'wb' ) ) except: for line in open( stderr_name ): print >> sys.stderr, line raise Exception( "Error indexing BAM file" ) finally: os.unlink( stderr_name ) def __main__(): # Parse Command Line parser = optparse.OptionParser() parser.add_option( '-p', '--pass_through', dest='pass_through_options', action='append', type="string", help='These options are passed through directly to GATK, without any modification.' ) parser.add_option( '-o', '--pass_through_options', dest='pass_through_options_encoded', action='append', type="string", help='These options are passed through directly to GATK, with decoding from binascii.unhexlify.' ) parser.add_option( '-d', '--dataset', dest='datasets', action='append', type="string", nargs=4, help='"-argument" "original_filename" "galaxy_filetype" "name_prefix"' ) parser.add_option( '', '--max_jvm_heap', dest='max_jvm_heap', action='store', type="string", default=None, help='If specified, the maximum java virtual machine heap size will be set to the provide value.' ) parser.add_option( '', '--max_jvm_heap_fraction', dest='max_jvm_heap_fraction', action='store', type="int", default=None, help='If specified, the maximum java virtual machine heap size will be set to the provide value as a fraction of total physical memory.' ) parser.add_option( '', '--stdout', dest='stdout', action='store', type="string", default=None, help='If specified, the output of stdout will be written to this file.' ) parser.add_option( '', '--stderr', dest='stderr', action='store', type="string", default=None, help='If specified, the output of stderr will be written to this file.' ) parser.add_option( '', '--html_report_from_directory', dest='html_report_from_directory', action='append', type="string", nargs=2, help='"Target HTML File" "Directory"') parser.add_option( '-e', '--phone_home', dest='phone_home', action='store', type="string", default='STANDARD', help='What kind of GATK run report should we generate(NO_ET|STANDARD|STDOUT)' ) parser.add_option( '-K', '--gatk_key', dest='gatk_key', action='store', type="string", default=None, help='What kind of GATK run report should we generate(NO_ET|STANDARD|STDOUT)' ) (options, args) = parser.parse_args() if options.pass_through_options: cmd = ' '.join( options.pass_through_options ) else: cmd = '' if options.pass_through_options_encoded: cmd = '%s %s' % ( cmd, ' '.join( map( unhexlify, options.pass_through_options_encoded ) ) ) if options.max_jvm_heap is not None: cmd = cmd.replace( 'java ', 'java -Xmx%s ' % ( options.max_jvm_heap ), 1 ) elif options.max_jvm_heap_fraction is not None: cmd = cmd.replace( 'java ', 'java -XX:DefaultMaxRAMFraction=%s -XX:+UseParallelGC ' % ( options.max_jvm_heap_fraction ), 1 ) bam_filenames = [] tmp_dir = tempfile.mkdtemp( prefix='tmp-gatk-' ) try: if options.datasets: for ( dataset_arg, filename, galaxy_ext, prefix ) in options.datasets: gatk_filename = gatk_filename_from_galaxy( filename, galaxy_ext, target_dir=tmp_dir, prefix=prefix ) if dataset_arg: cmd = '%s %s "%s"' % ( cmd, gatk_filetype_argument_substitution( dataset_arg, galaxy_ext ), gatk_filename ) if galaxy_ext == "bam": bam_filenames.append( gatk_filename ) if galaxy_ext == 'fasta': subprocess.check_call( 'samtools faidx "%s"' % gatk_filename, shell=True ) subprocess.check_call( 'java -jar %s R=%s O=%s QUIET=true' % ( os.path.join(os.environ['JAVA_JAR_PATH'], 'CreateSequenceDictionary.jar'), gatk_filename, os.path.splitext(gatk_filename)[0] + '.dict' ), shell=True ) index_bam_files( bam_filenames ) # set up stdout and stderr output options stdout = open_file_from_option( options.stdout, mode='wb' ) stderr = open_file_from_option( options.stderr, mode='wb' ) # if no stderr file is specified, we'll use our own if stderr is None: stderr = tempfile.NamedTemporaryFile( prefix="gatk-stderr-", dir=tmp_dir ) proc = subprocess.Popen( args=cmd, stdout=stdout, stderr=stderr, shell=True, cwd=tmp_dir ) return_code = proc.wait() if return_code: stderr_target = sys.stderr else: stderr_target = sys.stdout stderr.flush() stderr.seek(0) while True: chunk = stderr.read( CHUNK_SIZE ) if chunk: stderr_target.write( chunk ) else: break stderr.close() finally: cleanup_before_exit( tmp_dir ) # generate html reports if options.html_report_from_directory: for ( html_filename, html_dir ) in options.html_report_from_directory: html_report_from_directory( open( html_filename, 'wb' ), html_dir ) if __name__ == "__main__": __main__()
mit
ntt-sic/glance
glance/registry/api/v2/rpc.py
2
1751
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ RPC Controller """ from oslo.config import cfg from glance.common import rpc from glance.common import wsgi import glance.db import glance.openstack.common.log as logging LOG = logging.getLogger(__name__) CONF = cfg.CONF class Controller(rpc.Controller): def __init__(self, raise_exc=False): super(Controller, self).__init__(raise_exc) # NOTE(flaper87): Avoid using registry's db # driver for the registry service. It would # end up in an infinite loop. if CONF.data_api == "glance.db.registry.api": msg = _("Registry service can't use %s") % CONF.data_api raise RuntimeError(msg) # NOTE(flaper87): Register the # db_api as a resource to expose. db_api = glance.db.get_api() db_api.setup_db_env() self.register(glance.db.unwrap(db_api)) def create_resource(): """Images resource factory method.""" deserializer = rpc.RPCJSONDeserializer() serializer = rpc.RPCJSONSerializer() return wsgi.Resource(Controller(), deserializer, serializer)
apache-2.0
ssbarnea/ansible
lib/ansible/module_utils/facts/namespace.py
172
2366
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # (c) 2017 Red Hat Inc. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type class FactNamespace: def __init__(self, namespace_name): self.namespace_name = namespace_name def transform(self, name): '''Take a text name, and transforms it as needed (add a namespace prefix, etc)''' return name def _underscore(self, name): return name.replace('-', '_') class PrefixFactNamespace(FactNamespace): def __init__(self, namespace_name, prefix=None): super(PrefixFactNamespace, self).__init__(namespace_name) self.prefix = prefix def transform(self, name): new_name = self._underscore(name) return '%s%s' % (self.prefix, new_name)
gpl-3.0
40123142/2015cd_midterm2
static/Brython3.1.1-20150328-091302/Lib/opcode.py
714
5442
""" opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", "haslocal", "hascompare", "hasfree", "opname", "opmap", "HAVE_ARGUMENT", "EXTENDED_ARG", "hasnargs"] # It's a chicken-and-egg I'm afraid: # We're imported before _opcode's made. # With exception unheeded # (stack_effect is not needed) # Both our chickens and eggs are allayed. # --Larry Hastings, 2013/11/23 try: from _opcode import stack_effect __all__.append('stack_effect') except ImportError: pass cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', 'is not', 'exception match', 'BAD') hasconst = [] hasname = [] hasjrel = [] hasjabs = [] haslocal = [] hascompare = [] hasfree = [] hasnargs = [] opmap = {} opname = [''] * 256 for op in range(256): opname[op] = '<%r>' % (op,) del op def def_op(name, op): opname[op] = name opmap[name] = op def name_op(name, op): def_op(name, op) hasname.append(op) def jrel_op(name, op): def_op(name, op) hasjrel.append(op) def jabs_op(name, op): def_op(name, op) hasjabs.append(op) # Instruction opcodes for compiled code # Blank lines correspond to available opcodes def_op('POP_TOP', 1) def_op('ROT_TWO', 2) def_op('ROT_THREE', 3) def_op('DUP_TOP', 4) def_op('DUP_TOP_TWO', 5) def_op('NOP', 9) def_op('UNARY_POSITIVE', 10) def_op('UNARY_NEGATIVE', 11) def_op('UNARY_NOT', 12) def_op('UNARY_INVERT', 15) def_op('BINARY_POWER', 19) def_op('BINARY_MULTIPLY', 20) def_op('BINARY_MODULO', 22) def_op('BINARY_ADD', 23) def_op('BINARY_SUBTRACT', 24) def_op('BINARY_SUBSCR', 25) def_op('BINARY_FLOOR_DIVIDE', 26) def_op('BINARY_TRUE_DIVIDE', 27) def_op('INPLACE_FLOOR_DIVIDE', 28) def_op('INPLACE_TRUE_DIVIDE', 29) def_op('STORE_MAP', 54) def_op('INPLACE_ADD', 55) def_op('INPLACE_SUBTRACT', 56) def_op('INPLACE_MULTIPLY', 57) def_op('INPLACE_MODULO', 59) def_op('STORE_SUBSCR', 60) def_op('DELETE_SUBSCR', 61) def_op('BINARY_LSHIFT', 62) def_op('BINARY_RSHIFT', 63) def_op('BINARY_AND', 64) def_op('BINARY_XOR', 65) def_op('BINARY_OR', 66) def_op('INPLACE_POWER', 67) def_op('GET_ITER', 68) def_op('PRINT_EXPR', 70) def_op('LOAD_BUILD_CLASS', 71) def_op('YIELD_FROM', 72) def_op('INPLACE_LSHIFT', 75) def_op('INPLACE_RSHIFT', 76) def_op('INPLACE_AND', 77) def_op('INPLACE_XOR', 78) def_op('INPLACE_OR', 79) def_op('BREAK_LOOP', 80) def_op('WITH_CLEANUP', 81) def_op('RETURN_VALUE', 83) def_op('IMPORT_STAR', 84) def_op('YIELD_VALUE', 86) def_op('POP_BLOCK', 87) def_op('END_FINALLY', 88) def_op('POP_EXCEPT', 89) HAVE_ARGUMENT = 90 # Opcodes from here have an argument: name_op('STORE_NAME', 90) # Index in name list name_op('DELETE_NAME', 91) # "" def_op('UNPACK_SEQUENCE', 92) # Number of tuple items jrel_op('FOR_ITER', 93) def_op('UNPACK_EX', 94) name_op('STORE_ATTR', 95) # Index in name list name_op('DELETE_ATTR', 96) # "" name_op('STORE_GLOBAL', 97) # "" name_op('DELETE_GLOBAL', 98) # "" def_op('LOAD_CONST', 100) # Index in const list hasconst.append(100) name_op('LOAD_NAME', 101) # Index in name list def_op('BUILD_TUPLE', 102) # Number of tuple items def_op('BUILD_LIST', 103) # Number of list items def_op('BUILD_SET', 104) # Number of set items def_op('BUILD_MAP', 105) # Number of dict entries (upto 255) name_op('LOAD_ATTR', 106) # Index in name list def_op('COMPARE_OP', 107) # Comparison operator hascompare.append(107) name_op('IMPORT_NAME', 108) # Index in name list name_op('IMPORT_FROM', 109) # Index in name list jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip jabs_op('JUMP_IF_FALSE_OR_POP', 111) # Target byte offset from beginning of code jabs_op('JUMP_IF_TRUE_OR_POP', 112) # "" jabs_op('JUMP_ABSOLUTE', 113) # "" jabs_op('POP_JUMP_IF_FALSE', 114) # "" jabs_op('POP_JUMP_IF_TRUE', 115) # "" name_op('LOAD_GLOBAL', 116) # Index in name list jabs_op('CONTINUE_LOOP', 119) # Target address jrel_op('SETUP_LOOP', 120) # Distance to target address jrel_op('SETUP_EXCEPT', 121) # "" jrel_op('SETUP_FINALLY', 122) # "" def_op('LOAD_FAST', 124) # Local variable number haslocal.append(124) def_op('STORE_FAST', 125) # Local variable number haslocal.append(125) def_op('DELETE_FAST', 126) # Local variable number haslocal.append(126) def_op('RAISE_VARARGS', 130) # Number of raise arguments (1, 2, or 3) def_op('CALL_FUNCTION', 131) # #args + (#kwargs << 8) hasnargs.append(131) def_op('MAKE_FUNCTION', 132) # Number of args with default values def_op('BUILD_SLICE', 133) # Number of items def_op('MAKE_CLOSURE', 134) def_op('LOAD_CLOSURE', 135) hasfree.append(135) def_op('LOAD_DEREF', 136) hasfree.append(136) def_op('STORE_DEREF', 137) hasfree.append(137) def_op('DELETE_DEREF', 138) hasfree.append(138) def_op('CALL_FUNCTION_VAR', 140) # #args + (#kwargs << 8) hasnargs.append(140) def_op('CALL_FUNCTION_KW', 141) # #args + (#kwargs << 8) hasnargs.append(141) def_op('CALL_FUNCTION_VAR_KW', 142) # #args + (#kwargs << 8) hasnargs.append(142) jrel_op('SETUP_WITH', 143) def_op('LIST_APPEND', 145) def_op('SET_ADD', 146) def_op('MAP_ADD', 147) def_op('LOAD_CLASSDEREF', 148) hasfree.append(148) def_op('EXTENDED_ARG', 144) EXTENDED_ARG = 144 del def_op, name_op, jrel_op, jabs_op
gpl-2.0
abelx/googletest
test/gtest_help_test.py
2968
5856
#!/usr/bin/env python # # Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Tests the --help flag of Google C++ Testing Framework. SYNOPSIS gtest_help_test.py --build_dir=BUILD/DIR # where BUILD/DIR contains the built gtest_help_test_ file. gtest_help_test.py """ __author__ = 'wan@google.com (Zhanyong Wan)' import os import re import gtest_test_utils IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_') FLAG_PREFIX = '--gtest_' DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style' STREAM_RESULT_TO_FLAG = FLAG_PREFIX + 'stream_result_to' UNKNOWN_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing' LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', LIST_TESTS_FLAG), re.sub('^--', '/', LIST_TESTS_FLAG), re.sub('_', '-', LIST_TESTS_FLAG)] INTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing' SUPPORTS_DEATH_TESTS = "DeathTest" in gtest_test_utils.Subprocess( [PROGRAM_PATH, LIST_TESTS_FLAG]).output # The help message must match this regex. HELP_REGEX = re.compile( FLAG_PREFIX + r'list_tests.*' + FLAG_PREFIX + r'filter=.*' + FLAG_PREFIX + r'also_run_disabled_tests.*' + FLAG_PREFIX + r'repeat=.*' + FLAG_PREFIX + r'shuffle.*' + FLAG_PREFIX + r'random_seed=.*' + FLAG_PREFIX + r'color=.*' + FLAG_PREFIX + r'print_time.*' + FLAG_PREFIX + r'output=.*' + FLAG_PREFIX + r'break_on_failure.*' + FLAG_PREFIX + r'throw_on_failure.*' + FLAG_PREFIX + r'catch_exceptions=0.*', re.DOTALL) def RunWithFlag(flag): """Runs gtest_help_test_ with the given flag. Returns: the exit code and the text output as a tuple. Args: flag: the command-line flag to pass to gtest_help_test_, or None. """ if flag is None: command = [PROGRAM_PATH] else: command = [PROGRAM_PATH, flag] child = gtest_test_utils.Subprocess(command) return child.exit_code, child.output class GTestHelpTest(gtest_test_utils.TestCase): """Tests the --help flag and its equivalent forms.""" def TestHelpFlag(self, flag): """Verifies correct behavior when help flag is specified. The right message must be printed and the tests must skipped when the given flag is specified. Args: flag: A flag to pass to the binary or None. """ exit_code, output = RunWithFlag(flag) self.assertEquals(0, exit_code) self.assert_(HELP_REGEX.search(output), output) if IS_LINUX: self.assert_(STREAM_RESULT_TO_FLAG in output, output) else: self.assert_(STREAM_RESULT_TO_FLAG not in output, output) if SUPPORTS_DEATH_TESTS and not IS_WINDOWS: self.assert_(DEATH_TEST_STYLE_FLAG in output, output) else: self.assert_(DEATH_TEST_STYLE_FLAG not in output, output) def TestNonHelpFlag(self, flag): """Verifies correct behavior when no help flag is specified. Verifies that when no help flag is specified, the tests are run and the help message is not printed. Args: flag: A flag to pass to the binary or None. """ exit_code, output = RunWithFlag(flag) self.assert_(exit_code != 0) self.assert_(not HELP_REGEX.search(output), output) def testPrintsHelpWithFullFlag(self): self.TestHelpFlag('--help') def testPrintsHelpWithShortFlag(self): self.TestHelpFlag('-h') def testPrintsHelpWithQuestionFlag(self): self.TestHelpFlag('-?') def testPrintsHelpWithWindowsStyleQuestionFlag(self): self.TestHelpFlag('/?') def testPrintsHelpWithUnrecognizedGoogleTestFlag(self): self.TestHelpFlag(UNKNOWN_FLAG) def testPrintsHelpWithIncorrectFlagStyle(self): for incorrect_flag in INCORRECT_FLAG_VARIANTS: self.TestHelpFlag(incorrect_flag) def testRunsTestsWithoutHelpFlag(self): """Verifies that when no help flag is specified, the tests are run and the help message is not printed.""" self.TestNonHelpFlag(None) def testRunsTestsWithGtestInternalFlag(self): """Verifies that the tests are run and no help message is printed when a flag starting with Google Test prefix and 'internal_' is supplied.""" self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING) if __name__ == '__main__': gtest_test_utils.Main()
bsd-3-clause
Godmaster49/mtasa-blue
vendor/google-breakpad/src/tools/gyp/test/defines/gyptest-defines-env.py
501
1874
#!/usr/bin/env python # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies build of an executable with C++ define specified by a gyp define. """ import os import TestGyp test = TestGyp.TestGyp() # With the value only given in environment, it should be used. try: os.environ['GYP_DEFINES'] = 'value=10' test.run_gyp('defines-env.gyp') finally: del os.environ['GYP_DEFINES'] test.build('defines-env.gyp') expect = """\ VALUE is 10 """ test.run_built_executable('defines', stdout=expect) # With the value given in both command line and environment, # command line should take precedence. try: os.environ['GYP_DEFINES'] = 'value=20' test.run_gyp('defines-env.gyp', '-Dvalue=25') finally: del os.environ['GYP_DEFINES'] test.sleep() test.touch('defines.c') test.build('defines-env.gyp') expect = """\ VALUE is 25 """ test.run_built_executable('defines', stdout=expect) # With the value only given in environment, it should be ignored if # --ignore-environment is specified. try: os.environ['GYP_DEFINES'] = 'value=30' test.run_gyp('defines-env.gyp', '--ignore-environment') finally: del os.environ['GYP_DEFINES'] test.sleep() test.touch('defines.c') test.build('defines-env.gyp') expect = """\ VALUE is 5 """ test.run_built_executable('defines', stdout=expect) # With the value given in both command line and environment, and # --ignore-environment also specified, command line should still be used. try: os.environ['GYP_DEFINES'] = 'value=40' test.run_gyp('defines-env.gyp', '--ignore-environment', '-Dvalue=45') finally: del os.environ['GYP_DEFINES'] test.sleep() test.touch('defines.c') test.build('defines-env.gyp') expect = """\ VALUE is 45 """ test.run_built_executable('defines', stdout=expect) test.pass_test()
gpl-3.0
AlexTMjugador/mtasa-blue
vendor/google-breakpad/src/third_party/protobuf/protobuf/gtest/test/gtest_uninitialized_test.py
2901
2480
#!/usr/bin/env python # # Copyright 2008, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Verifies that Google Test warns the user when not initialized properly.""" __author__ = 'wan@google.com (Zhanyong Wan)' import gtest_test_utils COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_') def Assert(condition): if not condition: raise AssertionError def AssertEq(expected, actual): if expected != actual: print 'Expected: %s' % (expected,) print ' Actual: %s' % (actual,) raise AssertionError def TestExitCodeAndOutput(command): """Runs the given command and verifies its exit code and output.""" # Verifies that 'command' exits with code 1. p = gtest_test_utils.Subprocess(command) Assert(p.exited) AssertEq(1, p.exit_code) Assert('InitGoogleTest' in p.output) class GTestUninitializedTest(gtest_test_utils.TestCase): def testExitCodeAndOutput(self): TestExitCodeAndOutput(COMMAND) if __name__ == '__main__': gtest_test_utils.Main()
gpl-3.0
boundlessgeo/QGIS
python/console/console_settings.py
32
28058
# -*- coding:utf-8 -*- """ /*************************************************************************** Python Console for QGIS ------------------- begin : 2012-09-10 copyright : (C) 2012 by Salvatore Larosa email : lrssvtml (at) gmail (dot) com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ Some portions of code were taken from https://code.google.com/p/pydee/ """ from qgis.PyQt.QtCore import QCoreApplication, QSize, Qt from qgis.PyQt.QtWidgets import QDialog, QFileDialog, QMessageBox, QTableWidgetItem from qgis.PyQt.QtGui import QIcon, QFont, QColor, QFontDatabase from qgis.core import QgsSettings from .console_compile_apis import PrepareAPIDialog from .ui_console_settings import Ui_SettingsDialogPythonConsole class optionsDialog(QDialog, Ui_SettingsDialogPythonConsole): DEFAULT_COLOR = "#4d4d4c" KEYWORD_COLOR = "#8959a8" CLASS_COLOR = "#4271ae" METHOD_COLOR = "#4271ae" DECORATION_COLOR = "#3e999f" NUMBER_COLOR = "#c82829" COMMENT_COLOR = "#8e908c" COMMENT_BLOCK_COLOR = "#8e908c" BACKGROUND_COLOR = "#ffffff" CURSOR_COLOR = "#636363" CARET_LINE_COLOR = "#efefef" SINGLE_QUOTE_COLOR = "#718c00" DOUBLE_QUOTE_COLOR = "#718c00" TRIPLE_SINGLE_QUOTE_COLOR = "#eab700" TRIPLE_DOUBLE_QUOTE_COLOR = "#eab700" MARGIN_BACKGROUND_COLOR = "#efefef" MARGIN_FOREGROUND_COLOR = "#636363" SELECTION_BACKGROUND_COLOR = "#d7d7d7" SELECTION_FOREGROUND_COLOR = "#303030" MATCHED_BRACE_BACKGROUND_COLOR = "#b7f907" MATCHED_BRACE_FOREGROUND_COLOR = "#303030" EDGE_COLOR = "#efefef" FOLD_COLOR = "#efefef" ERROR_COLOR = "#e31a1c" def __init__(self, parent): QDialog.__init__(self, parent) self.setWindowTitle(QCoreApplication.translate( "SettingsDialogPythonConsole", "Python Console Settings")) self.parent = parent self.setupUi(self) self.listPath = [] self.lineEdit.setReadOnly(True) self.restoreSettings() self.initialCheck() self.addAPIpath.setIcon(QIcon(":/images/themes/default/symbologyAdd.svg")) self.addAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Add API path")) self.removeAPIpath.setIcon(QIcon(":/images/themes/default/symbologyRemove.svg")) self.removeAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Remove API path")) self.preloadAPI.stateChanged.connect(self.initialCheck) self.addAPIpath.clicked.connect(self.loadAPIFile) self.removeAPIpath.clicked.connect(self.removeAPI) self.compileAPIs.clicked.connect(self._prepareAPI) self.resetFontColor.setIcon(QIcon(":/images/themes/default/mActionUndo.svg")) self.resetFontColor.setIconSize(QSize(18, 18)) self.resetFontColorEditor.setIcon(QIcon(":/images/themes/default/mActionUndo.svg")) self.resetFontColorEditor.setIconSize(QSize(18, 18)) self.resetFontColor.clicked.connect(self._resetFontColor) self.resetFontColorEditor.clicked.connect(self._resetFontColorEditor) def initialCheck(self): if self.preloadAPI.isChecked(): self.enableDisable(False) else: self.enableDisable(True) def enableDisable(self, value): self.tableWidget.setEnabled(value) self.addAPIpath.setEnabled(value) self.removeAPIpath.setEnabled(value) self.groupBoxPreparedAPI.setEnabled(value) def loadAPIFile(self): settings = QgsSettings() lastDirPath = settings.value("pythonConsole/lastDirAPIPath", "", type=str) fileAPI, selected_filter = QFileDialog.getOpenFileName( self, "Open API File", lastDirPath, "API file (*.api)") if fileAPI: self.addAPI(fileAPI) settings.setValue("pythonConsole/lastDirAPIPath", fileAPI) def _prepareAPI(self): if self.tableWidget.rowCount() != 0: pap_file, filter = QFileDialog().getSaveFileName( self, "", '*.pap', "Prepared APIs file (*.pap)") else: QMessageBox.information( self, self.tr("Warning!"), self.tr('You need to add some APIs file in order to compile')) return if pap_file: api_lexer = 'QsciLexerPython' api_files = [] count = self.tableWidget.rowCount() for i in range(0, count): api_files.append(self.tableWidget.item(i, 1).text()) api_dlg = PrepareAPIDialog(api_lexer, api_files, pap_file, self) api_dlg.show() api_dlg.activateWindow() api_dlg.raise_() api_dlg.prepareAPI() self.lineEdit.setText(pap_file) def accept(self): if not self.preloadAPI.isChecked() and \ not self.groupBoxPreparedAPI.isChecked(): if self.tableWidget.rowCount() == 0: QMessageBox.information( self, self.tr("Warning!"), self.tr('Please specify API file or check "Use preloaded API files"')) return if self.groupBoxPreparedAPI.isChecked() and \ not self.lineEdit.text(): QMessageBox.information( self, self.tr("Warning!"), QCoreApplication.translate('optionsDialog', 'The APIs file was not compiled, click on "Compile APIs…"') ) return self.saveSettings() self.listPath = [] QDialog.accept(self) def addAPI(self, pathAPI): count = self.tableWidget.rowCount() self.tableWidget.setColumnCount(2) self.tableWidget.insertRow(count) pathItem = QTableWidgetItem(pathAPI) pathSplit = pathAPI.split("/") apiName = pathSplit[-1][0:-4] apiNameItem = QTableWidgetItem(apiName) self.tableWidget.setItem(count, 0, apiNameItem) self.tableWidget.setItem(count, 1, pathItem) def removeAPI(self): listItemSel = self.tableWidget.selectionModel().selectedRows() for index in reversed(listItemSel): self.tableWidget.removeRow(index.row()) def saveSettings(self): settings = QgsSettings() settings.setValue("pythonConsole/preloadAPI", self.preloadAPI.isChecked()) settings.setValue("pythonConsole/autoSaveScript", self.autoSaveScript.isChecked()) fontFamilyText = self.fontComboBox.currentText() settings.setValue("pythonConsole/fontfamilytext", fontFamilyText) fontFamilyTextEditor = self.fontComboBoxEditor.currentText() settings.setValue("pythonConsole/fontfamilytextEditor", fontFamilyTextEditor) fontSize = self.spinBox.value() fontSizeEditor = self.spinBoxEditor.value() for i in range(0, self.tableWidget.rowCount()): text = self.tableWidget.item(i, 1).text() self.listPath.append(text) settings.setValue("pythonConsole/fontsize", fontSize) settings.setValue("pythonConsole/fontsizeEditor", fontSizeEditor) settings.setValue("pythonConsole/userAPI", self.listPath) settings.setValue("pythonConsole/autoCompThreshold", self.autoCompThreshold.value()) settings.setValue("pythonConsole/autoCompThresholdEditor", self.autoCompThresholdEditor.value()) settings.setValue("pythonConsole/autoCompleteEnabledEditor", self.groupBoxAutoCompletionEditor.isChecked()) settings.setValue("pythonConsole/autoCompleteEnabled", self.groupBoxAutoCompletion.isChecked()) settings.setValue("pythonConsole/usePreparedAPIFile", self.groupBoxPreparedAPI.isChecked()) settings.setValue("pythonConsole/preparedAPIFile", self.lineEdit.text()) if self.autoCompFromAPIEditor.isChecked(): settings.setValue("pythonConsole/autoCompleteSourceEditor", 'fromAPI') elif self.autoCompFromDocEditor.isChecked(): settings.setValue("pythonConsole/autoCompleteSourceEditor", 'fromDoc') elif self.autoCompFromDocAPIEditor.isChecked(): settings.setValue("pythonConsole/autoCompleteSourceEditor", 'fromDocAPI') if self.autoCompFromAPI.isChecked(): settings.setValue("pythonConsole/autoCompleteSource", 'fromAPI') elif self.autoCompFromDoc.isChecked(): settings.setValue("pythonConsole/autoCompleteSource", 'fromDoc') elif self.autoCompFromDocAPI.isChecked(): settings.setValue("pythonConsole/autoCompleteSource", 'fromDocAPI') settings.setValue("pythonConsole/enableObjectInsp", self.enableObjectInspector.isChecked()) settings.setValue("pythonConsole/autoCloseBracket", self.autoCloseBracket.isChecked()) settings.setValue("pythonConsole/autoCloseBracketEditor", self.autoCloseBracketEditor.isChecked()) settings.setValue("pythonConsole/autoInsertionImport", self.autoInsertionImport.isChecked()) settings.setValue("pythonConsole/autoInsertionImportEditor", self.autoInsertionImportEditor.isChecked()) settings.setValue("pythonConsole/defaultFontColor", self.defaultFontColor.color()) settings.setValue("pythonConsole/defaultFontColorEditor", self.defaultFontColorEditor.color()) settings.setValue("pythonConsole/classFontColor", self.classFontColor.color()) settings.setValue("pythonConsole/classFontColorEditor", self.classFontColorEditor.color()) settings.setValue("pythonConsole/keywordFontColor", self.keywordFontColor.color()) settings.setValue("pythonConsole/keywordFontColorEditor", self.keywordFontColorEditor.color()) settings.setValue("pythonConsole/decorFontColor", self.decorFontColor.color()) settings.setValue("pythonConsole/decorFontColorEditor", self.decorFontColorEditor.color()) settings.setValue("pythonConsole/numberFontColor", self.numberFontColor.color()) settings.setValue("pythonConsole/numberFontColorEditor", self.numberFontColorEditor.color()) settings.setValue("pythonConsole/methodFontColor", self.methodFontColor.color()) settings.setValue("pythonConsole/methodFontColorEditor", self.methodFontColorEditor.color()) settings.setValue("pythonConsole/commentFontColor", self.commentFontColor.color()) settings.setValue("pythonConsole/commentFontColorEditor", self.commentFontColorEditor.color()) settings.setValue("pythonConsole/commentBlockFontColor", self.commentBlockFontColor.color()) settings.setValue("pythonConsole/commentBlockFontColorEditor", self.commentBlockFontColorEditor.color()) settings.setValue("pythonConsole/paperBackgroundColor", self.paperBackgroundColor.color()) settings.setValue("pythonConsole/paperBackgroundColorEditor", self.paperBackgroundColorEditor.color()) settings.setValue("pythonConsole/cursorColor", self.cursorColor.color()) settings.setValue("pythonConsole/cursorColorEditor", self.cursorColorEditor.color()) settings.setValue("pythonConsole/caretLineColor", self.caretLineColor.color()) settings.setValue("pythonConsole/caretLineColorEditor", self.caretLineColorEditor.color()) settings.setValue("pythonConsole/stderrFontColor", self.stderrFontColor.color()) settings.setValue("pythonConsole/singleQuoteFontColor", self.singleQuoteFontColor.color()) settings.setValue("pythonConsole/singleQuoteFontColorEditor", self.singleQuoteFontColorEditor.color()) settings.setValue("pythonConsole/doubleQuoteFontColor", self.doubleQuoteFontColor.color()) settings.setValue("pythonConsole/doubleQuoteFontColorEditor", self.doubleQuoteFontColorEditor.color()) settings.setValue("pythonConsole/tripleSingleQuoteFontColor", self.tripleSingleQuoteFontColor.color()) settings.setValue("pythonConsole/tripleSingleQuoteFontColorEditor", self.tripleSingleQuoteFontColorEditor.color()) settings.setValue("pythonConsole/tripleDoubleQuoteFontColor", self.tripleDoubleQuoteFontColor.color()) settings.setValue("pythonConsole/tripleDoubleQuoteFontColorEditor", self.tripleDoubleQuoteFontColorEditor.color()) settings.setValue("pythonConsole/edgeColorEditor", self.edgeColorEditor.color()) settings.setValue("pythonConsole/marginBackgroundColor", self.marginBackgroundColor.color()) settings.setValue("pythonConsole/marginBackgroundColorEditor", self.marginBackgroundColorEditor.color()) settings.setValue("pythonConsole/marginForegroundColor", self.marginForegroundColor.color()) settings.setValue("pythonConsole/marginForegroundColorEditor", self.marginForegroundColorEditor.color()) settings.setValue("pythonConsole/foldColorEditor", self.foldColorEditor.color()) settings.setValue("pythonConsole/selectionBackgroundColor", self.selectionBackgroundColor.color()) settings.setValue("pythonConsole/selectionBackgroundColorEditor", self.selectionBackgroundColorEditor.color()) settings.setValue("pythonConsole/selectionForegroundColor", self.selectionForegroundColor.color()) settings.setValue("pythonConsole/selectionForegroundColorEditor", self.selectionForegroundColorEditor.color()) settings.setValue("pythonConsole/matchedBraceBackgroundColor", self.matchedBraceBackgroundColor.color()) settings.setValue("pythonConsole/matchedBraceBackgroundColorEditor", self.matchedBraceBackgroundColorEditor.color()) settings.setValue("pythonConsole/matchedBraceForegroundColor", self.matchedBraceForegroundColor.color()) settings.setValue("pythonConsole/matchedBraceForegroundColorEditor", self.matchedBraceForegroundColorEditor.color()) def restoreSettings(self): settings = QgsSettings() font = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.spinBox.setValue(settings.value("pythonConsole/fontsize", font.pointSize(), type=int)) self.spinBoxEditor.setValue(settings.value("pythonConsole/fontsizeEditor", font.pointSize(), type=int)) self.fontComboBox.setCurrentFont(QFont(settings.value("pythonConsole/fontfamilytext", font.family()))) self.fontComboBoxEditor.setCurrentFont(QFont(settings.value("pythonConsole/fontfamilytextEditor", font.family()))) self.preloadAPI.setChecked(settings.value("pythonConsole/preloadAPI", True, type=bool)) self.lineEdit.setText(settings.value("pythonConsole/preparedAPIFile", "", type=str)) itemTable = settings.value("pythonConsole/userAPI", []) if itemTable: self.tableWidget.setRowCount(0) for i in range(len(itemTable)): self.tableWidget.insertRow(i) self.tableWidget.setColumnCount(2) pathSplit = itemTable[i].split("/") apiName = pathSplit[-1][0:-4] self.tableWidget.setItem(i, 0, QTableWidgetItem(apiName)) self.tableWidget.setItem(i, 1, QTableWidgetItem(itemTable[i])) self.autoSaveScript.setChecked(settings.value("pythonConsole/autoSaveScript", False, type=bool)) self.autoCompThreshold.setValue(settings.value("pythonConsole/autoCompThreshold", 2, type=int)) self.autoCompThresholdEditor.setValue(settings.value("pythonConsole/autoCompThresholdEditor", 2, type=int)) self.groupBoxAutoCompletionEditor.setChecked( settings.value("pythonConsole/autoCompleteEnabledEditor", True, type=bool)) self.groupBoxAutoCompletion.setChecked(settings.value("pythonConsole/autoCompleteEnabled", True, type=bool)) self.enableObjectInspector.setChecked(settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.autoCloseBracketEditor.setChecked(settings.value("pythonConsole/autoCloseBracketEditor", False, type=bool)) self.autoCloseBracket.setChecked(settings.value("pythonConsole/autoCloseBracket", False, type=bool)) self.autoInsertionImportEditor.setChecked( settings.value("pythonConsole/autoInsertionImportEditor", True, type=bool)) self.autoInsertionImport.setChecked(settings.value("pythonConsole/autoInsertionImport", True, type=bool)) if settings.value("pythonConsole/autoCompleteSource") == 'fromDoc': self.autoCompFromDoc.setChecked(True) elif settings.value("pythonConsole/autoCompleteSource") == 'fromAPI': self.autoCompFromAPI.setChecked(True) elif settings.value("pythonConsole/autoCompleteSource") == 'fromDocAPI': self.autoCompFromDocAPI.setChecked(True) if settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromDoc': self.autoCompFromDocEditor.setChecked(True) elif settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromAPI': self.autoCompFromAPIEditor.setChecked(True) elif settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromDocAPI': self.autoCompFromDocAPIEditor.setChecked(True) # Setting font lexer color self.defaultFontColor.setColor(QColor(settings.value("pythonConsole/defaultFontColor", QColor(self.DEFAULT_COLOR)))) self.defaultFontColorEditor.setColor( QColor(settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR)))) self.keywordFontColor.setColor(QColor(settings.value("pythonConsole/keywordFontColor", QColor(self.KEYWORD_COLOR)))) self.keywordFontColorEditor.setColor( QColor(settings.value("pythonConsole/keywordFontColorEditor", QColor(self.KEYWORD_COLOR)))) self.classFontColor.setColor(QColor(settings.value("pythonConsole/classFontColor", QColor(self.CLASS_COLOR)))) self.classFontColorEditor.setColor( QColor(settings.value("pythonConsole/classFontColorEditor", QColor(self.CLASS_COLOR)))) self.methodFontColor.setColor(QColor(settings.value("pythonConsole/methodFontColor", QColor(self.METHOD_COLOR)))) self.methodFontColorEditor.setColor( QColor(settings.value("pythonConsole/methodFontColorEditor", QColor(self.METHOD_COLOR)))) self.decorFontColor.setColor(QColor(settings.value("pythonConsole/decorFontColor", QColor(self.DECORATION_COLOR)))) self.decorFontColorEditor.setColor( QColor(settings.value("pythonConsole/decorFontColorEditor", QColor(self.DECORATION_COLOR)))) self.numberFontColor.setColor(QColor(settings.value("pythonConsole/numberFontColor", QColor(self.NUMBER_COLOR)))) self.numberFontColorEditor.setColor( QColor(settings.value("pythonConsole/numberFontColorEditor", QColor(self.NUMBER_COLOR)))) self.commentFontColor.setColor(QColor(settings.value("pythonConsole/commentFontColor", QColor(self.COMMENT_COLOR)))) self.commentFontColorEditor.setColor( QColor(settings.value("pythonConsole/commentFontColorEditor", QColor(self.COMMENT_COLOR)))) self.commentBlockFontColor.setColor( QColor(settings.value("pythonConsole/commentBlockFontColor", QColor(self.COMMENT_BLOCK_COLOR)))) self.commentBlockFontColorEditor.setColor( QColor(settings.value("pythonConsole/commentBlockFontColorEditor", QColor(self.COMMENT_BLOCK_COLOR)))) self.paperBackgroundColor.setColor( QColor(settings.value("pythonConsole/paperBackgroundColor", QColor(self.BACKGROUND_COLOR)))) self.paperBackgroundColorEditor.setColor( QColor(settings.value("pythonConsole/paperBackgroundColorEditor", QColor(self.BACKGROUND_COLOR)))) self.caretLineColor.setColor(QColor(settings.value("pythonConsole/caretLineColor", QColor(self.CARET_LINE_COLOR)))) self.caretLineColorEditor.setColor( QColor(settings.value("pythonConsole/caretLineColorEditor", QColor(self.CARET_LINE_COLOR)))) self.cursorColor.setColor(QColor(settings.value("pythonConsole/cursorColor", QColor(self.CURSOR_COLOR)))) self.cursorColorEditor.setColor(QColor(settings.value("pythonConsole/cursorColorEditor", QColor(self.CURSOR_COLOR)))) self.singleQuoteFontColor.setColor(settings.value("pythonConsole/singleQuoteFontColor", QColor(self.SINGLE_QUOTE_COLOR))) self.singleQuoteFontColorEditor.setColor( settings.value("pythonConsole/singleQuoteFontColorEditor", QColor(self.SINGLE_QUOTE_COLOR))) self.doubleQuoteFontColor.setColor(settings.value("pythonConsole/doubleQuoteFontColor", QColor(self.DOUBLE_QUOTE_COLOR))) self.doubleQuoteFontColorEditor.setColor( settings.value("pythonConsole/doubleQuoteFontColorEditor", QColor(self.DOUBLE_QUOTE_COLOR))) self.tripleSingleQuoteFontColor.setColor( settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(self.TRIPLE_SINGLE_QUOTE_COLOR))) self.tripleSingleQuoteFontColorEditor.setColor( settings.value("pythonConsole/tripleSingleQuoteFontColorEditor", QColor(self.TRIPLE_SINGLE_QUOTE_COLOR))) self.tripleDoubleQuoteFontColor.setColor( settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR))) self.tripleDoubleQuoteFontColorEditor.setColor( settings.value("pythonConsole/tripleDoubleQuoteFontColorEditor", QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR))) self.marginBackgroundColor.setColor(settings.value("pythonConsole/marginBackgroundColor", QColor(self.MARGIN_BACKGROUND_COLOR))) self.marginBackgroundColorEditor.setColor(settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR))) self.marginForegroundColor.setColor(settings.value("pythonConsole/marginForegroundColor", QColor(self.MARGIN_FOREGROUND_COLOR))) self.marginForegroundColorEditor.setColor(settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR))) self.selectionForegroundColor.setColor(settings.value("pythonConsole/selectionForegroundColor", QColor(self.SELECTION_FOREGROUND_COLOR))) self.selectionForegroundColorEditor.setColor(settings.value("pythonConsole/selectionForegroundColorEditor", QColor(self.SELECTION_FOREGROUND_COLOR))) self.selectionBackgroundColor.setColor(settings.value("pythonConsole/selectionBackgroundColor", QColor(self.SELECTION_BACKGROUND_COLOR))) self.selectionBackgroundColorEditor.setColor(settings.value("pythonConsole/selectionBackgroundColorEditor", QColor(self.SELECTION_BACKGROUND_COLOR))) self.matchedBraceForegroundColor.setColor(settings.value("pythonConsole/matchedBraceForegroundColor", QColor(self.MATCHED_BRACE_FOREGROUND_COLOR))) self.matchedBraceForegroundColorEditor.setColor(settings.value("pythonConsole/matchedBraceForegroundColorEditor", QColor(self.MATCHED_BRACE_FOREGROUND_COLOR))) self.matchedBraceBackgroundColor.setColor(settings.value("pythonConsole/matchedBraceBackgroundColor", QColor(self.MATCHED_BRACE_BACKGROUND_COLOR))) self.matchedBraceBackgroundColorEditor.setColor(settings.value("pythonConsole/matchedBraceBackgroundColorEditor", QColor(self.MATCHED_BRACE_BACKGROUND_COLOR))) self.stderrFontColor.setColor(QColor(settings.value("pythonConsole/stderrFontColor", QColor(self.ERROR_COLOR)))) self.edgeColorEditor.setColor(settings.value("pythonConsole/edgeColorEditor", QColor(self.EDGE_COLOR))) self.foldColorEditor.setColor(settings.value("pythonConsole/foldColorEditor", QColor(self.FOLD_COLOR))) def _resetFontColor(self): self.defaultFontColor.setColor(QColor(self.DEFAULT_COLOR)) self.keywordFontColor.setColor(QColor(self.KEYWORD_COLOR)) self.classFontColor.setColor(QColor(self.CLASS_COLOR)) self.methodFontColor.setColor(QColor(self.METHOD_COLOR)) self.decorFontColor.setColor(QColor(self.DECORATION_COLOR)) self.numberFontColor.setColor(QColor(self.NUMBER_COLOR)) self.commentFontColor.setColor(QColor(self.COMMENT_COLOR)) self.commentBlockFontColor.setColor(QColor(self.COMMENT_BLOCK_COLOR)) self.paperBackgroundColor.setColor(QColor(self.BACKGROUND_COLOR)) self.cursorColor.setColor(QColor(self.CURSOR_COLOR)) self.caretLineColor.setColor(QColor(self.CARET_LINE_COLOR)) self.singleQuoteFontColor.setColor(QColor(self.SINGLE_QUOTE_COLOR)) self.doubleQuoteFontColor.setColor(QColor(self.DOUBLE_QUOTE_COLOR)) self.tripleSingleQuoteFontColor.setColor(QColor(self.TRIPLE_SINGLE_QUOTE_COLOR)) self.tripleDoubleQuoteFontColor.setColor(QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR)) self.marginBackgroundColor.setColor(QColor(self.MARGIN_BACKGROUND_COLOR)) self.marginForegroundColor.setColor(QColor(self.MARGIN_FOREGROUND_COLOR)) self.selectionBackgroundColor.setColor(QColor(self.SELECTION_BACKGROUND_COLOR)) self.selectionForegroundColor.setColor(QColor(self.SELECTION_FOREGROUND_COLOR)) self.matchedBraceBackgroundColor.setColor(QColor(self.MATCHED_BRACE_BACKGROUND_COLOR)) self.matchedBraceForegroundColor.setColor(QColor(self.MATCHED_BRACE_FOREGROUND_COLOR)) self.stderrFontColor.setColor(QColor(self.ERROR_COLOR)) def _resetFontColorEditor(self): self.defaultFontColorEditor.setColor(QColor(self.DEFAULT_COLOR)) self.keywordFontColorEditor.setColor(QColor(self.KEYWORD_COLOR)) self.classFontColorEditor.setColor(QColor(self.CLASS_COLOR)) self.methodFontColorEditor.setColor(QColor(self.METHOD_COLOR)) self.decorFontColorEditor.setColor(QColor(self.DECORATION_COLOR)) self.numberFontColorEditor.setColor(QColor(self.NUMBER_COLOR)) self.commentFontColorEditor.setColor(QColor(self.COMMENT_COLOR)) self.commentBlockFontColorEditor.setColor(QColor(self.COMMENT_BLOCK_COLOR)) self.paperBackgroundColorEditor.setColor(QColor(self.BACKGROUND_COLOR)) self.cursorColorEditor.setColor(QColor(self.CURSOR_COLOR)) self.caretLineColorEditor.setColor(QColor(self.CARET_LINE_COLOR)) self.singleQuoteFontColorEditor.setColor(QColor(self.SINGLE_QUOTE_COLOR)) self.doubleQuoteFontColorEditor.setColor(QColor(self.DOUBLE_QUOTE_COLOR)) self.tripleSingleQuoteFontColorEditor.setColor(QColor(self.TRIPLE_SINGLE_QUOTE_COLOR)) self.tripleDoubleQuoteFontColorEditor.setColor(QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR)) self.marginBackgroundColorEditor.setColor(QColor(self.MARGIN_BACKGROUND_COLOR)) self.marginForegroundColorEditor.setColor(QColor(self.MARGIN_FOREGROUND_COLOR)) self.selectionBackgroundColorEditor.setColor(QColor(self.SELECTION_BACKGROUND_COLOR)) self.selectionForegroundColorEditor.setColor(QColor(self.SELECTION_FOREGROUND_COLOR)) self.matchedBraceBackgroundColorEditor.setColor(QColor(self.MATCHED_BRACE_BACKGROUND_COLOR)) self.matchedBraceForegroundColorEditor.setColor(QColor(self.MATCHED_BRACE_FOREGROUND_COLOR)) self.edgeColorEditor.setColor(QColor(self.EDGE_COLOR)) self.foldColorEditor.setColor(QColor(self.FOLD_COLOR)) def reject(self): self.restoreSettings() QDialog.reject(self)
gpl-2.0
ndhuang/python-lib
plot2Ddist.py
1
9018
import pylab import numpy as np import pymc import matplotlib.patches from mpl_toolkits.axes_grid1 import make_axes_locatable import scipy.stats def frac_inside_poly(x,y,polyxy): """Calculate the fraction of points x,y inside polygon polyxy. polyxy -- list of x,y coordinates of vertices. """ xy = np.vstack([x,y]).transpose() return float(sum(matplotlib.nxutils.points_inside_poly(xy, polyxy)))/len(x) def fracs_inside_contours(x, y, contours): """Calculate the fraction of points x,y inside each contour level. contours -- a matplotlib.contour.QuadContourSet """ fracs = [] for (icollection, collection) in enumerate(contours.collections): path = collection.get_paths()[0] pathxy = path.vertices frac = frac_inside_poly(x,y,pathxy) fracs.append(frac) return fracs def frac_label_contours(x, y, contours, format='%.3f'): """Label contours according to the fraction of points x,y inside. """ fracs = fracs_inside_contours(x,y,contours) levels = contours.levels labels = {} for (level, frac) in zip(levels, fracs): labels[level] = format % frac contours.clabel(fmt=labels) def contour_enclosing(x, y, fractions, xgrid, ygrid, zvals, axes, nstart = 200, *args, **kwargs): """Plot contours encompassing specified fractions of points x,y. """ print fractions # Generate a large set of contours initially. contours = axes.contour(xgrid, ygrid, zvals, nstart, extend='both') # Set up fracs and levs for interpolation. levs = contours.levels fracs = np.array(fracs_inside_contours(x,y,contours)) sortinds = np.argsort(fracs) levs = levs[sortinds] fracs = fracs[sortinds] # Find the levels that give the specified fractions. levels = scipy.interp(fractions, fracs, levs) # Remove the old contours from the graph. for coll in contours.collections: coll.remove() # Reset the contours contours.__init__(axes, xgrid, ygrid, zvals, levels, *args, **kwargs) return contours def plot2Ddist(variables, axeslist=None, truevalues=None, trimto=None, thin=1, histbinslist=[100, 100], labels=None, scaleview=True, plotscatter=True, plothists=True, plotcontours=True, contourKDEthin=1, contourNGrid=100, contourFractions=[0.6827, 0.9545, 0.9973], labelcontours=True, returncontours=False, scatterstyle={}, histstyle={}, contourstyle={}, **styleArgs): """Plot joint distribution of two variables, with marginal histograms. The resulting graphic includes (at your discretion): * a scatter plot of the 2D distribution of the two variables * estimated density contours for the distribution * marginal histograms for each variable See plot2Ddist_example.py for an example: > plot2Ddist([a, b], truevalues=[intercept, slope], **styleargs) Notes ----- The contour plotting can be quite slow for large samples because of the gaussian kernel density estimation. Try passing a larger value for contourKDEthin to speed it up. Inputs ------ variables -- list-like of length 2 a list of two array-like or pymc.Variable objects. The lengths of the arrays or variable traces should be equal. axeslist -- list-like of length 3 a list of three Matplotlib Axes for: the joint plot, marginal x histogram, and marginal y histogram, respectively. truevalues -- list-like of length 2 a list of the true values for each variable trimto -- int plot only the last trimto elements of each variable thin -- int plot only every thin-th element of each variable histbinlist -- list-like of length 2 specify the bins (number or limits) for x and y marginal histograms. labels -- list-like of two strings the x and y axis labels scaleview -- bool whether to set the axes limits according to the plotted data plotscatter, plothists, plotcontours -- bool whether to plot the scatter, marginal histograms, and contours scatterstyle, histstyle, contourstyle -- dict-like additional keyword arguments for the plot, hist, or contour commands contourKDEthin -- int factor by which to thin the samples before calculating the gaussian kernel density estimate for contouring contourNGrid -- int size of the grid to use (in each dimension) for the contour plotting contourFractions -- list-like countours are chosen to include the fractions of points specified here labelcontours -- bool whether to label the contours with the fraction of points enclosed styleArgs -- leftover arguments are passed to both the plot and hist commands """ ### Set up figures and axes. ### if axeslist is None: fig1 = pylab.figure(figsize=(6,6)) fig1.set_label('traces') ax1 = pylab.gca() divider = make_axes_locatable(ax1) ax2 = divider.append_axes("top", 1.5, pad=0.0, sharex=ax1) ax3 = divider.append_axes("right", 1.5, pad=0.0, sharey=ax1) for tl in (ax2.get_xticklabels() + ax2.get_yticklabels() + ax3.get_xticklabels() + ax3.get_yticklabels()): tl.set_visible(False) axeslist = (ax1, ax2, ax3) elif (len(axeslist) == 1): ax1 = axeslist[0] divider = make_axes_locatable(ax1) ax2 = divider.append_axes("top", 1.5, pad=0.0, sharex=ax1) ax3 = divider.append_axes("right", 1.5, pad=0.0, sharey=ax1) for tl in (ax2.get_xticklabels() + ax2.get_yticklabels() + ax3.get_xticklabels() + ax3.get_yticklabels()): tl.set_visible(False) axeslist = (ax1, ax2, ax3) else: ax1, ax2, ax3 = axeslist # Thin and trim variables. if labels is None: passedlabels = False labels = [None, None] else: passedlabels = True for (ivar, variable) in enumerate(variables): # Get the trace if this is a pymc.Variable object. if isinstance(variable, pymc.Variable): variables[ivar] = variable.trace() if hasattr(variable, '__name__') and not passedlabels: labels[ivar] = variable.__name__ if trimto is None: trimto = len(variables[0]) x = variables[0][-trimto::thin] y = variables[1][-trimto::thin] ### Plot the variables. ### # Plot 2D scatter of variables. if plotscatter: style = {'ls':'', 'marker':',', 'color':'r', 'alpha':'0.5'} style.update(styleArgs) style.update(scatterstyle) ax1.plot(x, y, **style) if plotcontours: xkde = variables[0][-trimto::contourKDEthin] ykde = variables[1][-trimto::contourKDEthin] # Inspired by Abraham Flaxman's https://gist.github.com/626689 style = {'linewidths':2.0, 'alpha':0.75, #'cmap':matplotlib.cm.Greys, 'zorder':10} style.update(styleArgs) style.update(contourstyle) if 'color' in style: style['colors'] = style['color'] gkde = scipy.stats.gaussian_kde([xkde,ykde]) xgrid, ygrid = np.mgrid[min(x):max(x):contourNGrid * 1j, min(y):max(y):contourNGrid * 1j] zvals = np.array(gkde.evaluate([xgrid.flatten(), ygrid.flatten()]) ).reshape(xgrid.shape) contours = contour_enclosing(x, y, contourFractions, xgrid, ygrid, zvals, ax1, **style) # Plot marginal histograms. if plothists: style = {'normed':True} style.update(styleArgs) style.update(histstyle) ax2.hist(x, histbinslist[0], **style) ax3.hist(y, histbinslist[1], orientation='horizontal', **style) # Plot lines for the true values. if truevalues is not None: ax1.axvline(x=truevalues[0], ls=':', c='k') ax1.axhline(y=truevalues[1], ls=':', c='k') ax2.axvline(x=truevalues[0], ls=':', c='k') ax3.axhline(y=truevalues[1], ls=':', c='k') if scaleview: ax2.relim() ax3.relim() ax1.relim() ax2.autoscale_view(tight=True) ax3.autoscale_view(tight=True) ax1.autoscale_view(tight=True) ax2.set_ylim(bottom=0) ax3.set_xlim(left=0) if labels[0] is not None: ax1.set_xlabel(labels[0]) if labels[1] is not None: ax1.set_ylabel(labels[1]) if plotcontours and labelcontours: frac_label_contours(x, y, contours) if plotcontours and returncontours: return axeslist, contours else: return axeslist
mit
kanagasabapathi/python-for-android
python-modules/pybluez/examples/advanced/write-inquiry-scan.py
47
3095
import os import sys import struct import bluetooth._bluetooth as bluez def read_inquiry_scan_activity(sock): """returns the current inquiry scan interval and window, or -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # read_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_READ_INQ_ACTIVITY) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # first read the current inquiry mode. bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_READ_INQ_ACTIVITY ) pkt = sock.recv(255) status,interval,window = struct.unpack("!xxxxxxBHH", pkt) interval = bluez.btohs(interval) interval = (interval >> 8) | ( (interval & 0xFF) << 8 ) window = (window >> 8) | ( (window & 0xFF) << 8 ) if status != 0: mode = -1 # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) return interval, window def write_inquiry_scan_activity(sock, interval, window): """returns 0 on success, -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # write_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_WRITE_INQ_ACTIVITY) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # send the command! bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_WRITE_INQ_ACTIVITY, struct.pack("HH", interval, window) ) pkt = sock.recv(255) status = struct.unpack("xxxxxxB", pkt)[0] # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) if status != 0: return -1 return 0 dev_id = 0 try: sock = bluez.hci_open_dev(dev_id) except: print "error accessing bluetooth device..." sys.exit(1) try: interval, window = read_inquiry_scan_activity(sock) except Exception, e: print "error reading inquiry scan activity. " print e sys.exit(1) print "current inquiry scan interval: %d (0x%X) window: %d (0x%X)" % \ (interval, interval, window, window) if len(sys.argv) == 3: interval = int(sys.argv[1]) window = int(sys.argv[2]) print "target interval: %d window %d" % (interval, window) write_inquiry_scan_activity(sock, interval, window) interval, window = read_inquiry_scan_activity(sock) print "current inquiry scan interval: %d (0x%X) window: %d (0x%X)" % \ (interval, interval, window, window)
apache-2.0
brennie/reviewboard
docs/manual/conf.py
1
10297
# -*- coding: utf-8 -*- # # Review Board Manual build configuration file, created by # sphinx-quickstart on Thu Feb 12 02:10:34 2009. # # This file is execfile()d with the current directory set to its containing # dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed # automatically). # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys from datetime import datetime sys.path.append(os.path.abspath('_ext')) # Set this up to parse Django-driven code. sys.path.insert(0, os.path.abspath(os.path.join(__file__, '..', '..', '..'))) sys.path.insert(0, os.path.abspath(os.path.join(__file__, '..', '..', '..', '..', 'djblets'))) sys.path.insert(0, os.path.dirname(__file__)) # The nightly docs system needs to inject certain builds of Djblets and Django. # PYTHONPATH will only append, meaning that the system-installed ones will # be looked up first, so allow us to append instead. sys.path = os.getenv('PYTHONPATH_PREPEND', '').split(':') + sys.path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reviewboard.settings') import reviewboard from reviewboard.dependencies import (django_doc_major_version, djblets_doc_major_version) from beanbag_docutils.sphinx.ext.github import github_linkcode_resolve # If your extensions are in another directory, add it here. If the directory # is relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. #sys.path.append(os.path.abspath('.')) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.linkcode', 'sphinx.ext.napoleon', 'sphinx.ext.todo', 'beanbag_docutils.sphinx.ext.autodoc_utils', 'beanbag_docutils.sphinx.ext.django_utils', 'beanbag_docutils.sphinx.ext.extlinks', 'beanbag_docutils.sphinx.ext.http_role', 'beanbag_docutils.sphinx.ext.retina_images', 'webapidocs', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'contents' # General information about the project. project = u'Review Board Manual' copyright = u'2009-%s, Beanbag, Inc.' % datetime.now().year # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '.'.join([str(i) for i in reviewboard.__version_info__[:2]]) # The full version, including alpha/beta/rc tags. release = reviewboard.get_version_string() # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build', '_templates'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Disable warning of unknown referenced options. suppress_warnings = ['ref.option'] # Options for HTML output # ----------------------- html_theme = 'classic' # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'classic.css' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". html_title = "Review Board Manual" # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "classic.css" will overwrite the builtin "classic.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, the reST sources are included in the HTML build as _sources/<name>. html_copy_source = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'ReviewBoardManual' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class # [howto/manual]). latex_documents = [ ('users/index', 'UserManual.tex', ur'Review Board User Manual', ur'Beanbag, Inc.', 'manual', False), ('admin/index', 'AdminGuide.tex', ur'Review Board Administration Guide', ur'Beanbag, Inc.', 'manual', False), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True latex_show_urls = True latex_show_pagerefs = True # Determine the branch or tag used for code references. rb_version = reviewboard.VERSION if rb_version[4] == 'final' or rb_version[4] > 0: if reviewboard.is_release(): git_branch = 'release-%s.%s.%s' % rb_version[:3] else: git_branch = 'release-%s.%s.x' % rb_version[:2] else: git_branch = 'master' # Check whether reviewboard.org intersphinx lookups should use the local # server. if os.getenv('DOCS_USE_LOCAL_RBWEBSITE') == '1': rbwebsite_url = 'http://localhost:8081' else: rbwebsite_url = 'https://www.reviewboard.org' django_doc_base_url = ('http://django.readthedocs.io/en/%s.x/' % django_doc_major_version) intersphinx_mapping = { 'django': (django_doc_base_url, None), 'djblets': ('%s/docs/djblets/%s/' % (rbwebsite_url, djblets_doc_major_version), None), 'python': ('https://docs.python.org/2.7', None), 'rbtools': ('%s/docs/rbtools/latest/' % rbwebsite_url, None), 'rbcontributing': ('%s/docs/codebase/dev/' % rbwebsite_url, None), } extlinks = { 'djangodoc': ('%s%%s.html' % django_doc_base_url, None), 'backbonejs': ('http://backbonejs.org/#%s', 'Backbone.'), 'rbintegration': ('https://www.reviewboard.org/integrations/%s', ''), 'rbsource': ('https://github.com/reviewboard/reviewboard/blob/%s/%%s' % git_branch, ''), } todo_include_todos = True autodoc_member_order = 'bysource' autoclass_content = 'class' autodoc_default_flags = [ 'members', 'special-members', 'undoc-members', 'show-inheritance', ] autodoc_excludes = { '*': [ '__dict__', '__doc__', '__module__', '__weakref__', ], 'class': [ # Common to models. 'DoesNotExist', 'MultipleObjectsReturned', # Common to forms. 'base_fields', 'media', ], } autosummary_generate = True napoleon_beanbag_docstring = True napoleon_google_docstring = False napoleon_numpy_docstring = False def linkcode_resolve(domain, info): return github_linkcode_resolve(domain=domain, info=info, allowed_module_names=['reviewboard'], github_org_id='reviewboard', github_repo_id='reviewboard', branch=git_branch)
mit
doganaltunbay/odoo
addons/sale_order_dates/__init__.py
441
1071
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import sale_order_dates # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
systers/portal
systers_portal/meetup/tests/test_models.py
2
4424
from django.contrib.auth.models import User from django.test import TestCase from django.utils import timezone from cities_light.models import City, Country from meetup.models import (Meetup, Rsvp, SupportRequest, RequestMeetup) from users.models import SystersUser class MeetupBaseTestCase: def setUp(self): country = Country.objects.create(name='Bar', continent='AS') self.location = City.objects.create(name='Foo', display_name='Foo', country=country) self.user = User.objects.create(username='foo', password='foobar') self.systers_user = SystersUser.objects.get(user=self.user) class MeetupTestCase(MeetupBaseTestCase, TestCase): def setUp(self): super(MeetupTestCase, self).setUp() self.meetup = Meetup.objects.create(title="Test Meetup", slug="baz", date=timezone.now().date(), time=timezone.now().time(), venue="FooBar colony", description="This is a testing meetup.", meetup_location=self.location, created_by=self.systers_user, leader=self.systers_user) def test_str(self): """Test Meetup object str/unicode representation""" self.assertEqual(str(self.meetup), "Test Meetup") class RequestMeetupTestCase(MeetupBaseTestCase, TestCase): def setUp(self): super(RequestMeetupTestCase, self).setUp() self.meetup_request = \ RequestMeetup.objects.create(title="Test Meetup Request", slug="baz", date=timezone.now().date(), time=timezone.now().time(), venue="FooBar colony", description="This is a testing meetup request.", meetup_location=self.location, created_by=self.systers_user) def test_str(self): """Test Meetup object str/unicode representation""" self.assertEqual(str(self.meetup_request), "Test Meetup Request") def test_get_verbose_fields(self): fields = self.meetup_request.get_verbose_fields() self.assertEqual(len(fields), 13) self.assertTrue(fields[1], ('Title', 'Test Meetup Request')) class RsvpTestCase(MeetupBaseTestCase, TestCase): def setUp(self): super(RsvpTestCase, self).setUp() self.meetup = Meetup.objects.create(title="Test Meetup", slug="baz", date=timezone.now().date(), time=timezone.now().time(), venue="FooBar colony", description="This is a testing meetup.", meetup_location=self.location, leader=self.systers_user, created_by=self.systers_user) self.rsvp = Rsvp.objects.create(user=self.systers_user, meetup=self.meetup) def test_str(self): self.assertEqual(str(self.rsvp), "foo RSVP for meetup Test Meetup") class SupportRequestTestCase(MeetupBaseTestCase, TestCase): def setUp(self): super(SupportRequestTestCase, self).setUp() self.meetup = Meetup.objects.create(title="Test Meetup", slug="baz", date=timezone.now().date(), time=timezone.now().time(), venue="FooBar colony", description="This is a testing meetup.", meetup_location=self.location, leader=self.systers_user, created_by=self.systers_user) self.support_request = SupportRequest.objects.create(volunteer=self.systers_user, meetup=self.meetup, description="Support Request") def test_str(self): self.assertEqual(str(self.support_request), "foo volunteered for meetup Test Meetup")
gpl-2.0