repo_name
stringlengths
5
100
path
stringlengths
4
375
copies
stringclasses
991 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
pandaxcl/gyp
test/builddir/gyptest-default.py
50
2674
#!/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. """ Verify the settings that cause a set of programs to be created in a specific build directory, and that no intermediate built files get created outside of that build directory hierarchy even when referred to with deeply-nested ../../.. paths. """ import TestGyp # TODO(mmoss): Make only supports (theoretically) a single, global build # directory (through GYP_GENERATOR_FLAGS 'output_dir'), rather than # gyp-file-specific settings (e.g. the stuff in builddir.gypi) that the other # generators support, so this doesn't work yet for make. # TODO(mmoss) Make also has the issue that the top-level Makefile is written to # the "--depth" location, which is one level above 'src', but then this test # moves 'src' somewhere else, leaving the Makefile behind, so make can't find # its sources. I'm not sure if make is wrong for writing outside the current # directory, or if the test is wrong for assuming everything generated is under # the current directory. # Ninja and CMake do not support setting the build directory. test = TestGyp.TestGyp(formats=['!make', '!ninja', '!cmake']) test.run_gyp('prog1.gyp', '--depth=..', chdir='src') if test.format == 'msvs': if test.uses_msbuild: test.must_contain('src/prog1.vcxproj', '<OutDir>..\\builddir\\Default\\</OutDir>') else: test.must_contain('src/prog1.vcproj', 'OutputDirectory="..\\builddir\\Default\\"') test.relocate('src', 'relocate/src') test.subdir('relocate/builddir') # Make sure that all the built ../../etc. files only get put under builddir, # by making all of relocate read-only and then making only builddir writable. test.writable('relocate', False) test.writable('relocate/builddir', True) # Suppress the test infrastructure's setting SYMROOT on the command line. test.build('prog1.gyp', SYMROOT=None, chdir='relocate/src') expect1 = """\ Hello from prog1.c Hello from func1.c """ expect2 = """\ Hello from subdir2/prog2.c Hello from func2.c """ expect3 = """\ Hello from subdir2/subdir3/prog3.c Hello from func3.c """ expect4 = """\ Hello from subdir2/subdir3/subdir4/prog4.c Hello from func4.c """ expect5 = """\ Hello from subdir2/subdir3/subdir4/subdir5/prog5.c Hello from func5.c """ def run_builddir(prog, expect): dir = 'relocate/builddir/Default/' test.run(program=test.workpath(dir + prog), stdout=expect) run_builddir('prog1', expect1) run_builddir('prog2', expect2) run_builddir('prog3', expect3) run_builddir('prog4', expect4) run_builddir('prog5', expect5) test.pass_test()
bsd-3-clause
xen0l/ansible
lib/ansible/modules/cloud/google/gce_instance_template.py
45
18982
#!/usr/bin/python # Copyright: 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: gce_instance_template version_added: "2.3" short_description: create or destroy instance templates of Compute Engine of GCP. description: - Creates or destroy Google instance templates of Compute Engine of Google Cloud Platform. options: state: description: - The desired state for the instance template. default: "present" choices: ["present", "absent"] name: description: - The name of the GCE instance template. size: description: - The desired machine type for the instance template. default: "f1-micro" source: description: - A source disk to attach to the instance. Cannot specify both I(image) and I(source). image: description: - The image to use to create the instance. Cannot specify both both I(image) and I(source). image_family: description: - The image family to use to create the instance. If I(image) has been used I(image_family) is ignored. Cannot specify both I(image) and I(source). disk_type: description: - Specify a C(pd-standard) disk or C(pd-ssd) for an SSD disk. default: pd-standard disk_auto_delete: description: - Indicate that the boot disk should be deleted when the Node is deleted. default: true network: description: - The network to associate with the instance. default: "default" subnetwork: description: - The Subnetwork resource name for this instance. can_ip_forward: description: - Set to C(yes) to allow instance to send/receive non-matching src/dst packets. type: bool default: 'no' external_ip: description: - The external IP address to use. If C(ephemeral), a new non-static address will be used. If C(None), then no external address will be used. To use an existing static IP address specify address name. default: "ephemeral" service_account_email: description: - service account email service_account_permissions: description: - service account permissions (see U(https://cloud.google.com/sdk/gcloud/reference/compute/instances/create), --scopes section for detailed information) choices: [ "bigquery", "cloud-platform", "compute-ro", "compute-rw", "useraccounts-ro", "useraccounts-rw", "datastore", "logging-write", "monitoring", "sql-admin", "storage-full", "storage-ro", "storage-rw", "taskqueue", "userinfo-email" ] automatic_restart: description: - Defines whether the instance should be automatically restarted when it is terminated by Compute Engine. preemptible: description: - Defines whether the instance is preemptible. tags: description: - a comma-separated list of tags to associate with the instance metadata: description: - a hash/dictionary of custom data for the instance; '{"key":"value", ...}' description: description: - description of instance template disks: description: - a list of persistent disks to attach to the instance; a string value gives the name of the disk; alternatively, a dictionary value can define 'name' and 'mode' ('READ_ONLY' or 'READ_WRITE'). The first entry will be the boot disk (which must be READ_WRITE). nic_gce_struct: description: - Support passing in the GCE-specific formatted networkInterfaces[] structure. disks_gce_struct: description: - Support passing in the GCE-specific formatted formatted disks[] structure. Case sensitive. see U(https://cloud.google.com/compute/docs/reference/latest/instanceTemplates#resource) for detailed information version_added: "2.4" project_id: description: - your GCE project ID pem_file: description: - path to the pem file associated with the service account email This option is deprecated. Use 'credentials_file'. credentials_file: description: - path to the JSON file associated with the service account email subnetwork_region: version_added: "2.4" description: - Region that subnetwork resides in. (Required for subnetwork to successfully complete) requirements: - "python >= 2.6" - "apache-libcloud >= 0.13.3, >= 0.17.0 if using JSON credentials, >= 0.20.0 if using preemptible option" notes: - JSON credentials strongly preferred. author: "Gwenael Pellen (@GwenaelPellenArkeup) <[email protected]>" ''' EXAMPLES = ''' # Usage - name: create instance template named foo gce_instance_template: name: foo size: n1-standard-1 image_family: ubuntu-1604-lts state: present project_id: "your-project-name" credentials_file: "/path/to/your-key.json" service_account_email: "[email protected]" # Example Playbook - name: Compute Engine Instance Template Examples hosts: localhost vars: service_account_email: "[email protected]" credentials_file: "/path/to/your-key.json" project_id: "your-project-name" tasks: - name: create instance template gce_instance_template: name: my-test-instance-template size: n1-standard-1 image_family: ubuntu-1604-lts state: present project_id: "{{ project_id }}" credentials_file: "{{ credentials_file }}" service_account_email: "{{ service_account_email }}" - name: delete instance template gce_instance_template: name: my-test-instance-template size: n1-standard-1 image_family: ubuntu-1604-lts state: absent project_id: "{{ project_id }}" credentials_file: "{{ credentials_file }}" service_account_email: "{{ service_account_email }}" # Example playbook using disks_gce_struct - name: Compute Engine Instance Template Examples hosts: localhost vars: service_account_email: "[email protected]" credentials_file: "/path/to/your-key.json" project_id: "your-project-name" tasks: - name: create instance template gce_instance_template: name: foo size: n1-standard-1 state: present project_id: "{{ project_id }}" credentials_file: "{{ credentials_file }}" service_account_email: "{{ service_account_email }}" disks_gce_struct: - device_name: /dev/sda boot: true autoDelete: true initializeParams: diskSizeGb: 30 diskType: pd-ssd sourceImage: projects/debian-cloud/global/images/family/debian-8 ''' RETURN = ''' ''' import traceback try: from ast import literal_eval HAS_PYTHON26 = True except ImportError: HAS_PYTHON26 = False try: import libcloud from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver from libcloud.common.google import GoogleBaseError, QuotaExceededError, \ ResourceExistsError, ResourceInUseError, ResourceNotFoundError from libcloud.compute.drivers.gce import GCEAddress _ = Provider.GCE HAS_LIBCLOUD = True except ImportError: HAS_LIBCLOUD = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.gce import gce_connect from ansible.module_utils._text import to_native def get_info(inst): """Retrieves instance template information """ return({ 'name': inst.name, 'extra': inst.extra, }) def create_instance_template(module, gce): """Create an instance template module : AnsibleModule object gce: authenticated GCE libcloud driver Returns: instance template information """ # get info from module name = module.params.get('name') size = module.params.get('size') source = module.params.get('source') image = module.params.get('image') image_family = module.params.get('image_family') disk_type = module.params.get('disk_type') disk_auto_delete = module.params.get('disk_auto_delete') network = module.params.get('network') subnetwork = module.params.get('subnetwork') subnetwork_region = module.params.get('subnetwork_region') can_ip_forward = module.params.get('can_ip_forward') external_ip = module.params.get('external_ip') service_account_permissions = module.params.get( 'service_account_permissions') service_account_email = module.params.get('service_account_email') on_host_maintenance = module.params.get('on_host_maintenance') automatic_restart = module.params.get('automatic_restart') preemptible = module.params.get('preemptible') tags = module.params.get('tags') metadata = module.params.get('metadata') description = module.params.get('description') disks_gce_struct = module.params.get('disks_gce_struct') changed = False # args of ex_create_instancetemplate gce_args = dict( name="instance", size="f1-micro", source=None, image=None, disk_type='pd-standard', disk_auto_delete=True, network='default', subnetwork=None, can_ip_forward=None, external_ip='ephemeral', service_accounts=None, on_host_maintenance=None, automatic_restart=None, preemptible=None, tags=None, metadata=None, description=None, disks_gce_struct=None, nic_gce_struct=None ) gce_args['name'] = name gce_args['size'] = size if source is not None: gce_args['source'] = source if image: gce_args['image'] = image else: if image_family: image = gce.ex_get_image_from_family(image_family) gce_args['image'] = image else: gce_args['image'] = "debian-8" gce_args['disk_type'] = disk_type gce_args['disk_auto_delete'] = disk_auto_delete gce_network = gce.ex_get_network(network) gce_args['network'] = gce_network if subnetwork is not None: gce_args['subnetwork'] = gce.ex_get_subnetwork(subnetwork, region=subnetwork_region) if can_ip_forward is not None: gce_args['can_ip_forward'] = can_ip_forward if external_ip == "ephemeral": instance_external_ip = external_ip elif external_ip == "none": instance_external_ip = None else: try: instance_external_ip = gce.ex_get_address(external_ip) except GoogleBaseError as err: # external_ip is name ? instance_external_ip = external_ip gce_args['external_ip'] = instance_external_ip ex_sa_perms = [] bad_perms = [] if service_account_permissions: for perm in service_account_permissions: if perm not in gce.SA_SCOPES_MAP: bad_perms.append(perm) if len(bad_perms) > 0: module.fail_json(msg='bad permissions: %s' % str(bad_perms)) if service_account_email is not None: ex_sa_perms.append({'email': str(service_account_email)}) else: ex_sa_perms.append({'email': "default"}) ex_sa_perms[0]['scopes'] = service_account_permissions gce_args['service_accounts'] = ex_sa_perms if on_host_maintenance is not None: gce_args['on_host_maintenance'] = on_host_maintenance if automatic_restart is not None: gce_args['automatic_restart'] = automatic_restart if preemptible is not None: gce_args['preemptible'] = preemptible if tags is not None: gce_args['tags'] = tags if disks_gce_struct is not None: gce_args['disks_gce_struct'] = disks_gce_struct # Try to convert the user's metadata value into the format expected # by GCE. First try to ensure user has proper quoting of a # dictionary-like syntax using 'literal_eval', then convert the python # dict into a python list of 'key' / 'value' dicts. Should end up # with: # [ {'key': key1, 'value': value1}, {'key': key2, 'value': value2}, ...] if metadata: if isinstance(metadata, dict): md = metadata else: try: md = literal_eval(str(metadata)) if not isinstance(md, dict): raise ValueError('metadata must be a dict') except ValueError as e: module.fail_json(msg='bad metadata: %s' % str(e)) except SyntaxError as e: module.fail_json(msg='bad metadata syntax') if hasattr(libcloud, '__version__') and libcloud.__version__ < '0.15': items = [] for k, v in md.items(): items.append({"key": k, "value": v}) metadata = {'items': items} else: metadata = md gce_args['metadata'] = metadata if description is not None: gce_args['description'] = description instance = None try: instance = gce.ex_get_instancetemplate(name) except ResourceNotFoundError: try: instance = gce.ex_create_instancetemplate(**gce_args) changed = True except GoogleBaseError as err: module.fail_json( msg='Unexpected error attempting to create instance {}, error: {}' .format( instance, err.value ) ) if instance: json_data = get_info(instance) else: module.fail_json(msg="no instance template!") return (changed, json_data, name) def delete_instance_template(module, gce): """ Delete instance template. module : AnsibleModule object gce: authenticated GCE libcloud driver Returns: instance template information """ name = module.params.get('name') current_state = "absent" changed = False # get instance template instance = None try: instance = gce.ex_get_instancetemplate(name) current_state = "present" except GoogleBaseError as e: json_data = dict(msg='instance template not exists: %s' % to_native(e), exception=traceback.format_exc()) if current_state == "present": rc = instance.destroy() if rc: changed = True else: module.fail_json( msg='instance template destroy failed' ) json_data = {} return (changed, json_data, name) def module_controller(module, gce): ''' Control module state parameter. module : AnsibleModule object gce: authenticated GCE libcloud driver Returns: nothing Exit: AnsibleModule object exit with json data. ''' json_output = dict() state = module.params.get("state") if state == "present": (changed, output, name) = create_instance_template(module, gce) json_output['changed'] = changed json_output['msg'] = output elif state == "absent": (changed, output, name) = delete_instance_template(module, gce) json_output['changed'] = changed json_output['msg'] = output module.exit_json(**json_output) def check_if_system_state_would_be_changed(module, gce): ''' check_if_system_state_would_be_changed ! module : AnsibleModule object gce: authenticated GCE libcloud driver Returns: system_state changed ''' changed = False current_state = "absent" state = module.params.get("state") name = module.params.get("name") try: gce.ex_get_instancetemplate(name) current_state = "present" except GoogleBaseError as e: module.fail_json(msg='GCE get instancetemplate problem: %s' % to_native(e), exception=traceback.format_exc()) if current_state != state: changed = True if current_state == "absent": if changed: output = 'instance template {0} will be created'.format(name) else: output = 'nothing to do for instance template {0} '.format(name) if current_state == "present": if changed: output = 'instance template {0} will be destroyed'.format(name) else: output = 'nothing to do for instance template {0} '.format(name) return (changed, output) def main(): module = AnsibleModule( argument_spec=dict( state=dict(choices=['present', 'absent'], default='present'), name=dict(require=True, aliases=['base_name']), size=dict(default='f1-micro'), source=dict(), image=dict(), image_family=dict(default='debian-8'), disk_type=dict(choices=['pd-standard', 'pd-ssd'], default='pd-standard', type='str'), disk_auto_delete=dict(type='bool', default=True), network=dict(default='default'), subnetwork=dict(), can_ip_forward=dict(type='bool', default=False), external_ip=dict(default='ephemeral'), service_account_email=dict(), service_account_permissions=dict(type='list'), automatic_restart=dict(type='bool', default=None), preemptible=dict(type='bool', default=None), tags=dict(type='list'), metadata=dict(), description=dict(), disks=dict(type='list'), nic_gce_struct=dict(type='list'), project_id=dict(), pem_file=dict(type='path'), credentials_file=dict(type='path'), subnetwork_region=dict(), disks_gce_struct=dict(type='list') ), mutually_exclusive=[['source', 'image']], required_one_of=[['image', 'image_family']], supports_check_mode=True ) if not HAS_PYTHON26: module.fail_json( msg="GCE module requires python's 'ast' module, python v2.6+") if not HAS_LIBCLOUD: module.fail_json( msg='libcloud with GCE support (0.17.0+) required for this module') try: gce = gce_connect(module) except GoogleBaseError as e: module.fail_json(msg='GCE Connexion failed %s' % to_native(e), exception=traceback.format_exc()) if module.check_mode: (changed, output) = check_if_system_state_would_be_changed(module, gce) module.exit_json( changed=changed, msg=output ) else: module_controller(module, gce) if __name__ == '__main__': main()
gpl-3.0
khchine5/xl
lino_xl/lib/ana/models.py
1
11111
# -*- coding: UTF-8 -*- # Copyright 2017-2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.exceptions import ValidationError from lino.api import dd, rt from lino.mixins import Referrable, Sequenced from lino.utils.mldbc.mixins import BabelDesignated from lino_xl.lib.ledger.choicelists import VoucherTypes from lino_xl.lib.ledger.ui import AccountBalances from lino_xl.lib.ledger.mixins import ItemsByVoucher from lino_xl.lib.ledger.roles import LedgerUser, LedgerStaff class Group(BabelDesignated, Referrable): ref_max_length = 10 class Meta: verbose_name = _("Analytical account group") verbose_name_plural = _("Analytical account groups") class Groups(dd.Table): model = 'ana.Group' required_roles = dd.login_required(LedgerStaff) stay_in_grid = True order_by = ['ref'] column_names = 'ref designation *' insert_layout = """ designation ref """ detail_layout = """ ref designation id AccountsByGroup """ @dd.python_2_unicode_compatible class Account(BabelDesignated, Sequenced, Referrable): ref_max_length = 10 class Meta: verbose_name = _("Analytical account") verbose_name_plural = _("Analytical accounts") ordering = ['ref'] group = dd.ForeignKey( 'ana.Group', verbose_name=_("Group"), blank=True, null=True) def full_clean(self, *args, **kw): if self.group_id is not None: if not self.ref: qs = rt.models.ana.Account.objects.all() self.ref = str(qs.count() + 1) if not self.designation: self.designation = self.group.designation # if self.default_dc is None: # self.default_dc = self.type.dc super(Account, self).full_clean(*args, **kw) def __str__(self): return "({ref}) {title}".format( ref=self.ref, title=dd.babelattr(self, 'designation')) class Accounts(dd.Table): model = 'ana.Account' required_roles = dd.login_required(LedgerStaff) stay_in_grid = True order_by = ['ref'] column_names = "ref designation group *" insert_layout = """ designation ref group """ detail_layout = """ ref designation group id ana.MovementsByAccount """ class AccountsByGroup(Accounts): required_roles = dd.login_required() master_key = 'group' column_names = "ref designation *" class MovementsByAccount(dd.Table): model = 'ledger.Movement' master_key = 'ana_account' from lino_xl.lib.ledger.models import Voucher from lino_xl.lib.ledger.mixins import Matching, AccountVoucherItem from lino_xl.lib.sepa.mixins import Payable from lino_xl.lib.vat.mixins import VatDocument, VatItemBase from lino_xl.lib.ledger.ui import PartnerVouchers, ByJournal, PrintableByJournal # class MakeCopy(dd.Action): # button_text = u"\u2042" # ASTERISM (⁂) # label = _("Make copy") # show_in_workflow = True # show_in_bbar = False # copy_item_fields = set('account ana_account total_incl seqno'.split()) # parameters = dict( # partner=dd.ForeignKey('contacts.Partner'), # account=dd.ForeignKey('accounts.Account', blank=True), # ana_account=dd.ForeignKey('ana.Account', blank=True), # subject=models.CharField( # _("Subject"), max_length=200, blank=True), # your_ref=models.CharField( # _("Your ref"), max_length=200, blank=True), # entry_date=models.DateField(_("Entry date")), # total_incl=dd.PriceField(_("Total incl VAT"), blank=True), # ) # params_layout = """ # entry_date partner # your_ref # subject total_incl # account ana_account # """ # def action_param_defaults(self, ar, obj, **kw): # kw = super(MakeCopy, self).action_param_defaults(ar, obj, **kw) # kw.update(your_ref=obj.your_ref) # kw.update(subject=obj.narration) # kw.update(entry_date=obj.entry_date) # kw.update(partner=obj.partner) # # qs = obj.items.all() # # if qs.count(): # # kw.update(product=qs[0].product) # # kw.update(total_incl=obj.total_incl) # return kw # # def partner_changed(self, ar, obj, **kw): # # pass # def run_from_ui(self, ar, **kw): # # raise Warning("20180802") # VoucherStates = rt.models.ledger.VoucherStates # obj = ar.selected_rows[0] # pv = ar.action_param_values # kw = dict( # journal=obj.journal, # user=ar.get_user(), # partner=pv.partner, entry_date=pv.entry_date, # narration=pv.subject, # your_ref=pv.your_ref) # new = obj.__class__(**kw) # new.fill_defaults() # new.full_clean() # new.save() # if pv.total_incl: # if not pv.account: # tt = obj.journal.trade_type # pv.account = tt.get_partner_invoice_account(pv.partner) # if pv.account: # if not pv.ana_account: # pv.ana_account = pv.account.ana_account # else: # qs = obj.items.all() # if qs.count(): # pv.account = qs[0].account # if not pv.ana_account: # pv.ana_account = qs[0].ana_account # if not pv.account.needs_ana: # pv.ana_account = None # item = new.add_voucher_item( # total_incl=pv.total_incl, account=pv.account, # seqno=1, # ana_account=pv.ana_account) # item.total_incl_changed(ar) # item.full_clean() # item.save() # else: # for olditem in obj.items.all(): # # ikw = dict() # # for k in self.copy_item_fields: # # ikw[k] = getattr(olditem, k) # ikw = { k: getattr(olditem, k) # for k in self.copy_item_fields} # item = new.add_voucher_item(**ikw) # item.total_incl_changed(ar) # item.full_clean() # item.save() # new.full_clean() # new.register_voucher(ar) # new.state = VoucherStates.registered # new.save() # ar.goto_instance(new) # ar.success() class AnaAccountInvoice(VatDocument, Payable, Voucher, Matching): class Meta: verbose_name = _("Analytic invoice") verbose_name_plural = _("Analytic invoices") # make_copy = MakeCopy() # probably no longer needed because now we have # VatDocument.items_edited class InvoiceItem(AccountVoucherItem, VatItemBase): class Meta: app_label = 'ana' verbose_name = _("Analytic invoice item") verbose_name_plural = _("Analytic invoice items") voucher = dd.ForeignKey('ana.AnaAccountInvoice', related_name='items') ana_account = dd.ForeignKey('ana.Account', blank=True, null=True) title = models.CharField(_("Description"), max_length=200, blank=True) def full_clean(self, *args, **kwargs): super(InvoiceItem, self).full_clean(*args, **kwargs) if self.account_id and self.account.needs_ana: if not self.ana_account_id: if self.account.ana_account_id: self.ana_account = self.account.ana_account def get_ana_account(self): return self.ana_account def account_changed(self, ar=None): if self.account_id: if self.account.needs_ana: # if the general account an analytic one but has no # default value (needs_ana is checked but ana_account # empty), leave the current one. if self.account.ana_account: self.ana_account = self.account.ana_account else: self.ana_account = None class InvoiceDetail(dd.DetailLayout): main = "general ledger" general = dd.Panel(""" topleft:60 totals:20 ItemsByInvoice """, label=_("General")) totals = """ total_base total_vat total_incl """ topleft = """number entry_date #voucher_date partner payment_term due_date your_ref vat_regime workflow_buttons user """ ledger = dd.Panel(""" journal accounting_period id narration ledger.MovementsByVoucher """, label=_("Ledger")) class Invoices(PartnerVouchers): """The table of all :class:`VatAccountInvoice<lino_xl.lib.vat.models.VatAccountInvoice>` objects. """ required_roles = dd.login_required(LedgerUser) model = 'ana.AnaAccountInvoice' order_by = ["-id"] column_names = "entry_date number_with_year partner total_incl user id *" detail_layout = 'ana.InvoiceDetail' insert_layout = """ journal partner entry_date total_incl """ # start_at_bottom = True class InvoicesByJournal(ByJournal, Invoices): """Shows all invoices of a given journal (whose :attr:`voucher_type<lino_xl.lib.ledger.models.Journal.voucher_type>` must be :class:`lino_xl.lib.vat.models.VatAccountInvoice`) """ # order_by = ["-accounting_period__year", "-number"] params_layout = "partner state year" column_names = "number_with_year entry_date due_date " \ "partner " \ "total_incl " \ "total_base total_vat user workflow_buttons *" #~ "ledger_remark:10 " \ insert_layout = """ partner entry_date total_incl """ class AnalyticAccountBalances(AccountBalances): label = _("Analytic Account Balances") @classmethod def get_request_queryset(self, ar, **filter): return rt.models.ana.Account.objects.order_by( 'group__ref', 'ref') @classmethod def rowmvtfilter(self, row): return dict(ana_account=row) @dd.displayfield(_("Ref")) def ref(self, row, ar): return ar.obj2html(row.group) VoucherTypes.add_item_lazy(InvoicesByJournal) class PrintableInvoicesByJournal(PrintableByJournal, Invoices): label = _("Purchase journal (analytic)") class ItemsByInvoice(ItemsByVoucher): model = 'ana.InvoiceItem' column_names = "account title ana_account vat_class total_base total_vat total_incl *" display_mode = 'grid' dd.inject_field( 'ledger.Movement', 'ana_account', dd.ForeignKey('ana.Account', blank=True, null=True)) dd.inject_field( 'accounts.Account', 'ana_account', dd.ForeignKey('ana.Account', blank=True, null=True)) dd.inject_field( 'accounts.Account', 'needs_ana', models.BooleanField(_("Needs analytical account"), default=False)) # if dd.is_installed('vat'): # dd.inject_field( # 'vat.InvoiceItem', 'ana_account', # dd.ForeignKey('ana.Account', blank=True, null=True))
bsd-2-clause
dysya92/monkeys
flask/lib/python2.7/site-packages/six.py
320
27344
"""Utilities for writing code that runs on Python 2 and 3""" # Copyright (c) 2010-2014 Benjamin Peterson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import absolute_import import functools import operator import sys import types __author__ = "Benjamin Peterson <[email protected]>" __version__ = "1.8.0" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, class_types = type, text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = basestring, integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. # This is a bit ugly, but it avoids running this again. delattr(obj.__class__, self.name) return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_modules = {} def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod def _get_module(self, fullname): return self.known_modules[self.name + "." + fullname] def find_module(self, fullname, path=None): if fullname in self.known_modules: return self return None def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname) def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__") def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule): _importer._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse") class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error") class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request") class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response") class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser") class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ['parse', 'error', 'request', 'response', 'robotparser'] _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) else: def iterkeys(d, **kw): return iter(d.iterkeys(**kw)) def itervalues(d, **kw): return iter(d.itervalues(**kw)) def iteritems(d, **kw): return iter(d.iteritems(**kw)) def iterlists(d, **kw): return iter(d.iterlists(**kw)) _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc(iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: def b(s): return s.encode("latin-1") def u(s): return s unichr = chr if sys.version_info[1] <= 1: def int2byte(i): return bytes((i,)) else: # This is about 2x faster than the implementation above on 3.2+ int2byte = operator.methodcaller("to_bytes", 1, "big") byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO else: def b(s): return s # Workaround for standalone backslash def u(s): return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) def iterbytes(buf): return (ord(byte) for byte in buf) import StringIO StringIO = BytesIO = StringIO.StringIO _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" 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_""") exec_("""def reraise(tp, value, tb=None): raise tp, value, tb """) print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): def wrapper(f): f = functools.wraps(wrapped)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if (type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer)
bsd-3-clause
mathLab/RBniCS
rbnics/utils/test/run_and_compare_to_gold.py
1
5296
# Copyright (C) 2015-2021 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later import os import shutil import glob try: import git except ImportError: # Full git support is only required by regold action; # null and compare actions do not require any git support pass from mpi4py.MPI import COMM_WORLD from rbnics.utils.mpi import parallel_io from rbnics.utils.test.diff import diff def run_and_compare_to_gold(subdirectory=""): def run_and_compare_to_gold_decorator(runtest): def run_and_compare_to_gold_function(self): """ Handles the comparison of test/tutorial with gold files """ mpi_comm = COMM_WORLD rootdir = str(self.config.rootdir) # Get action action = self.config.option.action assert action in ("compare", "regold", None) # Get data directory if action is not None: data_dir = self.config.option.data_dir assert data_dir is not None else: data_dir = None # Get current and reference directory current_dir = str(self.fspath.dirname) if action is not None: reference_dir = os.path.join( current_dir.replace(rootdir, data_dir), self.fspath.basename, str(mpi_comm.size)) current_dir = os.path.join(current_dir, subdirectory) reference_dir = os.path.join(reference_dir, subdirectory) else: reference_dir = None # Copy training and testing sets if action is not None: def copy_training_and_testing_sets(): for set_ in ("testing_set", "training_set"): set_directories = glob.glob(os.path.join(reference_dir, "**", set_), recursive=True) if action == "compare": assert len(set_directories) > 0 for set_directory in set_directories: set_directory = os.path.relpath(set_directory, reference_dir) if os.path.exists(os.path.join(reference_dir, set_directory)): if os.path.exists(os.path.join(current_dir, set_directory)): shutil.rmtree(os.path.join(current_dir, set_directory)) shutil.copytree(os.path.join(reference_dir, set_directory), os.path.join(current_dir, set_directory)) parallel_io(copy_training_and_testing_sets, mpi_comm) # Run test/tutorial runtest(self) # Process results def process_results(): if action == "compare": failures = list() filenames = glob.glob(os.path.join(reference_dir, "**", "*.*"), recursive=True) assert len(filenames) > 0 for filename in filenames: filename = os.path.relpath(filename, reference_dir) diffs = diff(os.path.join(reference_dir, filename), os.path.join(current_dir, filename)) if len(diffs) > 0: failures.append(filename) os.makedirs(os.path.dirname(os.path.join(current_dir, filename + "_diff")), exist_ok=True) with open(os.path.join(current_dir, filename + "_diff"), "w") as failure_file: failure_file.writelines(diffs) if len(failures) > 0: raise RuntimeError( self.name + ", comparison has failed for the following files: " + str(failures) + ".") elif action == "regold": data_dir_repo = git.Repo(data_dir) assert not data_dir_repo.is_dirty() # Move current files to reference directory if os.path.exists(reference_dir): shutil.rmtree(reference_dir) shutil.copytree(current_dir, reference_dir) if os.path.exists(os.path.join(reference_dir, ".gitignore")): os.remove(os.path.join(reference_dir, ".gitignore")) data_dir_repo.git.add([reference_dir]) # Commit changes commit = str(git.Repo(rootdir).head.commit) relpath = os.path.relpath(str(self.fspath), rootdir) if self.name != relpath: message = ("Automatic regold of " + self.name + " in " + relpath + " at upstream commit " + commit) else: message = "Automatic regold of " + relpath + " at upstream commit " + commit data_dir_repo.git.commit(message=message) # Clean repository data_dir_repo.git.clean("-Xdf") parallel_io(process_results, mpi_comm) return run_and_compare_to_gold_function return run_and_compare_to_gold_decorator
lgpl-3.0
rahushen/ansible
lib/ansible/modules/network/nxos/nxos_bgp_neighbor_af.py
5
27591
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = ''' --- module: nxos_bgp_neighbor_af extends_documentation_fragment: nxos version_added: "2.2" short_description: Manages BGP address-family's neighbors configuration. description: - Manages BGP address-family's neighbors configurations on NX-OS switches. author: Gabriele Gerbino (@GGabriele) notes: - Tested against NXOSv 7.3.(0)D1(1) on VIRL - C(state=absent) removes the whole BGP address-family's neighbor configuration. - Default, when supported, removes properties - In order to default maximum-prefix configuration, only C(max_prefix_limit=default) is needed. options: asn: description: - BGP autonomous system number. Valid values are String, Integer in ASPLAIN or ASDOT notation. required: true vrf: description: - Name of the VRF. The name 'default' is a valid VRF representing the global bgp. required: false default: default neighbor: description: - Neighbor Identifier. Valid values are string. Neighbors may use IPv4 or IPv6 notation, with or without prefix length. required: true afi: description: - Address Family Identifier. required: true choices: ['ipv4','ipv6', 'vpnv4', 'vpnv6', 'l2vpn'] safi: description: - Sub Address Family Identifier. required: true choices: ['unicast','multicast', 'evpn'] additional_paths_receive: description: - Valid values are enable for basic command enablement; disable for disabling the command at the neighbor af level (it adds the disable keyword to the basic command); and inherit to remove the command at this level (the command value is inherited from a higher BGP layer). required: false choices: ['enable','disable', 'inherit'] default: null additional_paths_send: description: - Valid values are enable for basic command enablement; disable for disabling the command at the neighbor af level (it adds the disable keyword to the basic command); and inherit to remove the command at this level (the command value is inherited from a higher BGP layer). required: false choices: ['enable','disable', 'inherit'] default: null advertise_map_exist: description: - Conditional route advertisement. This property requires two route maps, an advertise-map and an exist-map. Valid values are an array specifying both the advertise-map name and the exist-map name, or simply 'default' e.g. ['my_advertise_map', 'my_exist_map']. This command is mutually exclusive with the advertise_map_non_exist property. required: false default: null advertise_map_non_exist: description: - Conditional route advertisement. This property requires two route maps, an advertise-map and an exist-map. Valid values are an array specifying both the advertise-map name and the non-exist-map name, or simply 'default' e.g. ['my_advertise_map', 'my_non_exist_map']. This command is mutually exclusive with the advertise_map_exist property. required: false default: null allowas_in: description: - Activate allowas-in property required: false default: null allowas_in_max: description: - Max-occurrences value for allowas_in. Valid values are an integer value or 'default'. This is mutually exclusive with allowas_in. required: false default: null as_override: description: - Activate the as-override feature. required: false choices: ['true', 'false'] default: null default_originate: description: - Activate the default-originate feature. required: false choices: ['true', 'false'] default: null default_originate_route_map: description: - Route-map for the default_originate property. Valid values are a string defining a route-map name, or 'default'. This is mutually exclusive with default_originate. required: false default: null disable_peer_as_check: description: - Disable checking of peer AS-number while advertising required: false choices: ['true', 'false'] version_added: 2.5 filter_list_in: description: - Valid values are a string defining a filter-list name, or 'default'. required: false default: null filter_list_out: description: - Valid values are a string defining a filter-list name, or 'default'. required: false default: null max_prefix_limit: description: - maximum-prefix limit value. Valid values are an integer value or 'default'. required: false default: null max_prefix_interval: description: - Optional restart interval. Valid values are an integer. Requires max_prefix_limit. May not be combined with max_prefix_warning. required: false default: null max_prefix_threshold: description: - Optional threshold percentage at which to generate a warning. Valid values are an integer value. Requires max_prefix_limit. required: false default: null max_prefix_warning: description: - Optional warning-only keyword. Requires max_prefix_limit. May not be combined with max_prefix_interval. required: false choices: ['true','false'] default: null next_hop_self: description: - Activate the next-hop-self feature. required: false choices: ['true','false'] default: null next_hop_third_party: description: - Activate the next-hop-third-party feature. required: false choices: ['true','false'] default: null prefix_list_in: description: - Valid values are a string defining a prefix-list name, or 'default'. required: false default: null prefix_list_out: description: - Valid values are a string defining a prefix-list name, or 'default'. required: false default: null route_map_in: description: - Valid values are a string defining a route-map name, or 'default'. required: false default: null route_map_out: description: - Valid values are a string defining a route-map name, or 'default'. required: false default: null route_reflector_client: description: - Router reflector client. required: false choices: ['true','false'] default: null send_community: description: - send-community attribute. required: false choices: ['none', 'both', 'extended', 'standard', 'default'] default: null soft_reconfiguration_in: description: - Valid values are 'enable' for basic command enablement; 'always' to add the always keyword to the basic command; and 'inherit' to remove the command at this level (the command value is inherited from a higher BGP layer). required: false choices: ['enable','always','inherit'] default: null soo: description: - Site-of-origin. Valid values are a string defining a VPN extcommunity or 'default'. required: false default: null suppress_inactive: description: - suppress-inactive feature. required: false choices: ['true','false','default'] default: null unsuppress_map: description: - unsuppress-map. Valid values are a string defining a route-map name or 'default'. required: false default: null weight: description: - Weight value. Valid values are an integer value or 'default'. required: false default: null state: description: - Determines whether the config should be present or not on the device. required: false default: present choices: ['present','absent'] ''' EXAMPLES = ''' - name: configure RR client nxos_bgp_neighbor_af: asn: 65535 neighbor: '3.3.3.3' afi: ipv4 safi: unicast route_reflector_client: true state: present ''' RETURN = ''' commands: description: commands sent to the device returned: always type: list sample: ["router bgp 65535", "neighbor 3.3.3.3", "address-family ipv4 unicast", "route-reflector-client"] ''' import re from ansible.module_utils.network.nxos.nxos import get_config, load_config from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.common.config import CustomNetworkConfig BOOL_PARAMS = [ 'allowas_in', 'as_override', 'default_originate', 'disable_peer_as_check', 'next_hop_self', 'next_hop_third_party', 'route_reflector_client', 'suppress_inactive' ] PARAM_TO_COMMAND_KEYMAP = { 'afi': 'address-family', 'asn': 'router bgp', 'neighbor': 'neighbor', 'additional_paths_receive': 'capability additional-paths receive', 'additional_paths_send': 'capability additional-paths send', 'advertise_map_exist': 'advertise-map exist-map', 'advertise_map_non_exist': 'advertise-map non-exist-map', 'allowas_in': 'allowas-in', 'allowas_in_max': 'allowas-in', 'as_override': 'as-override', 'default_originate': 'default-originate', 'default_originate_route_map': 'default-originate route-map', 'disable_peer_as_check': 'disable-peer-as-check', 'filter_list_in': 'filter-list in', 'filter_list_out': 'filter-list out', 'max_prefix_limit': 'maximum-prefix', 'max_prefix_interval': 'maximum-prefix interval', 'max_prefix_threshold': 'maximum-prefix threshold', 'max_prefix_warning': 'maximum-prefix warning', 'next_hop_self': 'next-hop-self', 'next_hop_third_party': 'next-hop-third-party', 'prefix_list_in': 'prefix-list in', 'prefix_list_out': 'prefix-list out', 'route_map_in': 'route-map in', 'route_map_out': 'route-map out', 'route_reflector_client': 'route-reflector-client', 'safi': 'address-family', 'send_community': 'send-community', 'soft_reconfiguration_in': 'soft-reconfiguration inbound', 'soo': 'soo', 'suppress_inactive': 'suppress-inactive', 'unsuppress_map': 'unsuppress-map', 'weight': 'weight', 'vrf': 'vrf' } def get_value(arg, config, module): custom = [ 'additional_paths_send', 'additional_paths_receive', 'max_prefix_limit', 'max_prefix_interval', 'max_prefix_threshold', 'max_prefix_warning', 'send_community', 'soft_reconfiguration_in' ] command = PARAM_TO_COMMAND_KEYMAP[arg] has_command = re.search(r'^\s+{0}\s*'.format(command), config, re.M) has_command_val = re.search(r'(?:{0}\s)(?P<value>.*)$'.format(command), config, re.M) value = '' if arg in custom: value = get_custom_value(arg, config, module) elif arg == 'next_hop_third_party': has_no_command = re.search(r'^\s+no\s+{0}\s*$'.format(command), config, re.M) value = False if not has_no_command: value = True elif arg in BOOL_PARAMS: value = False if has_command: value = True elif command.startswith('advertise-map'): value = [] has_adv_map = re.search(r'{0}\s(?P<value1>.*)\s{1}\s(?P<value2>.*)$'.format(*command.split()), config, re.M) if has_adv_map: value = list(has_adv_map.groups()) elif command.split()[0] in ['filter-list', 'prefix-list', 'route-map']: has_cmd_direction_val = re.search(r'{0}\s(?P<value>.*)\s{1}$'.format(*command.split()), config, re.M) if has_cmd_direction_val: value = has_cmd_direction_val.group('value') elif has_command_val: value = has_command_val.group('value') return value def get_custom_value(arg, config, module): command = PARAM_TO_COMMAND_KEYMAP.get(arg) splitted_config = config.splitlines() value = '' command_re = re.compile(r'\s+{0}\s*'.format(command), re.M) has_command = command_re.search(config) command_val_re = re.compile(r'(?:{0}\s)(?P<value>.*)$'.format(command), re.M) has_command_val = command_val_re.search(config) if arg.startswith('additional_paths'): value = 'inherit' for line in splitted_config: if command in line: if 'disable' in line: value = 'disable' else: value = 'enable' elif arg.startswith('max_prefix'): for line in splitted_config: if 'maximum-prefix' in line: splitted_line = line.split() if arg == 'max_prefix_limit': value = splitted_line[1] elif arg == 'max_prefix_interval' and 'restart' in line: value = splitted_line[-1] elif arg == 'max_prefix_threshold' and len(splitted_line) > 2: try: int(splitted_line[2]) value = splitted_line[2] except ValueError: value = '' elif arg == 'max_prefix_warning': value = 'warning-only' in line elif arg == 'soft_reconfiguration_in': value = 'inherit' for line in splitted_config: if command in line: if 'always' in line: value = 'always' else: value = 'enable' elif arg == 'send_community': value = 'none' for line in splitted_config: if command in line: if 'extended' in line: if value == 'standard': value = 'both' else: value = 'extended' elif 'both' in line: value = 'both' else: value = 'standard' return value def get_existing(module, args, warnings): existing = {} netcfg = CustomNetworkConfig(indent=2, contents=get_config(module)) asn_regex = re.compile(r'.*router\sbgp\s(?P<existing_asn>\d+(\.\d+)?).*', re.S) match_asn = asn_regex.match(str(netcfg)) if match_asn: existing_asn = match_asn.group('existing_asn') parents = ["router bgp {0}".format(existing_asn)] if module.params['vrf'] != 'default': parents.append('vrf {0}'.format(module.params['vrf'])) parents.append('neighbor {0}'.format(module.params['neighbor'])) parents.append('address-family {0} {1}'.format(module.params['afi'], module.params['safi'])) config = netcfg.get_section(parents) if config: for arg in args: if arg not in ['asn', 'vrf', 'neighbor', 'afi', 'safi']: existing[arg] = get_value(arg, config, module) existing['asn'] = existing_asn existing['neighbor'] = module.params['neighbor'] existing['vrf'] = module.params['vrf'] existing['afi'] = module.params['afi'] existing['safi'] = module.params['safi'] else: warnings.append("The BGP process didn't exist but the task just created it.") return existing def apply_key_map(key_map, table): new_dict = {} for key in table: new_key = key_map.get(key) if new_key: new_dict[new_key] = table.get(key) return new_dict def get_default_command(key, value, existing_commands): command = '' if existing_commands.get(key): existing_value = existing_commands.get(key) if value == 'inherit': if existing_value != 'inherit': command = 'no {0}'.format(key) else: if key == 'advertise-map exist-map': command = 'no advertise-map {0} exist-map {1}'.format( existing_value[0], existing_value[1]) elif key == 'advertise-map non-exist-map': command = 'no advertise-map {0} non-exist-map {1}'.format( existing_value[0], existing_value[1]) elif key == 'filter-list in': command = 'no filter-list {0} in'.format(existing_value) elif key == 'filter-list out': command = 'no filter-list {0} out'.format(existing_value) elif key == 'prefix-list in': command = 'no prefix-list {0} in'.format(existing_value) elif key == 'prefix-list out': command = 'no prefix-list {0} out'.format(existing_value) elif key == 'route-map in': command = 'no route-map {0} in'.format(existing_value) elif key == 'route-map out': command = 'no route-map {0} out'.format(existing_value) elif key.startswith('maximum-prefix'): command = 'no maximum-prefix' elif key == 'allowas-in max': command = ['no allowas-in {0}'.format(existing_value)] command.append('allowas-in') else: command = 'no {0} {1}'.format(key, existing_value) else: if key.replace(' ', '_').replace('-', '_') in BOOL_PARAMS: command = 'no {0}'.format(key) return command def fix_proposed(module, existing, proposed): allowas_in = proposed.get('allowas_in') allowas_in_max = proposed.get('allowas_in_max') if allowas_in_max and not allowas_in: proposed.pop('allowas_in_max') elif allowas_in and allowas_in_max: proposed.pop('allowas_in') if existing.get('send_community') == 'none' and proposed.get('send_community') == 'default': proposed.pop('send_community') return proposed def state_present(module, existing, proposed, candidate): commands = list() proposed = fix_proposed(module, existing, proposed) proposed_commands = apply_key_map(PARAM_TO_COMMAND_KEYMAP, proposed) existing_commands = apply_key_map(PARAM_TO_COMMAND_KEYMAP, existing) for key, value in proposed_commands.items(): if value in ['inherit', 'default']: command = get_default_command(key, value, existing_commands) if isinstance(command, str): if command and command not in commands: commands.append(command) elif isinstance(command, list): for cmd in command: if cmd not in commands: commands.append(cmd) elif key.startswith('maximum-prefix'): if module.params['max_prefix_limit'] != 'default': command = 'maximum-prefix {0}'.format(module.params['max_prefix_limit']) if module.params['max_prefix_threshold']: command += ' {0}'.format(module.params['max_prefix_threshold']) if module.params['max_prefix_interval']: command += ' restart {0}'.format(module.params['max_prefix_interval']) elif module.params['max_prefix_warning']: command += ' warning-only' commands.append(command) elif value is True: commands.append(key) elif value is False: commands.append('no {0}'.format(key)) elif key == 'address-family': commands.append("address-family {0} {1}".format(module.params['afi'], module.params['safi'])) elif key.startswith('capability additional-paths'): command = key if value == 'disable': command += ' disable' commands.append(command) elif key.startswith('advertise-map'): direction = key.split()[1] commands.append('advertise-map {1} {0} {2}'.format(direction, *value)) elif key.split()[0] in ['filter-list', 'prefix-list', 'route-map']: commands.append('{1} {0} {2}'.format(value, *key.split())) elif key == 'soft-reconfiguration inbound': command = '' if value == 'enable': command = key elif value == 'always': command = '{0} {1}'.format(key, value) commands.append(command) elif key == 'send-community': command = key if value in ['standard', 'extended']: commands.append('no ' + key + ' both') command += ' {0}'.format(value) commands.append(command) else: command = '{0} {1}'.format(key, value) commands.append(command) if commands: parents = ['router bgp {0}'.format(module.params['asn'])] if module.params['vrf'] != 'default': parents.append('vrf {0}'.format(module.params['vrf'])) parents.append('neighbor {0}'.format(module.params['neighbor'])) af_command = 'address-family {0} {1}'.format( module.params['afi'], module.params['safi']) parents.append(af_command) if af_command in commands: commands.remove(af_command) candidate.add(commands, parents=parents) def state_absent(module, existing, candidate): commands = [] parents = ["router bgp {0}".format(module.params['asn'])] if module.params['vrf'] != 'default': parents.append('vrf {0}'.format(module.params['vrf'])) parents.append('neighbor {0}'.format(module.params['neighbor'])) commands.append('no address-family {0} {1}'.format( module.params['afi'], module.params['safi'])) candidate.add(commands, parents=parents) def main(): argument_spec = dict( asn=dict(required=True, type='str'), vrf=dict(required=False, type='str', default='default'), neighbor=dict(required=True, type='str'), afi=dict(required=True, type='str'), safi=dict(required=True, type='str'), additional_paths_receive=dict(required=False, type='str', choices=['enable', 'disable', 'inherit']), additional_paths_send=dict(required=False, type='str', choices=['enable', 'disable', 'inherit']), advertise_map_exist=dict(required=False, type='list'), advertise_map_non_exist=dict(required=False, type='list'), allowas_in=dict(required=False, type='bool'), allowas_in_max=dict(required=False, type='str'), as_override=dict(required=False, type='bool'), default_originate=dict(required=False, type='bool'), default_originate_route_map=dict(required=False, type='str'), disable_peer_as_check=dict(required=False, type='bool'), filter_list_in=dict(required=False, type='str'), filter_list_out=dict(required=False, type='str'), max_prefix_limit=dict(required=False, type='str'), max_prefix_interval=dict(required=False, type='str'), max_prefix_threshold=dict(required=False, type='str'), max_prefix_warning=dict(required=False, type='bool'), next_hop_self=dict(required=False, type='bool'), next_hop_third_party=dict(required=False, type='bool'), prefix_list_in=dict(required=False, type='str'), prefix_list_out=dict(required=False, type='str'), route_map_in=dict(required=False, type='str'), route_map_out=dict(required=False, type='str'), route_reflector_client=dict(required=False, type='bool'), send_community=dict(required=False, choices=['none', 'both', 'extended', 'standard', 'default']), soft_reconfiguration_in=dict(required=False, type='str', choices=['enable', 'always', 'inherit']), soo=dict(required=False, type='str'), suppress_inactive=dict(required=False, type='bool'), unsuppress_map=dict(required=False, type='str'), weight=dict(required=False, type='str'), state=dict(choices=['present', 'absent'], default='present', required=False), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[['advertise_map_exist', 'advertise_map_non_exist'], ['max_prefix_interval', 'max_prefix_warning'], ['default_originate', 'default_originate_route_map'], ['allowas_in', 'allowas_in_max']], supports_check_mode=True, ) warnings = list() check_args(module, warnings) result = dict(changed=False, warnings=warnings) state = module.params['state'] for key in ['max_prefix_interval', 'max_prefix_warning', 'max_prefix_threshold']: if module.params[key] and not module.params['max_prefix_limit']: module.fail_json( msg='max_prefix_limit is required when using %s' % key ) if module.params['vrf'] == 'default' and module.params['soo']: module.fail_json(msg='SOO is only allowed in non-default VRF') args = PARAM_TO_COMMAND_KEYMAP.keys() existing = get_existing(module, args, warnings) if existing.get('asn') and state == 'present': if existing.get('asn') != module.params['asn']: module.fail_json(msg='Another BGP ASN already exists.', proposed_asn=module.params['asn'], existing_asn=existing.get('asn')) for param in ['advertise_map_exist', 'advertise_map_non_exist']: if module.params[param] == ['default']: module.params[param] = 'default' proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) proposed = {} for key, value in proposed_args.items(): if key not in ['asn', 'vrf', 'neighbor']: if not isinstance(value, list): if str(value).lower() == 'true': value = True elif str(value).lower() == 'false': value = False elif str(value).lower() == 'default': if key in BOOL_PARAMS: value = False else: value = 'default' elif key == 'send_community' and str(value).lower() == 'none': value = 'default' if existing.get(key) != value: proposed[key] = value candidate = CustomNetworkConfig(indent=3) if state == 'present': state_present(module, existing, proposed, candidate) elif state == 'absent' and existing: state_absent(module, existing, candidate) if candidate: candidate = candidate.items_text() load_config(module, candidate) result['changed'] = True result['commands'] = candidate else: result['commands'] = [] module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
CollinsIchigo/hdx_2
venv/lib/python2.7/site-packages/_markerlib/markers.py
1769
3979
# -*- coding: utf-8 -*- """Interpret PEP 345 environment markers. EXPR [in|==|!=|not in] EXPR [or|and] ... where EXPR belongs to any of those: python_version = '%s.%s' % (sys.version_info[0], sys.version_info[1]) python_full_version = sys.version.split()[0] os.name = os.name sys.platform = sys.platform platform.version = platform.version() platform.machine = platform.machine() platform.python_implementation = platform.python_implementation() a free string, like '2.6', or 'win32' """ __all__ = ['default_environment', 'compile', 'interpret'] import ast import os import platform import sys import weakref _builtin_compile = compile try: from platform import python_implementation except ImportError: if os.name == "java": # Jython 2.5 has ast module, but not platform.python_implementation() function. def python_implementation(): return "Jython" else: raise # restricted set of variables _VARS = {'sys.platform': sys.platform, 'python_version': '%s.%s' % sys.version_info[:2], # FIXME parsing sys.platform is not reliable, but there is no other # way to get e.g. 2.7.2+, and the PEP is defined with sys.version 'python_full_version': sys.version.split(' ', 1)[0], 'os.name': os.name, 'platform.version': platform.version(), 'platform.machine': platform.machine(), 'platform.python_implementation': python_implementation(), 'extra': None # wheel extension } for var in list(_VARS.keys()): if '.' in var: _VARS[var.replace('.', '_')] = _VARS[var] def default_environment(): """Return copy of default PEP 385 globals dictionary.""" return dict(_VARS) class ASTWhitelist(ast.NodeTransformer): def __init__(self, statement): self.statement = statement # for error messages ALLOWED = (ast.Compare, ast.BoolOp, ast.Attribute, ast.Name, ast.Load, ast.Str) # Bool operations ALLOWED += (ast.And, ast.Or) # Comparison operations ALLOWED += (ast.Eq, ast.Gt, ast.GtE, ast.In, ast.Is, ast.IsNot, ast.Lt, ast.LtE, ast.NotEq, ast.NotIn) def visit(self, node): """Ensure statement only contains allowed nodes.""" if not isinstance(node, self.ALLOWED): raise SyntaxError('Not allowed in environment markers.\n%s\n%s' % (self.statement, (' ' * node.col_offset) + '^')) return ast.NodeTransformer.visit(self, node) def visit_Attribute(self, node): """Flatten one level of attribute access.""" new_node = ast.Name("%s.%s" % (node.value.id, node.attr), node.ctx) return ast.copy_location(new_node, node) def parse_marker(marker): tree = ast.parse(marker, mode='eval') new_tree = ASTWhitelist(marker).generic_visit(tree) return new_tree def compile_marker(parsed_marker): return _builtin_compile(parsed_marker, '<environment marker>', 'eval', dont_inherit=True) _cache = weakref.WeakValueDictionary() def compile(marker): """Return compiled marker as a function accepting an environment dict.""" try: return _cache[marker] except KeyError: pass if not marker.strip(): def marker_fn(environment=None, override=None): """""" return True else: compiled_marker = compile_marker(parse_marker(marker)) def marker_fn(environment=None, override=None): """override updates environment""" if override is None: override = {} if environment is None: environment = default_environment() environment.update(override) return eval(compiled_marker, environment) marker_fn.__doc__ = marker _cache[marker] = marker_fn return _cache[marker] def interpret(marker, environment=None): return compile(marker)(environment)
mit
cschnei3/forseti-security
tests/inventory/pipelines/test_data/fake_configs.py
3
1090
#!/usr/bin/env python # Copyright 2017 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. """Test IAM policies data.""" FAKE_CONFIGS = { 'inventory_groups': True, 'groups_service_account_key_file': '/foo/path', 'domain_super_admin_email': '[email protected]', 'organization_id': '66666', 'max_crm_api_calls_per_100_seconds': 10000000, 'db_name': 'forseti_security', 'db_user': 'sqlproxy', 'db_host': '127.0.0.1', 'email_sender': '[email protected]', 'email_recipient': '[email protected]', 'sendgrid_api_key': 'foo_email_key', }
apache-2.0
alistairlow/tensorflow
tensorflow/python/framework/random_seed_test.py
25
2520
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.python.framework.random_seed.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.eager import context from tensorflow.python.framework import random_seed from tensorflow.python.framework import test_util from tensorflow.python.platform import test class RandomSeedTest(test.TestCase): @test_util.run_in_graph_and_eager_modes() def testRandomSeed(self): test_cases = [ # Each test case is a tuple with input to get_seed: # (input_graph_seed, input_op_seed) # and output from get_seed: # (output_graph_seed, output_op_seed) ((None, None), (None, None)), ((None, 1), (random_seed.DEFAULT_GRAPH_SEED, 1)), ((1, 1), (1, 1)), ((0, 0), (0, 2**31 - 1)), # Avoid nondeterministic (0, 0) output ((2**31 - 1, 0), (0, 2**31 - 1)), # Don't wrap to (0, 0) either ((0, 2**31 - 1), (0, 2**31 - 1)), # Wrapping for the other argument ] if context.in_graph_mode(): # 0 will be the default_graph._lastid. test_cases.append(((1, None), (1, 0))) else: # operation seed is random number generated based on global seed. # it's not tested due to possibility of platform or version difference. pass for tc in test_cases: tinput, toutput = tc[0], tc[1] random_seed.set_random_seed(tinput[0]) g_seed, op_seed = random_seed.get_seed(tinput[1]) msg = 'test_case = {0}, got {1}, want {2}'.format(tinput, (g_seed, op_seed), toutput) self.assertEqual((g_seed, op_seed), toutput, msg=msg) random_seed.set_random_seed(None) if __name__ == '__main__': test.main()
apache-2.0
jeasoft/odoo
addons/base_vat/__openerp__.py
262
2897
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'VAT Number Validation', 'version': '1.0', 'category': 'Hidden/Dependency', 'description': """ VAT validation for Partner's VAT numbers. ========================================= After installing this module, values entered in the VAT field of Partners will be validated for all supported countries. The country is inferred from the 2-letter country code that prefixes the VAT number, e.g. ``BE0477472701`` will be validated using the Belgian rules. There are two different levels of VAT number validation: -------------------------------------------------------- * By default, a simple off-line check is performed using the known validation rules for the country, usually a simple check digit. This is quick and always available, but allows numbers that are perhaps not truly allocated, or not valid anymore. * When the "VAT VIES Check" option is enabled (in the configuration of the user's Company), VAT numbers will be instead submitted to the online EU VIES database, which will truly verify that the number is valid and currently allocated to a EU company. This is a little bit slower than the simple off-line check, requires an Internet connection, and may not be available all the time. If the service is not available or does not support the requested country (e.g. for non-EU countries), a simple check will be performed instead. Supported countries currently include EU countries, and a few non-EU countries such as Chile, Colombia, Mexico, Norway or Russia. For unsupported countries, only the country code will be validated. """, 'author': 'OpenERP SA', 'depends': ['account'], 'website': 'https://www.odoo.com/page/accounting', 'data': ['base_vat_view.xml'], 'installable': True, 'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
txenoo/django-radio
radioco/apps/users/models.py
1
2458
# Radioco - Broadcasting Radio Recording Scheduling system. # Copyright (C) 2014 Iago Veloso Abalo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ckeditor_uploader.fields import RichTextUploadingField from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ class UserProfile(models.Model): user = models.OneToOneField(User, unique=True) bio = RichTextUploadingField(blank=True, verbose_name=_("biography")) avatar = models.ImageField( upload_to='avatars/', default='defaults/default-userprofile-avatar.jpg', verbose_name=_("avatar") ) display_personal_page = models.BooleanField(default=False, verbose_name=_("display personal page")) slug = models.SlugField(max_length=30) def get_absolute_url(self): return reverse('users:detail', args=[self.slug]) def save(self, *args, **kwargs): if not self.pk: try: p = UserProfile.objects.get(user=self.user) self.pk = p.pk except UserProfile.DoesNotExist: pass self.slug = slugify(self.user.username) super(UserProfile, self).save(*args, **kwargs) class Meta: default_permissions = ('change',) verbose_name = _('user profile') verbose_name_plural = _('user profile') def __unicode__(self): return "%s's profile" % self.user def save_slug(sender, instance=None, **kwargs): if instance is not None and not kwargs.get('raw', False): userprofile, created = UserProfile.objects.get_or_create(user=instance) userprofile.save() # Signal while saving user post_save.connect(save_slug, sender=User)
gpl-3.0
rosarior/mayan
apps/tags/links.py
2
2178
from __future__ import absolute_import from django.utils.translation import ugettext_lazy as _ from acls.permissions import ACLS_VIEW_ACL from .permissions import (PERMISSION_TAG_CREATE, PERMISSION_TAG_ATTACH, PERMISSION_TAG_REMOVE, PERMISSION_TAG_DELETE, PERMISSION_TAG_EDIT, PERMISSION_TAG_VIEW) tag_list = {'text': _(u'tag list'), 'view': 'tag_list', 'famfam': 'tag_blue'} tag_create = {'text': _(u'create new tag'), 'view': 'tag_create', 'famfam': 'tag_blue_add', 'permissions': [PERMISSION_TAG_CREATE]} tag_attach = {'text': _(u'attach tag'), 'view': 'tag_attach', 'args': 'object.pk', 'famfam': 'tag_blue_add', 'permissions': [PERMISSION_TAG_ATTACH]} tag_multiple_attach = {'text': _(u'attach tag'), 'view': 'tag_multiple_attach', 'famfam': 'tag_blue_add'} #tag_remove = {'text': _(u'remove tag'), 'view': 'tag_remove', 'args': 'object.pk', 'famfam': 'tag_blue_delete', 'permissions': [PERMISSION_TAG_REMOVE]} multiple_documents_selection_tag_remove = {'text': _(u'remove tag'), 'view': 'multiple_documents_selection_tag_remove', 'famfam': 'tag_blue_delete'} single_document_multiple_tag_remove = {'text': _(u'remove tags'), 'view': 'single_document_multiple_tag_remove', 'args': 'document.id', 'famfam': 'tag_blue_delete', 'permissions': [PERMISSION_TAG_REMOVE]} tag_document_list = {'text': _(u'tags'), 'view': 'document_tags', 'args': 'object.pk', 'famfam': 'tag_blue', 'permissions': [PERMISSION_TAG_REMOVE, PERMISSION_TAG_ATTACH], 'children_view_regex': ['tag']} tag_delete = {'text': _(u'delete'), 'view': 'tag_delete', 'args': 'object.id', 'famfam': 'tag_blue_delete', 'permissions': [PERMISSION_TAG_DELETE]} tag_edit = {'text': _(u'edit'), 'view': 'tag_edit', 'args': 'object.id', 'famfam': 'tag_blue_edit', 'permissions': [PERMISSION_TAG_EDIT]} tag_tagged_item_list = {'text': _(u'tagged documents'), 'view': 'tag_tagged_item_list', 'args': 'object.id', 'famfam': 'page'} tag_multiple_delete = {'text': _(u'delete'), 'view': 'tag_multiple_delete', 'famfam': 'tag_blue_delete', 'permissions': [PERMISSION_TAG_DELETE]} tag_acl_list = {'text': _(u'ACLs'), 'view': 'tag_acl_list', 'args': 'object.pk', 'famfam': 'lock', 'permissions': [ACLS_VIEW_ACL]}
gpl-3.0
jvgomez/jvgomez_page_source
pelican-plugins/liquid_tags/notebook.py
1
9750
""" Notebook Tag ------------ This is a liquid-style tag to include a static html rendering of an IPython notebook in a blog post. Syntax ------ {% notebook filename.ipynb [ cells[start:end] ]%} The file should be specified relative to the ``notebooks`` subdirectory of the content directory. Optionally, this subdirectory can be specified in the config file: NOTEBOOK_DIR = 'notebooks' The cells[start:end] statement is optional, and can be used to specify which block of cells from the notebook to include. Requirements ------------ - The plugin requires IPython version 1.0 or above. It no longer supports the standalone nbconvert package, which has been deprecated. Details ------- Because the notebook relies on some rather extensive custom CSS, the use of this plugin requires additional CSS to be inserted into the blog theme. After typing "make html" when using the notebook tag, a file called ``_nb_header.html`` will be produced in the main directory. The content of the file should be included in the header of the theme. An easy way to accomplish this is to add the following lines within the header template of the theme you use: {% if EXTRA_HEADER %} {{ EXTRA_HEADER }} {% endif %} and in your ``pelicanconf.py`` file, include the line: EXTRA_HEADER = open('_nb_header.html').read().decode('utf-8') this will insert the appropriate CSS. All efforts have been made to ensure that this CSS will not override formats within the blog theme, but there may still be some conflicts. """ import re import os from functools import partial from .mdx_liquid_tags import LiquidTags from distutils.version import LooseVersion import IPython if not LooseVersion(IPython.__version__) >= '1.0': raise ValueError("IPython version 1.0+ required for notebook tag") from IPython import nbconvert try: from IPython.nbconvert.filters.highlight import _pygments_highlight except ImportError: # IPython < 2.0 from IPython.nbconvert.filters.highlight import _pygment_highlight as _pygments_highlight from pygments.formatters import HtmlFormatter from IPython.nbconvert.exporters import HTMLExporter from IPython.config import Config from IPython.nbformat import current as nbformat try: from IPython.nbconvert.preprocessors import Preprocessor except ImportError: # IPython < 2.0 from IPython.nbconvert.transformers import Transformer as Preprocessor from IPython.utils.traitlets import Integer from copy import deepcopy from jinja2 import DictLoader #---------------------------------------------------------------------- # Some code that will be added to the header: # Some of the following javascript/css include is adapted from # IPython/nbconvert/templates/fullhtml.tpl, while some are custom tags # specifically designed to make the results look good within the # pelican-octopress theme. JS_INCLUDE = r""" <style type="text/css"> /* Overrides of notebook CSS for static HTML export */ div.entry-content { overflow: visible; padding: 8px; } .input_area { padding: 0.2em; } a.heading-anchor { white-space: normal; } .rendered_html code { font-size: .8em; } pre.ipynb { color: black; background: #f7f7f7; border: none; box-shadow: none; margin-bottom: 0; padding: 0; margin: 0px; font-size: 13px; } /* remove the prompt div from text cells */ div.text_cell .prompt { display: none; } /* remove horizontal padding from text cells, */ /* so it aligns with outer body text */ div.text_cell_render { padding: 0.5em 0em; } img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none} div.collapseheader { width=100%; background-color:#d3d3d3; padding: 2px; cursor: pointer; font-family:"Helvetica Neue",Helvetica,Arial,sans-serif; } </style> <script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script> <script type="text/javascript"> init_mathjax = function() { if (window.MathJax) { // MathJax loaded MathJax.Hub.Config({ tex2jax: { inlineMath: [ ['$','$'], ["\\(","\\)"] ], displayMath: [ ['$$','$$'], ["\\[","\\]"] ] }, displayAlign: 'left', // Change this to 'center' to center equations. "HTML-CSS": { styles: {'.MathJax_Display': {"margin": 0}} } }); MathJax.Hub.Queue(["Typeset",MathJax.Hub]); } } init_mathjax(); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function($) { $("div.collapseheader").click(function () { $header = $(this).children("span").first(); $codearea = $(this).children(".input_area"); console.log($(this).children()); $codearea.slideToggle(500, function () { $header.text(function () { return $codearea.is(":visible") ? "Collapse Code" : "Expand Code"; }); }); }); }); </script> """ CSS_WRAPPER = """ <style type="text/css"> {0} </style> """ #---------------------------------------------------------------------- # Create a custom preprocessor class SliceIndex(Integer): """An integer trait that accepts None""" default_value = None def validate(self, obj, value): if value is None: return value else: return super(SliceIndex, self).validate(obj, value) class SubCell(Preprocessor): """A transformer to select a slice of the cells of a notebook""" start = SliceIndex(0, config=True, help="first cell of notebook to be converted") end = SliceIndex(None, config=True, help="last cell of notebook to be converted") def preprocess(self, nb, resources): nbc = deepcopy(nb) for worksheet in nbc.worksheets: cells = worksheet.cells[:] worksheet.cells = cells[self.start:self.end] return nbc, resources call = preprocess # IPython < 2.0 #---------------------------------------------------------------------- # Custom highlighter: # instead of using class='highlight', use class='highlight-ipynb' def custom_highlighter(source, language='ipython', metadata=None): formatter = HtmlFormatter(cssclass='highlight-ipynb') if not language: language = 'ipython' output = _pygments_highlight(source, formatter, language) return output.replace('<pre>', '<pre class="ipynb">') #---------------------------------------------------------------------- # Below is the pelican plugin code. # SYNTAX = "{% notebook /path/to/notebook.ipynb [ cells[start:end] ] [ language[language] ] %}" FORMAT = re.compile(r"""^(\s+)?(?P<src>\S+)(\s+)?((cells\[)(?P<start>-?[0-9]*):(?P<end>-?[0-9]*)(\]))?(\s+)?((language\[)(?P<language>-?[a-z0-9\+\-]*)(\]))?(\s+)?$""") @LiquidTags.register('notebook') def notebook(preprocessor, tag, markup): match = FORMAT.search(markup) if match: argdict = match.groupdict() src = argdict['src'] start = argdict['start'] end = argdict['end'] language = argdict['language'] else: raise ValueError("Error processing input, " "expected syntax: {0}".format(SYNTAX)) if start: start = int(start) else: start = 0 if end: end = int(end) else: end = None language_applied_highlighter = partial(custom_highlighter, language=language) nb_dir = preprocessor.configs.getConfig('NOTEBOOK_DIR') nb_path = os.path.join('content', nb_dir, src) if not os.path.exists(nb_path): raise ValueError("File {0} could not be found".format(nb_path)) # Create the custom notebook converter c = Config({'CSSHTMLHeaderTransformer': {'enabled':True, 'highlight_class':'.highlight-ipynb'}, 'SubCell': {'enabled':True, 'start':start, 'end':end}}) template_file = 'basic' if LooseVersion(IPython.__version__) >= '2.0': if os.path.exists('pelicanhtml_2.tpl'): template_file = 'pelicanhtml_2' else: if os.path.exists('pelicanhtml_1.tpl'): template_file = 'pelicanhtml_1' if LooseVersion(IPython.__version__) >= '2.0': subcell_kwarg = dict(preprocessors=[SubCell]) else: subcell_kwarg = dict(transformers=[SubCell]) exporter = HTMLExporter(config=c, template_file=template_file, filters={'highlight2html': language_applied_highlighter}, **subcell_kwarg) # read and parse the notebook with open(nb_path) as f: nb_text = f.read() nb_json = nbformat.reads_json(nb_text) (body, resources) = exporter.from_notebook_node(nb_json) # if we haven't already saved the header, save it here. if not notebook.header_saved: print ("\n ** Writing styles to _nb_header.html: " "this should be included in the theme. **\n") header = '\n'.join(CSS_WRAPPER.format(css_line) for css_line in resources['inlining']['css']) header += JS_INCLUDE with open('_nb_header.html', 'w') as f: f.write(header) notebook.header_saved = True # this will stash special characters so that they won't be transformed # by subsequent processes. body = preprocessor.configs.htmlStash.store(body, safe=True) return body notebook.header_saved = False #---------------------------------------------------------------------- # This import allows notebook to be a Pelican plugin from liquid_tags import register
gpl-2.0
talhasch/pyhttps
pyhttps.py
1
2306
import argparse import atexit import logging import os import sys import tempfile from subprocess import call from version import version logging.basicConfig(level=logging.INFO) PY3 = sys.version_info[0] == 3 parser = argparse.ArgumentParser(description='') parser.add_argument('--host', dest='host', default='localhost') parser.add_argument('--port', dest='port', type=int, default=4443) args = parser.parse_args() server_host = args.host server_port = args.port ssl_cert_path = '{}/server.pem'.format(tempfile.gettempdir()) if PY3: OpenSslExecutableNotFoundError = FileNotFoundError else: OpenSslExecutableNotFoundError = OSError def create_ssl_cert(): if PY3: from subprocess import DEVNULL else: DEVNULL = open(os.devnull, 'wb') try: ssl_exec_list = ['openssl', 'req', '-new', '-x509', '-keyout', ssl_cert_path, '-out', ssl_cert_path, '-days', '365', '-nodes', '-subj', '/CN=www.talhasch.com/O=Talhasch Inc./C=TR'] call(ssl_exec_list, stdout=DEVNULL, stderr=DEVNULL) except OpenSslExecutableNotFoundError: logging.error('openssl executable not found!') exit(1) logging.info('Self signed ssl certificate created at {}'.format(ssl_cert_path)) def exit_handler(): # remove certificate file at exit os.remove(ssl_cert_path) logging.info('Bye!') def main(): logging.info('pyhttps {}'.format(version)) create_ssl_cert() atexit.register(exit_handler) if PY3: import http.server import socketserver import ssl logging.info('Server running... https://{}:{}'.format(server_host, server_port)) httpd = socketserver.TCPServer((server_host, server_port), http.server.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile=ssl_cert_path, server_side=True) else: import BaseHTTPServer import SimpleHTTPServer import ssl logging.info('Server running... https://{}:{}'.format(server_host, server_port)) httpd = BaseHTTPServer.HTTPServer((server_host, server_port), SimpleHTTPServer.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile=ssl_cert_path, server_side=True) httpd.serve_forever()
mit
alkaitz/starloot
src/gameengine/webSocketServer/lib/tornado-3.0.1/build/lib/tornado/testing.py
4
20477
#!/usr/bin/env python """Support classes for automated testing. * `AsyncTestCase` and `AsyncHTTPTestCase`: Subclasses of unittest.TestCase with additional support for testing asynchronous (`.IOLoop` based) code. * `ExpectLog` and `LogTrapTestCase`: Make test logs less spammy. * `main()`: A simple test runner (wrapper around unittest.main()) with support for the tornado.autoreload module to rerun the tests when code changes. """ from __future__ import absolute_import, division, print_function, with_statement try: from tornado import gen from tornado.httpclient import AsyncHTTPClient from tornado.httpserver import HTTPServer from tornado.simple_httpclient import SimpleAsyncHTTPClient from tornado.ioloop import IOLoop from tornado import netutil except ImportError: # These modules are not importable on app engine. Parts of this module # won't work, but e.g. LogTrapTestCase and main() will. AsyncHTTPClient = None gen = None HTTPServer = None IOLoop = None netutil = None SimpleAsyncHTTPClient = None from tornado.log import gen_log from tornado.stack_context import ExceptionStackContext from tornado.util import raise_exc_info, basestring_type import functools import logging import os import re import signal import socket import sys try: from cStringIO import StringIO # py2 except ImportError: from io import StringIO # py3 # Tornado's own test suite requires the updated unittest module # (either py27+ or unittest2) so tornado.test.util enforces # this requirement, but for other users of tornado.testing we want # to allow the older version if unitest2 is not available. try: import unittest2 as unittest except ImportError: import unittest _next_port = 10000 def get_unused_port(): """Returns a (hopefully) unused port number. This function does not guarantee that the port it returns is available, only that a series of get_unused_port calls in a single process return distinct ports. **Deprecated**. Use bind_unused_port instead, which is guaranteed to find an unused port. """ global _next_port port = _next_port _next_port = _next_port + 1 return port def bind_unused_port(): """Binds a server socket to an available port on localhost. Returns a tuple (socket, port). """ [sock] = netutil.bind_sockets(0, 'localhost', family=socket.AF_INET) port = sock.getsockname()[1] return sock, port class AsyncTestCase(unittest.TestCase): """`~unittest.TestCase` subclass for testing `.IOLoop`-based asynchronous code. The unittest framework is synchronous, so the test must be complete by the time the test method returns. This class provides the `stop()` and `wait()` methods for this purpose. The test method itself must call ``self.wait()``, and asynchronous callbacks should call ``self.stop()`` to signal completion. Alternately, the `gen_test` decorator can be used to use yield points from the `tornado.gen` module. By default, a new `.IOLoop` is constructed for each test and is available as ``self.io_loop``. This `.IOLoop` should be used in the construction of HTTP clients/servers, etc. If the code being tested requires a global `.IOLoop`, subclasses should override `get_new_ioloop` to return it. The `.IOLoop`'s ``start`` and ``stop`` methods should not be called directly. Instead, use `self.stop <stop>` and `self.wait <wait>`. Arguments passed to ``self.stop`` are returned from ``self.wait``. It is possible to have multiple ``wait``/``stop`` cycles in the same test. Example:: # This test uses argument passing between self.stop and self.wait. class MyTestCase(AsyncTestCase): def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.tornadoweb.org/", self.stop) response = self.wait() # Test contents of response self.assertIn("FriendFeed", response.body) # This test uses an explicit callback-based style. class MyTestCase2(AsyncTestCase): def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.tornadoweb.org/", self.handle_fetch) self.wait() def handle_fetch(self, response): # Test contents of response (failures and exceptions here # will cause self.wait() to throw an exception and end the # test). # Exceptions thrown here are magically propagated to # self.wait() in test_http_fetch() via stack_context. self.assertIn("FriendFeed", response.body) self.stop() """ def __init__(self, *args, **kwargs): super(AsyncTestCase, self).__init__(*args, **kwargs) self.__stopped = False self.__running = False self.__failure = None self.__stop_args = None self.__timeout = None def setUp(self): super(AsyncTestCase, self).setUp() self.io_loop = self.get_new_ioloop() self.io_loop.make_current() def tearDown(self): self.io_loop.clear_current() if (not IOLoop.initialized() or self.io_loop is not IOLoop.instance()): # Try to clean up any file descriptors left open in the ioloop. # This avoids leaks, especially when tests are run repeatedly # in the same process with autoreload (because curl does not # set FD_CLOEXEC on its file descriptors) self.io_loop.close(all_fds=True) super(AsyncTestCase, self).tearDown() # In case an exception escaped or the StackContext caught an exception # when there wasn't a wait() to re-raise it, do so here. # This is our last chance to raise an exception in a way that the # unittest machinery understands. self.__rethrow() def get_new_ioloop(self): """Creates a new `.IOLoop` for this test. May be overridden in subclasses for tests that require a specific `.IOLoop` (usually the singleton `.IOLoop.instance()`). """ return IOLoop() def _handle_exception(self, typ, value, tb): self.__failure = sys.exc_info() self.stop() return True def __rethrow(self): if self.__failure is not None: failure = self.__failure self.__failure = None raise_exc_info(failure) def run(self, result=None): with ExceptionStackContext(self._handle_exception): super(AsyncTestCase, self).run(result) # As a last resort, if an exception escaped super.run() and wasn't # re-raised in tearDown, raise it here. This will cause the # unittest run to fail messily, but that's better than silently # ignoring an error. self.__rethrow() def stop(self, _arg=None, **kwargs): """Stops the `.IOLoop`, causing one pending (or future) call to `wait()` to return. Keyword arguments or a single positional argument passed to `stop()` are saved and will be returned by `wait()`. """ assert _arg is None or not kwargs self.__stop_args = kwargs or _arg if self.__running: self.io_loop.stop() self.__running = False self.__stopped = True def wait(self, condition=None, timeout=5): """Runs the `.IOLoop` until stop is called or timeout has passed. In the event of a timeout, an exception will be thrown. If ``condition`` is not None, the `.IOLoop` will be restarted after `stop()` until ``condition()`` returns true. """ if not self.__stopped: if timeout: def timeout_func(): try: raise self.failureException( 'Async operation timed out after %s seconds' % timeout) except Exception: self.__failure = sys.exc_info() self.stop() self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout, timeout_func) while True: self.__running = True self.io_loop.start() if (self.__failure is not None or condition is None or condition()): break if self.__timeout is not None: self.io_loop.remove_timeout(self.__timeout) self.__timeout = None assert self.__stopped self.__stopped = False self.__rethrow() result = self.__stop_args self.__stop_args = None return result class AsyncHTTPTestCase(AsyncTestCase): """A test case that starts up an HTTP server. Subclasses must override `get_app()`, which returns the `tornado.web.Application` (or other `.HTTPServer` callback) to be tested. Tests will typically use the provided ``self.http_client`` to fetch URLs from this server. Example:: class MyHTTPTest(AsyncHTTPTestCase): def get_app(self): return Application([('/', MyHandler)...]) def test_homepage(self): # The following two lines are equivalent to # response = self.fetch('/') # but are shown in full here to demonstrate explicit use # of self.stop and self.wait. self.http_client.fetch(self.get_url('/'), self.stop) response = self.wait() # test contents of response """ def setUp(self): super(AsyncHTTPTestCase, self).setUp() sock, port = bind_unused_port() self.__port = port self.http_client = self.get_http_client() self._app = self.get_app() self.http_server = self.get_http_server() self.http_server.add_sockets([sock]) def get_http_client(self): return AsyncHTTPClient(io_loop=self.io_loop) def get_http_server(self): return HTTPServer(self._app, io_loop=self.io_loop, **self.get_httpserver_options()) def get_app(self): """Should be overridden by subclasses to return a `tornado.web.Application` or other `.HTTPServer` callback. """ raise NotImplementedError() def fetch(self, path, **kwargs): """Convenience method to synchronously fetch a url. The given path will be appended to the local server's host and port. Any additional kwargs will be passed directly to `.AsyncHTTPClient.fetch` (and so could be used to pass ``method="POST"``, ``body="..."``, etc). """ self.http_client.fetch(self.get_url(path), self.stop, **kwargs) return self.wait() def get_httpserver_options(self): """May be overridden by subclasses to return additional keyword arguments for the server. """ return {} def get_http_port(self): """Returns the port used by the server. A new port is chosen for each test. """ return self.__port def get_protocol(self): return 'http' def get_url(self, path): """Returns an absolute url for the given path on the test server.""" return '%s://localhost:%s%s' % (self.get_protocol(), self.get_http_port(), path) def tearDown(self): self.http_server.stop() if (not IOLoop.initialized() or self.http_client.io_loop is not IOLoop.instance()): self.http_client.close() super(AsyncHTTPTestCase, self).tearDown() class AsyncHTTPSTestCase(AsyncHTTPTestCase): """A test case that starts an HTTPS server. Interface is generally the same as `AsyncHTTPTestCase`. """ def get_http_client(self): # Some versions of libcurl have deadlock bugs with ssl, # so always run these tests with SimpleAsyncHTTPClient. return SimpleAsyncHTTPClient(io_loop=self.io_loop, force_instance=True, defaults=dict(validate_cert=False)) def get_httpserver_options(self): return dict(ssl_options=self.get_ssl_options()) def get_ssl_options(self): """May be overridden by subclasses to select SSL options. By default includes a self-signed testing certificate. """ # Testing keys were generated with: # openssl req -new -keyout tornado/test/test.key -out tornado/test/test.crt -nodes -days 3650 -x509 module_dir = os.path.dirname(__file__) return dict( certfile=os.path.join(module_dir, 'test', 'test.crt'), keyfile=os.path.join(module_dir, 'test', 'test.key')) def get_protocol(self): return 'https' def gen_test(f): """Testing equivalent of ``@gen.coroutine``, to be applied to test methods. ``@gen.coroutine`` cannot be used on tests because the `.IOLoop` is not already running. ``@gen_test`` should be applied to test methods on subclasses of `AsyncTestCase`. Example:: class MyTest(AsyncHTTPTestCase): @gen_test def test_something(self): response = yield gen.Task(self.fetch('/')) """ f = gen.coroutine(f) @functools.wraps(f) def wrapper(self): return self.io_loop.run_sync(functools.partial(f, self), timeout=5) return wrapper # Without this attribute, nosetests will try to run gen_test as a test # anywhere it is imported. gen_test.__test__ = False class LogTrapTestCase(unittest.TestCase): """A test case that captures and discards all logging output if the test passes. Some libraries can produce a lot of logging output even when the test succeeds, so this class can be useful to minimize the noise. Simply use it as a base class for your test case. It is safe to combine with AsyncTestCase via multiple inheritance (``class MyTestCase(AsyncHTTPTestCase, LogTrapTestCase):``) This class assumes that only one log handler is configured and that it is a `~logging.StreamHandler`. This is true for both `logging.basicConfig` and the "pretty logging" configured by `tornado.options`. It is not compatible with other log buffering mechanisms, such as those provided by some test runners. """ def run(self, result=None): logger = logging.getLogger() if not logger.handlers: logging.basicConfig() handler = logger.handlers[0] if (len(logger.handlers) > 1 or not isinstance(handler, logging.StreamHandler)): # Logging has been configured in a way we don't recognize, # so just leave it alone. super(LogTrapTestCase, self).run(result) return old_stream = handler.stream try: handler.stream = StringIO() gen_log.info("RUNNING TEST: " + str(self)) old_error_count = len(result.failures) + len(result.errors) super(LogTrapTestCase, self).run(result) new_error_count = len(result.failures) + len(result.errors) if new_error_count != old_error_count: old_stream.write(handler.stream.getvalue()) finally: handler.stream = old_stream class ExpectLog(logging.Filter): """Context manager to capture and suppress expected log output. Useful to make tests of error conditions less noisy, while still leaving unexpected log entries visible. *Not thread safe.* Usage:: with ExpectLog('tornado.application', "Uncaught exception"): error_response = self.fetch("/some_page") """ def __init__(self, logger, regex, required=True): """Constructs an ExpectLog context manager. :param logger: Logger object (or name of logger) to watch. Pass an empty string to watch the root logger. :param regex: Regular expression to match. Any log entries on the specified logger that match this regex will be suppressed. :param required: If true, an exeption will be raised if the end of the ``with`` statement is reached without matching any log entries. """ if isinstance(logger, basestring_type): logger = logging.getLogger(logger) self.logger = logger self.regex = re.compile(regex) self.required = required self.matched = False def filter(self, record): message = record.getMessage() if self.regex.match(message): self.matched = True return False return True def __enter__(self): self.logger.addFilter(self) def __exit__(self, typ, value, tb): self.logger.removeFilter(self) if not typ and self.required and not self.matched: raise Exception("did not get expected log message") def main(**kwargs): """A simple test runner. This test runner is essentially equivalent to `unittest.main` from the standard library, but adds support for tornado-style option parsing and log formatting. The easiest way to run a test is via the command line:: python -m tornado.testing tornado.test.stack_context_test See the standard library unittest module for ways in which tests can be specified. Projects with many tests may wish to define a test script like ``tornado/test/runtests.py``. This script should define a method ``all()`` which returns a test suite and then call `tornado.testing.main()`. Note that even when a test script is used, the ``all()`` test suite may be overridden by naming a single test on the command line:: # Runs all tests python -m tornado.test.runtests # Runs one test python -m tornado.test.runtests tornado.test.stack_context_test Additional keyword arguments passed through to ``unittest.main()``. For example, use ``tornado.testing.main(verbosity=2)`` to show many test details as they are run. See http://docs.python.org/library/unittest.html#unittest.main for full argument list. """ from tornado.options import define, options, parse_command_line define('exception_on_interrupt', type=bool, default=True, help=("If true (default), ctrl-c raises a KeyboardInterrupt " "exception. This prints a stack trace but cannot interrupt " "certain operations. If false, the process is more reliably " "killed, but does not print a stack trace.")) # support the same options as unittest's command-line interface define('verbose', type=bool) define('quiet', type=bool) define('failfast', type=bool) define('catch', type=bool) define('buffer', type=bool) argv = [sys.argv[0]] + parse_command_line(sys.argv) if not options.exception_on_interrupt: signal.signal(signal.SIGINT, signal.SIG_DFL) if options.verbose is not None: kwargs['verbosity'] = 2 if options.quiet is not None: kwargs['verbosity'] = 0 if options.failfast is not None: kwargs['failfast'] = True if options.catch is not None: kwargs['catchbreak'] = True if options.buffer is not None: kwargs['buffer'] = True if __name__ == '__main__' and len(argv) == 1: print("No tests specified", file=sys.stderr) sys.exit(1) try: # In order to be able to run tests by their fully-qualified name # on the command line without importing all tests here, # module must be set to None. Python 3.2's unittest.main ignores # defaultTest if no module is given (it tries to do its own # test discovery, which is incompatible with auto2to3), so don't # set module if we're not asking for a specific test. if len(argv) > 1: unittest.main(module=None, argv=argv, **kwargs) else: unittest.main(defaultTest="all", argv=argv, **kwargs) except SystemExit as e: if e.code == 0: gen_log.info('PASS') else: gen_log.error('FAIL') raise if __name__ == '__main__': main()
apache-2.0
dreamsxin/kbengine
kbe/res/scripts/common/Lib/test/test_hashlib.py
72
22074
# Test hashlib module # # $Id$ # # Copyright (C) 2005-2010 Gregory P. Smith ([email protected]) # Licensed to PSF under a Contributor Agreement. # import array import hashlib import itertools import os import sys try: import threading except ImportError: threading = None import unittest import warnings from test import support from test.support import _4G, bigmemtest, import_fresh_module # Were we compiled --with-pydebug or with #define Py_DEBUG? COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount') c_hashlib = import_fresh_module('hashlib', fresh=['_hashlib']) py_hashlib = import_fresh_module('hashlib', blocked=['_hashlib']) def hexstr(s): assert isinstance(s, bytes), repr(s) h = "0123456789abcdef" r = '' for i in s: r += h[(i >> 4) & 0xF] + h[i & 0xF] return r class HashLibTestCase(unittest.TestCase): supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1', 'sha224', 'SHA224', 'sha256', 'SHA256', 'sha384', 'SHA384', 'sha512', 'SHA512') # Issue #14693: fallback modules are always compiled under POSIX _warn_on_extension_import = os.name == 'posix' or COMPILED_WITH_PYDEBUG def _conditional_import_module(self, module_name): """Import a module and return a reference to it or None on failure.""" try: exec('import '+module_name) except ImportError as error: if self._warn_on_extension_import: warnings.warn('Did a C extension fail to compile? %s' % error) return locals().get(module_name) def __init__(self, *args, **kwargs): algorithms = set() for algorithm in self.supported_hash_names: algorithms.add(algorithm.lower()) self.constructors_to_test = {} for algorithm in algorithms: self.constructors_to_test[algorithm] = set() # For each algorithm, test the direct constructor and the use # of hashlib.new given the algorithm name. for algorithm, constructors in self.constructors_to_test.items(): constructors.add(getattr(hashlib, algorithm)) def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm): if data is None: return hashlib.new(_alg) return hashlib.new(_alg, data) constructors.add(_test_algorithm_via_hashlib_new) _hashlib = self._conditional_import_module('_hashlib') if _hashlib: # These two algorithms should always be present when this module # is compiled. If not, something was compiled wrong. self.assertTrue(hasattr(_hashlib, 'openssl_md5')) self.assertTrue(hasattr(_hashlib, 'openssl_sha1')) for algorithm, constructors in self.constructors_to_test.items(): constructor = getattr(_hashlib, 'openssl_'+algorithm, None) if constructor: constructors.add(constructor) def add_builtin_constructor(name): constructor = getattr(hashlib, "__get_builtin_constructor")(name) self.constructors_to_test[name].add(constructor) _md5 = self._conditional_import_module('_md5') if _md5: add_builtin_constructor('md5') _sha1 = self._conditional_import_module('_sha1') if _sha1: add_builtin_constructor('sha1') _sha256 = self._conditional_import_module('_sha256') if _sha256: add_builtin_constructor('sha224') add_builtin_constructor('sha256') _sha512 = self._conditional_import_module('_sha512') if _sha512: add_builtin_constructor('sha384') add_builtin_constructor('sha512') super(HashLibTestCase, self).__init__(*args, **kwargs) @property def hash_constructors(self): constructors = self.constructors_to_test.values() return itertools.chain.from_iterable(constructors) def test_hash_array(self): a = array.array("b", range(10)) for cons in self.hash_constructors: c = cons(a) c.hexdigest() def test_algorithms_guaranteed(self): self.assertEqual(hashlib.algorithms_guaranteed, set(_algo for _algo in self.supported_hash_names if _algo.islower())) def test_algorithms_available(self): self.assertTrue(set(hashlib.algorithms_guaranteed). issubset(hashlib.algorithms_available)) def test_unknown_hash(self): self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam') self.assertRaises(TypeError, hashlib.new, 1) def test_get_builtin_constructor(self): get_builtin_constructor = getattr(hashlib, '__get_builtin_constructor') builtin_constructor_cache = getattr(hashlib, '__builtin_constructor_cache') self.assertRaises(ValueError, get_builtin_constructor, 'test') try: import _md5 except ImportError: pass # This forces an ImportError for "import _md5" statements sys.modules['_md5'] = None # clear the cache builtin_constructor_cache.clear() try: self.assertRaises(ValueError, get_builtin_constructor, 'md5') finally: if '_md5' in locals(): sys.modules['_md5'] = _md5 else: del sys.modules['_md5'] self.assertRaises(TypeError, get_builtin_constructor, 3) constructor = get_builtin_constructor('md5') self.assertIs(constructor, _md5.md5) self.assertEqual(sorted(builtin_constructor_cache), ['MD5', 'md5']) def test_hexdigest(self): for cons in self.hash_constructors: h = cons() self.assertIsInstance(h.digest(), bytes) self.assertEqual(hexstr(h.digest()), h.hexdigest()) def test_name_attribute(self): for cons in self.hash_constructors: h = cons() self.assertIsInstance(h.name, str) self.assertIn(h.name, self.supported_hash_names) self.assertEqual(h.name, hashlib.new(h.name).name) def test_large_update(self): aas = b'a' * 128 bees = b'b' * 127 cees = b'c' * 126 dees = b'd' * 2048 # HASHLIB_GIL_MINSIZE for cons in self.hash_constructors: m1 = cons() m1.update(aas) m1.update(bees) m1.update(cees) m1.update(dees) m2 = cons() m2.update(aas + bees + cees + dees) self.assertEqual(m1.digest(), m2.digest()) m3 = cons(aas + bees + cees + dees) self.assertEqual(m1.digest(), m3.digest()) # verify copy() doesn't touch original m4 = cons(aas + bees + cees) m4_digest = m4.digest() m4_copy = m4.copy() m4_copy.update(dees) self.assertEqual(m1.digest(), m4_copy.digest()) self.assertEqual(m4.digest(), m4_digest) def check(self, name, data, hexdigest): hexdigest = hexdigest.lower() constructors = self.constructors_to_test[name] # 2 is for hashlib.name(...) and hashlib.new(name, ...) self.assertGreaterEqual(len(constructors), 2) for hash_object_constructor in constructors: m = hash_object_constructor(data) computed = m.hexdigest() self.assertEqual( computed, hexdigest, "Hash algorithm %s constructed using %s returned hexdigest" " %r for %d byte input data that should have hashed to %r." % (name, hash_object_constructor, computed, len(data), hexdigest)) computed = m.digest() digest = bytes.fromhex(hexdigest) self.assertEqual(computed, digest) self.assertEqual(len(digest), m.digest_size) def check_no_unicode(self, algorithm_name): # Unicode objects are not allowed as input. constructors = self.constructors_to_test[algorithm_name] for hash_object_constructor in constructors: self.assertRaises(TypeError, hash_object_constructor, 'spam') def test_no_unicode(self): self.check_no_unicode('md5') self.check_no_unicode('sha1') self.check_no_unicode('sha224') self.check_no_unicode('sha256') self.check_no_unicode('sha384') self.check_no_unicode('sha512') def check_blocksize_name(self, name, block_size=0, digest_size=0): constructors = self.constructors_to_test[name] for hash_object_constructor in constructors: m = hash_object_constructor() self.assertEqual(m.block_size, block_size) self.assertEqual(m.digest_size, digest_size) self.assertEqual(len(m.digest()), digest_size) self.assertEqual(m.name, name) # split for sha3_512 / _sha3.sha3 object self.assertIn(name.split("_")[0], repr(m)) def test_blocksize_name(self): self.check_blocksize_name('md5', 64, 16) self.check_blocksize_name('sha1', 64, 20) self.check_blocksize_name('sha224', 64, 28) self.check_blocksize_name('sha256', 64, 32) self.check_blocksize_name('sha384', 128, 48) self.check_blocksize_name('sha512', 128, 64) def test_case_md5_0(self): self.check('md5', b'', 'd41d8cd98f00b204e9800998ecf8427e') def test_case_md5_1(self): self.check('md5', b'abc', '900150983cd24fb0d6963f7d28e17f72') def test_case_md5_2(self): self.check('md5', b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 'd174ab98d277d9f5a5611c2c9f419d9f') @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems') @bigmemtest(size=_4G + 5, memuse=1, dry_run=False) def test_case_md5_huge(self, size): self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d') @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems') @bigmemtest(size=_4G - 1, memuse=1, dry_run=False) def test_case_md5_uintmax(self, size): self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3') # use the three examples from Federal Information Processing Standards # Publication 180-1, Secure Hash Standard, 1995 April 17 # http://www.itl.nist.gov/div897/pubs/fip180-1.htm def test_case_sha1_0(self): self.check('sha1', b"", "da39a3ee5e6b4b0d3255bfef95601890afd80709") def test_case_sha1_1(self): self.check('sha1', b"abc", "a9993e364706816aba3e25717850c26c9cd0d89d") def test_case_sha1_2(self): self.check('sha1', b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "84983e441c3bd26ebaae4aa1f95129e5e54670f1") def test_case_sha1_3(self): self.check('sha1', b"a" * 1000000, "34aa973cd4c4daa4f61eeb2bdbad27316534016f") # use the examples from Federal Information Processing Standards # Publication 180-2, Secure Hash Standard, 2002 August 1 # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf def test_case_sha224_0(self): self.check('sha224', b"", "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f") def test_case_sha224_1(self): self.check('sha224', b"abc", "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7") def test_case_sha224_2(self): self.check('sha224', b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525") def test_case_sha224_3(self): self.check('sha224', b"a" * 1000000, "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67") def test_case_sha256_0(self): self.check('sha256', b"", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") def test_case_sha256_1(self): self.check('sha256', b"abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") def test_case_sha256_2(self): self.check('sha256', b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1") def test_case_sha256_3(self): self.check('sha256', b"a" * 1000000, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0") def test_case_sha384_0(self): self.check('sha384', b"", "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+ "274edebfe76f65fbd51ad2f14898b95b") def test_case_sha384_1(self): self.check('sha384', b"abc", "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+ "8086072ba1e7cc2358baeca134c825a7") def test_case_sha384_2(self): self.check('sha384', b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+ b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+ "fcc7c71a557e2db966c3e9fa91746039") def test_case_sha384_3(self): self.check('sha384', b"a" * 1000000, "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+ "07b8b3dc38ecc4ebae97ddd87f3d8985") def test_case_sha512_0(self): self.check('sha512', b"", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+ "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e") def test_case_sha512_1(self): self.check('sha512', b"abc", "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+ "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f") def test_case_sha512_2(self): self.check('sha512', b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+ b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+ "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909") def test_case_sha512_3(self): self.check('sha512', b"a" * 1000000, "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+ "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b") @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems') @bigmemtest(size=_4G + 5, memuse=1, dry_run=False) def test_case_sha3_224_huge(self, size): self.check('sha3_224', b'A'*size, '58ef60057c9dddb6a87477e9ace5a26f0d9db01881cf9b10a9f8c224') def test_gil(self): # Check things work fine with an input larger than the size required # for multithreaded operation (which is hardwired to 2048). gil_minsize = 2048 for cons in self.hash_constructors: m = cons() m.update(b'1') m.update(b'#' * gil_minsize) m.update(b'1') m = cons(b'x' * gil_minsize) m.update(b'1') m = hashlib.md5() m.update(b'1') m.update(b'#' * gil_minsize) m.update(b'1') self.assertEqual(m.hexdigest(), 'cb1e1a2cbc80be75e19935d621fb9b21') m = hashlib.md5(b'x' * gil_minsize) self.assertEqual(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958') @unittest.skipUnless(threading, 'Threading required for this test.') @support.reap_threads def test_threaded_hashing(self): # Updating the same hash object from several threads at once # using data chunk sizes containing the same byte sequences. # # If the internal locks are working to prevent multiple # updates on the same object from running at once, the resulting # hash will be the same as doing it single threaded upfront. hasher = hashlib.sha1() num_threads = 5 smallest_data = b'swineflu' data = smallest_data*200000 expected_hash = hashlib.sha1(data*num_threads).hexdigest() def hash_in_chunks(chunk_size, event): index = 0 while index < len(data): hasher.update(data[index:index+chunk_size]) index += chunk_size event.set() events = [] for threadnum in range(num_threads): chunk_size = len(data) // (10**threadnum) self.assertGreater(chunk_size, 0) self.assertEqual(chunk_size % len(smallest_data), 0) event = threading.Event() events.append(event) threading.Thread(target=hash_in_chunks, args=(chunk_size, event)).start() for event in events: event.wait() self.assertEqual(expected_hash, hasher.hexdigest()) class KDFTests(unittest.TestCase): pbkdf2_test_vectors = [ (b'password', b'salt', 1, None), (b'password', b'salt', 2, None), (b'password', b'salt', 4096, None), # too slow, it takes over a minute on a fast CPU. #(b'password', b'salt', 16777216, None), (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, -1), (b'pass\0word', b'sa\0lt', 4096, 16), ] pbkdf2_results = { "sha1": [ # offical test vectors from RFC 6070 (bytes.fromhex('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None), (bytes.fromhex('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None), (bytes.fromhex('4b007901b765489abead49d926f721d065a429c1'), None), #(bytes.fromhex('eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), None), (bytes.fromhex('3d2eec4fe41c849b80c8d83662c0e44a8b291a964c' 'f2f07038'), 25), (bytes.fromhex('56fa6aa75548099dcc37d7f03425e0c3'), None),], "sha256": [ (bytes.fromhex('120fb6cffcf8b32c43e7225256c4f837' 'a86548c92ccc35480805987cb70be17b'), None), (bytes.fromhex('ae4d0c95af6b46d32d0adff928f06dd0' '2a303f8ef3c251dfd6e2d85a95474c43'), None), (bytes.fromhex('c5e478d59288c841aa530db6845c4c8d' '962893a001ce4e11a4963873aa98134a'), None), #(bytes.fromhex('cf81c66fe8cfc04d1f31ecb65dab4089' # 'f7f179e89b3b0bcb17ad10e3ac6eba46'), None), (bytes.fromhex('348c89dbcbd32b2f32d814b8116e84cf2b17' '347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9'), 40), (bytes.fromhex('89b69d0516f829893c696226650a8687'), None),], "sha512": [ (bytes.fromhex('867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5' 'd513554e1c8cf252c02d470a285a0501bad999bfe943c08f' '050235d7d68b1da55e63f73b60a57fce'), None), (bytes.fromhex('e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f004071' '3f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82' 'be67335c77a6068e04112754f27ccf4e'), None), (bytes.fromhex('d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f8' '7f6902e072f457b5143f30602641b3d55cd335988cb36b84' '376060ecd532e039b742a239434af2d5'), None), (bytes.fromhex('8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b8' '68c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30' '225c583a186cd82bd4daea9724a3d3b8'), 64), (bytes.fromhex('9d9e9c4cd21fe4be24d5b8244c759665'), None),], } def _test_pbkdf2_hmac(self, pbkdf2): for digest_name, results in self.pbkdf2_results.items(): for i, vector in enumerate(self.pbkdf2_test_vectors): password, salt, rounds, dklen = vector expected, overwrite_dklen = results[i] if overwrite_dklen: dklen = overwrite_dklen out = pbkdf2(digest_name, password, salt, rounds, dklen) self.assertEqual(out, expected, (digest_name, password, salt, rounds, dklen)) out = pbkdf2(digest_name, memoryview(password), memoryview(salt), rounds, dklen) out = pbkdf2(digest_name, bytearray(password), bytearray(salt), rounds, dklen) self.assertEqual(out, expected) if dklen is None: out = pbkdf2(digest_name, password, salt, rounds) self.assertEqual(out, expected, (digest_name, password, salt, rounds)) self.assertRaises(TypeError, pbkdf2, b'sha1', b'pass', b'salt', 1) self.assertRaises(TypeError, pbkdf2, 'sha1', 'pass', 'salt', 1) self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 0) self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', -1) self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, 0) self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, -1) with self.assertRaisesRegex(ValueError, 'unsupported hash type'): pbkdf2('unknown', b'pass', b'salt', 1) def test_pbkdf2_hmac_py(self): self._test_pbkdf2_hmac(py_hashlib.pbkdf2_hmac) @unittest.skipUnless(hasattr(c_hashlib, 'pbkdf2_hmac'), ' test requires OpenSSL > 1.0') def test_pbkdf2_hmac_c(self): self._test_pbkdf2_hmac(c_hashlib.pbkdf2_hmac) if __name__ == "__main__": unittest.main()
lgpl-3.0
ryfeus/lambda-packs
Tensorflow_LightGBM_Scipy_nightly/source/scipy/odr/__init__.py
19
4343
""" ================================================= Orthogonal distance regression (:mod:`scipy.odr`) ================================================= .. currentmodule:: scipy.odr Package Content =============== .. autosummary:: :toctree: generated/ Data -- The data to fit. RealData -- Data with weights as actual std. dev.s and/or covariances. Model -- Stores information about the function to be fit. ODR -- Gathers all info & manages the main fitting routine. Output -- Result from the fit. odr -- Low-level function for ODR. OdrWarning -- Warning about potential problems when running ODR OdrError -- Error exception. OdrStop -- Stop exception. odr_error -- Same as OdrError (for backwards compatibility) odr_stop -- Same as OdrStop (for backwards compatibility) Prebuilt models: .. autosummary:: :toctree: generated/ polynomial .. data:: exponential .. data:: multilinear .. data:: unilinear .. data:: quadratic .. data:: polynomial Usage information ================= Introduction ------------ Why Orthogonal Distance Regression (ODR)? Sometimes one has measurement errors in the explanatory (a.k.a., "independent") variable(s), not just the response (a.k.a., "dependent") variable(s). Ordinary Least Squares (OLS) fitting procedures treat the data for explanatory variables as fixed, i.e., not subject to error of any kind. Furthermore, OLS procedures require that the response variables be an explicit function of the explanatory variables; sometimes making the equation explicit is impractical and/or introduces errors. ODR can handle both of these cases with ease, and can even reduce to the OLS case if that is sufficient for the problem. ODRPACK is a FORTRAN-77 library for performing ODR with possibly non-linear fitting functions. It uses a modified trust-region Levenberg-Marquardt-type algorithm [1]_ to estimate the function parameters. The fitting functions are provided by Python functions operating on NumPy arrays. The required derivatives may be provided by Python functions as well, or may be estimated numerically. ODRPACK can do explicit or implicit ODR fits, or it can do OLS. Input and output variables may be multi-dimensional. Weights can be provided to account for different variances of the observations, and even covariances between dimensions of the variables. The `scipy.odr` package offers an object-oriented interface to ODRPACK, in addition to the low-level `odr` function. Additional background information about ODRPACK can be found in the `ODRPACK User's Guide <https://docs.scipy.org/doc/external/odrpack_guide.pdf>`_, reading which is recommended. Basic usage ----------- 1. Define the function you want to fit against.:: def f(B, x): '''Linear function y = m*x + b''' # B is a vector of the parameters. # x is an array of the current x values. # x is in the same format as the x passed to Data or RealData. # # Return an array in the same format as y passed to Data or RealData. return B[0]*x + B[1] 2. Create a Model.:: linear = Model(f) 3. Create a Data or RealData instance.:: mydata = Data(x, y, wd=1./power(sx,2), we=1./power(sy,2)) or, when the actual covariances are known:: mydata = RealData(x, y, sx=sx, sy=sy) 4. Instantiate ODR with your data, model and initial parameter estimate.:: myodr = ODR(mydata, linear, beta0=[1., 2.]) 5. Run the fit.:: myoutput = myodr.run() 6. Examine output.:: myoutput.pprint() References ---------- .. [1] P. T. Boggs and J. E. Rogers, "Orthogonal Distance Regression," in "Statistical analysis of measurement error models and applications: proceedings of the AMS-IMS-SIAM joint summer research conference held June 10-16, 1989," Contemporary Mathematics, vol. 112, pg. 186, 1990. """ # version: 0.7 # author: Robert Kern <[email protected]> # date: 2006-09-21 from __future__ import division, print_function, absolute_import from .odrpack import * from .models import * from . import add_newdocs __all__ = [s for s in dir() if not s.startswith('_')] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
mit
Kazade/NeHe-Website
google_appengine/lib/django_0_96/django/contrib/auth/handlers/modpython.py
33
1760
from mod_python import apache import os def authenhandler(req, **kwargs): """ Authentication handler that checks against Django's auth database. """ # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes # that so that the following import works os.environ.update(req.subprocess_env) # check for PythonOptions _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes') options = req.get_options() permission_name = options.get('DjangoPermissionName', None) staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on")) superuser_only = _str_to_bool(options.get('DjangoRequireSuperuserStatus', "off")) settings_module = options.get('DJANGO_SETTINGS_MODULE', None) if settings_module: os.environ['DJANGO_SETTINGS_MODULE'] = settings_module from django.contrib.auth.models import User from django import db db.reset_queries() # check that the username is valid kwargs = {'username': req.user, 'is_active': True} if staff_only: kwargs['is_staff'] = True if superuser_only: kwargs['is_superuser'] = True try: try: user = User.objects.get(**kwargs) except User.DoesNotExist: return apache.HTTP_UNAUTHORIZED # check the password and any permission given if user.check_password(req.get_basic_auth_pw()): if permission_name: if user.has_perm(permission_name): return apache.OK else: return apache.HTTP_UNAUTHORIZED else: return apache.OK else: return apache.HTTP_UNAUTHORIZED finally: db.connection.close()
bsd-3-clause
aprefontaine/TMScheduler
django/test/simple.py
17
12744
import sys import signal import unittest from django.conf import settings from django.db.models import get_app, get_apps from django.test import _doctest as doctest from django.test.utils import setup_test_environment, teardown_test_environment from django.test.testcases import OutputChecker, DocTestRunner, TestCase # The module name for tests outside models.py TEST_MODULE = 'tests' doctestOutputChecker = OutputChecker() class DjangoTestRunner(unittest.TextTestRunner): def __init__(self, verbosity=0, failfast=False, **kwargs): super(DjangoTestRunner, self).__init__(verbosity=verbosity, **kwargs) self.failfast = failfast self._keyboard_interrupt_intercepted = False def run(self, *args, **kwargs): """ Runs the test suite after registering a custom signal handler that triggers a graceful exit when Ctrl-C is pressed. """ self._default_keyboard_interrupt_handler = signal.signal(signal.SIGINT, self._keyboard_interrupt_handler) try: result = super(DjangoTestRunner, self).run(*args, **kwargs) finally: signal.signal(signal.SIGINT, self._default_keyboard_interrupt_handler) return result def _keyboard_interrupt_handler(self, signal_number, stack_frame): """ Handles Ctrl-C by setting a flag that will stop the test run when the currently running test completes. """ self._keyboard_interrupt_intercepted = True sys.stderr.write(" <Test run halted by Ctrl-C> ") # Set the interrupt handler back to the default handler, so that # another Ctrl-C press will trigger immediate exit. signal.signal(signal.SIGINT, self._default_keyboard_interrupt_handler) def _makeResult(self): result = super(DjangoTestRunner, self)._makeResult() failfast = self.failfast def stoptest_override(func): def stoptest(test): # If we were set to failfast and the unit test failed, # or if the user has typed Ctrl-C, report and quit if (failfast and not result.wasSuccessful()) or \ self._keyboard_interrupt_intercepted: result.stop() func(test) return stoptest setattr(result, 'stopTest', stoptest_override(result.stopTest)) return result def get_tests(app_module): try: app_path = app_module.__name__.split('.')[:-1] test_module = __import__('.'.join(app_path + [TEST_MODULE]), {}, {}, TEST_MODULE) except ImportError, e: # Couldn't import tests.py. Was it due to a missing file, or # due to an import error in a tests.py that actually exists? import os.path from imp import find_module try: mod = find_module(TEST_MODULE, [os.path.dirname(app_module.__file__)]) except ImportError: # 'tests' module doesn't exist. Move on. test_module = None else: # The module exists, so there must be an import error in the # test module itself. We don't need the module; so if the # module was a single file module (i.e., tests.py), close the file # handle returned by find_module. Otherwise, the test module # is a directory, and there is nothing to close. if mod[0]: mod[0].close() raise return test_module def build_suite(app_module): "Create a complete Django test suite for the provided application module" suite = unittest.TestSuite() # Load unit and doctests in the models.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if hasattr(app_module, 'suite'): suite.addTest(app_module.suite()) else: suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(app_module)) try: suite.addTest(doctest.DocTestSuite(app_module, checker=doctestOutputChecker, runner=DocTestRunner)) except ValueError: # No doc tests in models.py pass # Check to see if a separate 'tests' module exists parallel to the # models module test_module = get_tests(app_module) if test_module: # Load unit and doctests in the tests.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if hasattr(test_module, 'suite'): suite.addTest(test_module.suite()) else: suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module)) try: suite.addTest(doctest.DocTestSuite(test_module, checker=doctestOutputChecker, runner=DocTestRunner)) except ValueError: # No doc tests in tests.py pass return suite def build_test(label): """Construct a test case with the specified label. Label should be of the form model.TestClass or model.TestClass.test_method. Returns an instantiated test or test suite corresponding to the label provided. """ parts = label.split('.') if len(parts) < 2 or len(parts) > 3: raise ValueError("Test label '%s' should be of the form app.TestCase or app.TestCase.test_method" % label) # # First, look for TestCase instances with a name that matches # app_module = get_app(parts[0]) test_module = get_tests(app_module) TestClass = getattr(app_module, parts[1], None) # Couldn't find the test class in models.py; look in tests.py if TestClass is None: if test_module: TestClass = getattr(test_module, parts[1], None) try: if issubclass(TestClass, unittest.TestCase): if len(parts) == 2: # label is app.TestClass try: return unittest.TestLoader().loadTestsFromTestCase(TestClass) except TypeError: raise ValueError("Test label '%s' does not refer to a test class" % label) else: # label is app.TestClass.test_method return TestClass(parts[2]) except TypeError: # TestClass isn't a TestClass - it must be a method or normal class pass # # If there isn't a TestCase, look for a doctest that matches # tests = [] for module in app_module, test_module: try: doctests = doctest.DocTestSuite(module, checker=doctestOutputChecker, runner=DocTestRunner) # Now iterate over the suite, looking for doctests whose name # matches the pattern that was given for test in doctests: if test._dt_test.name in ( '%s.%s' % (module.__name__, '.'.join(parts[1:])), '%s.__test__.%s' % (module.__name__, '.'.join(parts[1:]))): tests.append(test) except ValueError: # No doctests found. pass # If no tests were found, then we were given a bad test label. if not tests: raise ValueError("Test label '%s' does not refer to a test" % label) # Construct a suite out of the tests that matched. return unittest.TestSuite(tests) def partition_suite(suite, classes, bins): """ Partitions a test suite by test type. classes is a sequence of types bins is a sequence of TestSuites, one more than classes Tests of type classes[i] are added to bins[i], tests with no match found in classes are place in bins[-1] """ for test in suite: if isinstance(test, unittest.TestSuite): partition_suite(test, classes, bins) else: for i in range(len(classes)): if isinstance(test, classes[i]): bins[i].addTest(test) break else: bins[-1].addTest(test) def reorder_suite(suite, classes): """ Reorders a test suite by test type. classes is a sequence of types All tests of type clases[0] are placed first, then tests of type classes[1], etc. Tests with no match in classes are placed last. """ class_count = len(classes) bins = [unittest.TestSuite() for i in range(class_count+1)] partition_suite(suite, classes, bins) for i in range(class_count): bins[0].addTests(bins[i+1]) return bins[0] class DjangoTestSuiteRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def setup_test_environment(self, **kwargs): setup_test_environment() settings.DEBUG = False def build_suite(self, test_labels, extra_tests=None, **kwargs): suite = unittest.TestSuite() if test_labels: for label in test_labels: if '.' in label: suite.addTest(build_test(label)) else: app = get_app(label) suite.addTest(build_suite(app)) else: for app in get_apps(): suite.addTest(build_suite(app)) if extra_tests: for test in extra_tests: suite.addTest(test) return reorder_suite(suite, (TestCase,)) def setup_databases(self, **kwargs): from django.db import connections old_names = [] mirrors = [] for alias in connections: connection = connections[alias] # If the database is a test mirror, redirect it's connection # instead of creating a test database. if connection.settings_dict['TEST_MIRROR']: mirrors.append((alias, connection)) mirror_alias = connection.settings_dict['TEST_MIRROR'] connections._connections[alias] = connections[mirror_alias] else: old_names.append((connection, connection.settings_dict['NAME'])) connection.creation.create_test_db(self.verbosity, autoclobber=not self.interactive) return old_names, mirrors def run_suite(self, suite, **kwargs): return DjangoTestRunner(verbosity=self.verbosity, failfast=self.failfast).run(suite) def teardown_databases(self, old_config, **kwargs): from django.db import connections old_names, mirrors = old_config # Point all the mirrors back to the originals for alias, connection in mirrors: connections._connections[alias] = connection # Destroy all the non-mirror databases for connection, old_name in old_names: connection.creation.destroy_test_db(old_name, self.verbosity) def teardown_test_environment(self, **kwargs): teardown_test_environment() def suite_result(self, suite, result, **kwargs): return len(result.failures) + len(result.errors) def run_tests(self, test_labels, extra_tests=None, **kwargs): """ Run the unit tests for all the test labels in the provided list. Labels must be of the form: - app.TestClass.test_method Run a single specific test method - app.TestClass Run all the test methods in a given class - app Search for doctests and unittests in the named application. When looking for tests, the test runner will look in the models and tests modules for the application. A list of 'extra' tests may also be provided; these tests will be added to the test suite. Returns the number of tests that failed. """ self.setup_test_environment() suite = self.build_suite(test_labels, extra_tests) old_config = self.setup_databases() result = self.run_suite(suite) self.teardown_databases(old_config) self.teardown_test_environment() return self.suite_result(suite, result) def run_tests(test_labels, verbosity=1, interactive=True, failfast=False, extra_tests=None): import warnings warnings.warn( 'The run_tests() test runner has been deprecated in favor of DjangoTestSuiteRunner.', PendingDeprecationWarning ) test_runner = DjangoTestSuiteRunner(verbosity=verbosity, interactive=interactive, failfast=failfast) return test_runner.run_tests(test_labels, extra_tests=extra_tests)
bsd-3-clause
petewarden/tensorflow
tensorflow/python/debug/lib/debug_gradients_test.py
11
15831
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Unit tests for debug_gradients module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tempfile from tensorflow.core.protobuf import config_pb2 from tensorflow.core.protobuf import rewriter_config_pb2 from tensorflow.python.client import session from tensorflow.python.debug.lib import debug_data from tensorflow.python.debug.lib import debug_gradients from tensorflow.python.debug.lib import debug_utils from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.lib.io import file_io from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import googletest from tensorflow.python.training import gradient_descent @test_util.run_v1_only("Sessions are not available in TF 2.x") class IdentifyGradientTest(test_util.TensorFlowTestCase): def setUp(self): rewriter_config = rewriter_config_pb2.RewriterConfig( disable_model_pruning=True, dependency_optimization=rewriter_config_pb2.RewriterConfig.OFF) graph_options = config_pb2.GraphOptions(rewrite_options=rewriter_config) config = config_pb2.ConfigProto(graph_options=graph_options) self.sess = session.Session(config=config) with self.sess.as_default(): self.u = variables.Variable(2.0, name="u") self.v = variables.Variable(3.0, name="v") self.w = math_ops.multiply(self.u.value(), self.v.value(), name="w") def tearDown(self): ops.reset_default_graph() debug_gradients.clear_gradient_debuggers() def testIdentifyGradientGivesCorrectTensorObjectWithoutContextManager(self): grad_debugger = debug_gradients.GradientsDebugger() id_grad_w = grad_debugger.identify_gradient(self.w) y = math_ops.add(id_grad_w, -1.0, name="y") grads = gradients_impl.gradients(y, [self.u, self.v]) self.assertEqual(2, len(grads)) u_grad = grads[0] v_grad = grads[1] self.sess.run(variables.global_variables_initializer()) self.assertAllClose(5.0, self.sess.run(y)) self.assertAllClose(3.0, self.sess.run(u_grad)) self.assertAllClose(2.0, self.sess.run(v_grad)) # Fetch the gradient tensor with the x-tensor object. w_grad = grad_debugger.gradient_tensor(self.w) self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) # Fetch the gradient tensor with the x-tensor's name. w_grad = grad_debugger.gradient_tensor(self.w.name) self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) # Fetch the gradient tensor with the x-tensor name. w_grad = grad_debugger.gradient_tensor(self.w.name) self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) def testIdentifyGradientGivesCorrectTensorObjectWithTfGradients(self): grad_debugger = debug_gradients.GradientsDebugger() id_grad_w = grad_debugger.identify_gradient(self.w) y = math_ops.add(id_grad_w, -1.0, name="y") with grad_debugger: grads = gradients_impl.gradients(y, [self.u, self.v]) self.assertEqual(2, len(grads)) u_grad = grads[0] v_grad = grads[1] self.sess.run(variables.global_variables_initializer()) self.assertAllClose(5.0, self.sess.run(y)) self.assertAllClose(3.0, self.sess.run(u_grad)) self.assertAllClose(2.0, self.sess.run(v_grad)) # Fetch the gradient tensor with the x-tensor object. w_grad = grad_debugger.gradient_tensor(self.w) self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) # Fetch the gradient tensor with the x-tensor's name. w_grad = grad_debugger.gradient_tensor(self.w.name) self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) # Fetch the gradient tensor with the x-tensor name. w_grad = grad_debugger.gradient_tensor(self.w.name) self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) def testCallingIdentifyGradientTwiceWithTheSameGradientsDebuggerErrors(self): grad_debugger = debug_gradients.GradientsDebugger() grad_debugger.identify_gradient(self.w) with self.assertRaisesRegex(ValueError, "The graph already contains an op named .*"): grad_debugger.identify_gradient(self.w) def testIdentifyGradientWorksOnMultipleLosses(self): grad_debugger_1 = debug_gradients.GradientsDebugger() grad_debugger_2 = debug_gradients.GradientsDebugger() y = math_ops.add(self.w, -1.0, name="y") debug_y = grad_debugger_1.identify_gradient(y) z1 = math_ops.square(debug_y, name="z1") debug_y = grad_debugger_2.identify_gradient(y) z2 = math_ops.sqrt(debug_y, name="z2") with grad_debugger_1: gradient_descent.GradientDescentOptimizer(0.1).minimize(z1) with grad_debugger_2: gradient_descent.GradientDescentOptimizer(0.1).minimize(z2) dz1_dy = grad_debugger_1.gradient_tensor(y) dz2_dy = grad_debugger_2.gradient_tensor(y) self.assertIsInstance(dz1_dy, ops.Tensor) self.assertIsInstance(dz2_dy, ops.Tensor) self.assertIsNot(dz1_dy, dz2_dy) self.sess.run(variables.global_variables_initializer()) self.assertAllClose(5.0**2, self.sess.run(z1)) self.assertAllClose(5.0**0.5, self.sess.run(z2)) self.assertAllClose(2.0 * 5.0, self.sess.run(dz1_dy)) self.assertAllClose(0.5 * (5.0**-0.5), self.sess.run(dz2_dy)) def testIdentifyGradientRaisesLookupErrorForUnknownXTensor(self): grad_debugger_1 = debug_gradients.GradientsDebugger() grad_debugger_2 = debug_gradients.GradientsDebugger() id_grad_w = grad_debugger_1.identify_gradient(self.w) y = math_ops.add(id_grad_w, -1.0, name="y") # There are >1 gradient debuggers registered, and grad_debugger is not used # as a context manager here, so the gradient w.r.t. self.w will not be # registered. gradients_impl.gradients(y, [self.u, self.v]) with self.assertRaisesRegex( LookupError, r"This GradientsDebugger has not received any gradient tensor for "): grad_debugger_1.gradient_tensor(self.w) with self.assertRaisesRegex( LookupError, r"This GradientsDebugger has not received any gradient tensor for "): grad_debugger_2.gradient_tensor(self.w) def testIdentifyGradientRaisesTypeErrorForNonTensorOrTensorNameInput(self): grad_debugger = debug_gradients.GradientsDebugger() with self.assertRaisesRegex( TypeError, r"x_tensor must be a str or tf\.Tensor or tf\.Variable, but instead " r"has type .*Operation.*"): grad_debugger.gradient_tensor(variables.global_variables_initializer()) def testIdentifyGradientTensorWorksWithGradientDescentOptimizer(self): grad_debugger = debug_gradients.GradientsDebugger() id_grad_w = grad_debugger.identify_gradient(self.w) y = math_ops.add(id_grad_w, -1.0, name="y") with grad_debugger: gradient_descent.GradientDescentOptimizer(0.1).minimize(y) self.sess.run(variables.global_variables_initializer()) # Fetch the gradient tensor with the x-tensor object. w_grad = grad_debugger.gradient_tensor(self.w) self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) def testWatchGradientsByXTensorNamesWorks(self): y = math_ops.add(self.w, -1.0, name="y") # The constructrion of the forward graph has completed. # But we can still get the gradient tensors by using # watch_gradients_by_tensor_names(). grad_debugger = debug_gradients.GradientsDebugger() with grad_debugger.watch_gradients_by_tensor_names(self.sess.graph, "w:0$"): grads = gradients_impl.gradients(y, [self.u, self.v]) self.assertEqual(2, len(grads)) u_grad = grads[0] v_grad = grads[1] self.sess.run(variables.global_variables_initializer()) self.assertAllClose(5.0, self.sess.run(y)) self.assertAllClose(3.0, self.sess.run(u_grad)) self.assertAllClose(2.0, self.sess.run(v_grad)) w_grad = grad_debugger.gradient_tensor(self.w) self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) w_grad = grad_debugger.gradient_tensor("w:0") self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) def testWatchGradientsByXTensorNamesWorksWithoutContextManager(self): y = math_ops.add(self.w, -1.0, name="y") # The constructrion of the forward graph has completed. # But we can still get the gradient tensors by using # watch_gradients_by_tensor_names(). grad_debugger = debug_gradients.GradientsDebugger() grad_debugger.watch_gradients_by_tensor_names(self.sess.graph, "w:0$") grads = gradients_impl.gradients(y, [self.u, self.v]) self.assertEqual(2, len(grads)) u_grad = grads[0] v_grad = grads[1] self.sess.run(variables.global_variables_initializer()) self.assertAllClose(5.0, self.sess.run(y)) self.assertAllClose(3.0, self.sess.run(u_grad)) self.assertAllClose(2.0, self.sess.run(v_grad)) w_grad = grad_debugger.gradient_tensor(self.w) self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) w_grad = grad_debugger.gradient_tensor("w:0") self.assertIsInstance(w_grad, ops.Tensor) self.assertAllClose(1.0, self.sess.run(w_grad)) def testWatchGradientsWorksOnRefTensor(self): y = math_ops.add(self.w, -1.0, name="y") grad_debugger = debug_gradients.GradientsDebugger() with grad_debugger.watch_gradients_by_tensor_names(self.sess.graph, "u:0$"): grads = gradients_impl.gradients(y, [self.u, self.v]) self.assertEqual(2, len(grads)) u_grad = grads[0] v_grad = grads[1] self.assertIs(u_grad, grad_debugger.gradient_tensor("u:0")) self.sess.run(variables.global_variables_initializer()) self.assertAllClose(3.0, self.sess.run(u_grad)) self.assertAllClose(2.0, self.sess.run(v_grad)) self.assertAllClose(3.0, self.sess.run( grad_debugger.gradient_tensor("u:0"))) def testWatchGradientsWorksOnMultipleTensors(self): y = math_ops.add(self.w, -1.0, name="y") grad_debugger = debug_gradients.GradientsDebugger() with grad_debugger.watch_gradients_by_tensor_names(self.sess.graph, "(u|w):0$"): grads = gradients_impl.gradients(y, [self.u, self.v]) self.assertEqual(2, len(grads)) u_grad = grads[0] self.assertEqual(2, len(grad_debugger.gradient_tensors())) self.assertIs(u_grad, grad_debugger.gradient_tensor("u:0")) self.assertIsInstance(grad_debugger.gradient_tensor("w:0"), ops.Tensor) self.sess.run(variables.global_variables_initializer()) self.assertAllClose(1.0, self.sess.run( grad_debugger.gradient_tensor("w:0"))) self.assertAllClose(3.0, self.sess.run( grad_debugger.gradient_tensor("u:0"))) def testWatchGradientsByXTensorsWorks(self): y = math_ops.add(self.w, -1.0, name="foo/y") z = math_ops.square(y, name="foo/z") # The constructrion of the forward graph has completed. # But we can still get the gradient tensors by using # watch_gradients_by_x_tensors(). grad_debugger = debug_gradients.GradientsDebugger() with grad_debugger.watch_gradients_by_tensors(self.sess.graph, [self.w, self.u, y]): gradient_descent.GradientDescentOptimizer(0.1).minimize(z) self.assertEqual(3, len(grad_debugger.gradient_tensors())) u_grad = grad_debugger.gradient_tensor(self.u) w_grad = grad_debugger.gradient_tensor(self.w) y_grad = grad_debugger.gradient_tensor(y) self.sess.run(variables.global_variables_initializer()) self.assertAllClose(10.0, self.sess.run(y_grad)) self.assertAllClose(10.0, self.sess.run(w_grad)) self.assertAllClose(30.0, self.sess.run(u_grad)) def testWatchGradientsByTensorCanWorkOnMultipleLosses(self): y = math_ops.add(self.w, -1.0, name="y") z1 = math_ops.square(y, name="z1") z2 = math_ops.sqrt(y, name="z2") grad_debugger_1 = debug_gradients.GradientsDebugger() with grad_debugger_1.watch_gradients_by_tensors(self.sess.graph, y): gradient_descent.GradientDescentOptimizer(0.1).minimize(z1) grad_debugger_2 = debug_gradients.GradientsDebugger() with grad_debugger_2.watch_gradients_by_tensors(self.sess.graph, y): gradient_descent.GradientDescentOptimizer(0.1).minimize(z2) dz1_dy = grad_debugger_1.gradient_tensor(y) dz2_dy = grad_debugger_2.gradient_tensor(y) self.assertIsInstance(dz1_dy, ops.Tensor) self.assertIsInstance(dz2_dy, ops.Tensor) self.assertIsNot(dz1_dy, dz2_dy) self.sess.run(variables.global_variables_initializer()) self.assertAllClose(5.0**2, self.sess.run(z1)) self.assertAllClose(5.0**0.5, self.sess.run(z2)) self.assertAllClose(2.0 * 5.0, self.sess.run(dz1_dy)) self.assertAllClose(0.5 * (5.0**-0.5), self.sess.run(dz2_dy)) def testGradientsValuesFromDumpWorks(self): y = math_ops.add(self.w, -1.0, name="y") z = math_ops.square(y, name="z") grad_debugger = debug_gradients.GradientsDebugger() with grad_debugger.watch_gradients_by_tensors(self.sess.graph, [self.w, self.u, y]): train_op = gradient_descent.GradientDescentOptimizer(0.1).minimize(z) self.sess.run(variables.global_variables_initializer()) run_options = config_pb2.RunOptions(output_partition_graphs=True) dump_dir = tempfile.mkdtemp() debug_url = "file://" + dump_dir debug_utils.watch_graph(run_options, self.sess.graph, debug_urls=debug_url) run_metadata = config_pb2.RunMetadata() self.assertAllClose(2.0, self.sess.run(self.u)) self.sess.run(train_op, options=run_options, run_metadata=run_metadata) self.assertAllClose(-1.0, self.sess.run(self.u)) dump = debug_data.DebugDumpDir( dump_dir, partition_graphs=run_metadata.partition_graphs) dump.set_python_graph(self.sess.graph) y_grad_values = debug_gradients.gradient_values_from_dump( grad_debugger, y, dump) self.assertEqual(1, len(y_grad_values)) self.assertAllClose(10.0, y_grad_values[0]) w_grad_values = debug_gradients.gradient_values_from_dump( grad_debugger, self.w, dump) self.assertEqual(1, len(w_grad_values)) self.assertAllClose(10.0, w_grad_values[0]) u_grad_values = debug_gradients.gradient_values_from_dump( grad_debugger, self.u, dump) self.assertEqual(1, len(u_grad_values)) self.assertAllClose(30.0, u_grad_values[0]) with self.assertRaisesRegex( LookupError, r"This GradientsDebugger has not received any gradient tensor for " r"x-tensor v:0"): debug_gradients.gradient_values_from_dump(grad_debugger, self.v, dump) # Cleanup. file_io.delete_recursively(dump_dir) if __name__ == "__main__": googletest.main()
apache-2.0
macarthur-lab/leiden_sc
setup.py
1
1393
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='leiden_sc', version='0.1.0', description='Tools for extracting, remapping, and validating variants from Leiden Open Variation Database Installations.', long_description=readme + '\n\n' + history, author='Andrew Hill', author_email='[email protected]', url='https://github.com/andrewhill157/leiden_sc', packages=[ 'leiden_sc', ], package_dir={'leiden_sc': 'leiden_sc'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='leiden_sc', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
bsd-3-clause
colehertz/Stripe-Tester
venv/lib/python3.5/site-packages/pip-7.1.0-py3.5.egg/pip/_vendor/requests/packages/urllib3/response.py
478
16459
try: import http.client as httplib except ImportError: import httplib import zlib import io from socket import timeout as SocketTimeout from ._collections import HTTPHeaderDict from .exceptions import ( ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked ) from .packages.six import string_types as basestring, binary_type, PY3 from .connection import HTTPException, BaseSSLError from .util.response import is_fp_closed class DeflateDecoder(object): def __init__(self): self._first_try = True self._data = binary_type() self._obj = zlib.decompressobj() def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data if not self._first_try: return self._obj.decompress(data) self._data += data try: return self._obj.decompress(data) except zlib.error: self._first_try = False self._obj = zlib.decompressobj(-zlib.MAX_WBITS) try: return self.decompress(self._data) finally: self._data = None class GzipDecoder(object): def __init__(self): self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data return self._obj.decompress(data) def _get_decoder(mode): if mode == 'gzip': return GzipDecoder() return DeflateDecoder() class HTTPResponse(io.IOBase): """ HTTP Response container. Backwards-compatible to httplib's HTTPResponse but the response ``body`` is loaded and decoded on-demand when the ``data`` property is accessed. This class is also compatible with the Python standard library's :mod:`io` module, and can hence be treated as a readable object in the context of that framework. Extra parameters for behaviour not present in httplib.HTTPResponse: :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, attempts to decode specific content-encoding's based on headers (like 'gzip' and 'deflate') will be skipped and raw data will be used instead. :param original_response: When this HTTPResponse wrapper is generated from an httplib.HTTPResponse object, it's convenient to include the original for debug purposes. It's otherwise unused. """ CONTENT_DECODERS = ['gzip', 'deflate'] REDIRECT_STATUSES = [301, 302, 303, 307, 308] def __init__(self, body='', headers=None, status=0, version=0, reason=None, strict=0, preload_content=True, decode_content=True, original_response=None, pool=None, connection=None): if isinstance(headers, HTTPHeaderDict): self.headers = headers else: self.headers = HTTPHeaderDict(headers) self.status = status self.version = version self.reason = reason self.strict = strict self.decode_content = decode_content self._decoder = None self._body = None self._fp = None self._original_response = original_response self._fp_bytes_read = 0 if body and isinstance(body, (basestring, binary_type)): self._body = body self._pool = pool self._connection = connection if hasattr(body, 'read'): self._fp = body # Are we using the chunked-style of transfer encoding? self.chunked = False self.chunk_left = None tr_enc = self.headers.get('transfer-encoding', '').lower() # Don't incur the penalty of creating a list and then discarding it encodings = (enc.strip() for enc in tr_enc.split(",")) if "chunked" in encodings: self.chunked = True # We certainly don't want to preload content when the response is chunked. if not self.chunked and preload_content and not self._body: self._body = self.read(decode_content=decode_content) def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get('location') return False def release_conn(self): if not self._pool or not self._connection: return self._pool._put_conn(self._connection) self._connection = None @property def data(self): # For backwords-compat with earlier urllib3 0.4 and earlier. if self._body: return self._body if self._fp: return self.read(cache_content=True) def tell(self): """ Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). """ return self._fp_bytes_read def _init_decoder(self): """ Set-up the _decoder attribute if necessar. """ # Note: content-encoding value should be case-insensitive, per RFC 7230 # Section 3.2 content_encoding = self.headers.get('content-encoding', '').lower() if self._decoder is None and content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) def _decode(self, data, decode_content, flush_decoder): """ Decode the data passed in and potentially flush the decoder. """ try: if decode_content and self._decoder: data = self._decoder.decompress(data) except (IOError, zlib.error) as e: content_encoding = self.headers.get('content-encoding', '').lower() raise DecodeError( "Received response with content-encoding: %s, but " "failed to decode it." % content_encoding, e) if flush_decoder and decode_content and self._decoder: buf = self._decoder.decompress(binary_type()) data += buf + self._decoder.flush() return data def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) """ self._init_decoder() if decode_content is None: decode_content = self.decode_content if self._fp is None: return flush_decoder = False try: try: if amt is None: # cStringIO doesn't like amt=None data = self._fp.read() flush_decoder = True else: cache_content = False data = self._fp.read(amt) if amt != 0 and not data: # Platform-specific: Buggy versions of Python. # Close the connection when no data is returned # # This is redundant to what httplib/http.client _should_ # already do. However, versions of python released before # December 15, 2012 (http://bugs.python.org/issue16298) do # not properly close the connection in all cases. There is # no harm in redundantly calling close. self._fp.close() flush_decoder = True except SocketTimeout: # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but # there is yet no clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if 'read operation timed out' not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise raise ReadTimeoutError(self._pool, None, 'Read timed out.') except HTTPException as e: # This includes IncompleteRead. raise ProtocolError('Connection broken: %r' % e, e) self._fp_bytes_read += len(data) data = self._decode(data, decode_content, flush_decoder) if cache_content: self._body = data return data finally: if self._original_response and self._original_response.isclosed(): self.release_conn() def stream(self, amt=2**16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ if self.chunked: for line in self.read_chunked(amt, decode_content=decode_content): yield line else: while not is_fp_closed(self._fp): data = self.read(amt=amt, decode_content=decode_content) if data: yield data @classmethod def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if PY3: # Python 3 headers = HTTPHeaderDict(headers.items()) else: # Python 2 headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) resp = ResponseCls(body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw) return resp # Backwards-compatibility methods for httplib.HTTPResponse def getheaders(self): return self.headers def getheader(self, name, default=None): return self.headers.get(name, default) # Overrides from io.IOBase def close(self): if not self.closed: self._fp.close() @property def closed(self): if self._fp is None: return True elif hasattr(self._fp, 'closed'): return self._fp.closed elif hasattr(self._fp, 'isclosed'): # Python 2 return self._fp.isclosed() else: return True def fileno(self): if self._fp is None: raise IOError("HTTPResponse has no file to get a fileno from") elif hasattr(self._fp, "fileno"): return self._fp.fileno() else: raise IOError("The file-like object this HTTPResponse is wrapped " "around has no file descriptor") def flush(self): if self._fp is not None and hasattr(self._fp, 'flush'): return self._fp.flush() def readable(self): # This method is required for `io` module compatibility. return True def readinto(self, b): # This method is required for `io` module compatibility. temp = self.read(len(b)) if len(temp) == 0: return 0 else: b[:len(temp)] = temp return len(temp) def _update_chunk_length(self): # First, we'll figure out length of a chunk and then # we'll try to read it from socket. if self.chunk_left is not None: return line = self._fp.fp.readline() line = line.split(b';', 1)[0] try: self.chunk_left = int(line, 16) except ValueError: # Invalid chunked protocol response, abort. self.close() raise httplib.IncompleteRead(line) def _handle_chunk(self, amt): returned_chunk = None if amt is None: chunk = self._fp._safe_read(self.chunk_left) returned_chunk = chunk self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None elif amt < self.chunk_left: value = self._fp._safe_read(amt) self.chunk_left = self.chunk_left - amt returned_chunk = value elif amt == self.chunk_left: value = self._fp._safe_read(amt) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None returned_chunk = value else: # amt > self.chunk_left returned_chunk = self._fp._safe_read(self.chunk_left) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None return returned_chunk def read_chunked(self, amt=None, decode_content=None): """ Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ self._init_decoder() # FIXME: Rewrite this method and make it a class with a better structured logic. if not self.chunked: raise ResponseNotChunked("Response is not chunked. " "Header 'transfer-encoding: chunked' is missing.") if self._original_response and self._original_response._method.upper() == 'HEAD': # Don't bother reading the body of a HEAD request. # FIXME: Can we do this somehow without accessing private httplib _method? self._original_response.close() return while True: self._update_chunk_length() if self.chunk_left == 0: break chunk = self._handle_chunk(amt) yield self._decode(chunk, decode_content=decode_content, flush_decoder=True) # Chunk content ends with \r\n: discard it. while True: line = self._fp.fp.readline() if not line: # Some sites may not end with '\r\n'. break if line == b'\r\n': break # We read everything; close the "file". if self._original_response: self._original_response.close() self.release_conn()
mit
UstadMobile/eXePUB
exe/webui/mywebbrowser.py
5
23438
#!/usr/bin/python # -*- coding: utf-8 -*- ###! /usr/bin/python2.7 """Interfaces for launching and remotely controlling Web browsers. JRJ: Fichero parcheado de webbrowser.py para que acepte chrome y chromium""" # Maintained by Georg Brandl. import os import shlex import sys import stat import subprocess import time import __builtin__ __all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"] class Error(Exception): pass _browsers = {} # Dictionary of available browser controllers _tryorder = [] # Preference order of available browsers def register(name, klass, instance=None, update_tryorder=1): """Register a browser connector and, optionally, connection.""" _browsers[name.lower().replace(' ', '-')] = [klass, instance] if update_tryorder > 0: _tryorder.append(name) elif update_tryorder < 0: _tryorder.insert(0, name) def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if using is not None: alternatives = [using] else: alternatives = _tryorder for browser in alternatives: if '%s' in browser: # User gave us a command line, split it into name and args browser = shlex.split(browser) if browser[-1] == '&': return BackgroundBrowser(browser[:-1]) else: return GenericBrowser(browser) else: # User gave us a browser name or path. try: command = _browsers[browser.lower()] except KeyError: command = _synthesize(browser) if command[1] is not None: return command[1] elif command[0] is not None: return command[0]() raise Error("could not locate runnable browser") # Please note: the following definition hides a builtin function. # It is recommended one does "import webbrowser" and uses webbrowser.open(url) # instead of "from webbrowser import *". def open(url, new=0, autoraise=True): for name in _tryorder: browser = get(name) if browser.open(url, new, autoraise): return True return False def open_new(url): return open(url, 1) def open_new_tab(url): return open(url, 2) def _synthesize(browser, update_tryorder=1): """Attempt to synthesize a controller base on existing controllers. This is useful to create a controller when a user specifies a path to an entry in the BROWSER environment variable -- we can copy a general controller to operate using a specific installation of the desired browser in this way. If we can't create a controller in this way, or if there is no executable for the requested browser, return [None, None]. """ cmd = browser.split()[0] if not _iscommand(cmd): return [None, None] name = os.path.basename(cmd) try: command = _browsers[name.lower()] except KeyError: return [None, None] # now attempt to clone to fit the new name: controller = command[1] if controller and name.lower() == controller.basename: import copy controller = copy.copy(controller) controller.name = browser controller.basename = os.path.basename(browser) register(browser, None, controller, update_tryorder) return [None, controller] return [None, None] if sys.platform[:3] == "win": def _isexecutable(cmd): cmd = cmd.lower() if os.path.isfile(cmd) and cmd.endswith((".exe", ".bat")): return True for ext in ".exe", ".bat": if os.path.isfile(cmd + ext): return True return False else: def _isexecutable(cmd): if os.path.isfile(cmd): mode = os.stat(cmd)[stat.ST_MODE] if mode & stat.S_IXUSR or mode & stat.S_IXGRP or mode & stat.S_IXOTH: return True return False def _iscommand(cmd): """Return True if cmd is executable or can be found on the executable search path.""" if _isexecutable(cmd): return True path = os.environ.get("PATH") if not path: return False for d in path.split(os.pathsep): exe = os.path.join(d, cmd) if _isexecutable(exe): return True return False # General parent classes class BaseBrowser(object): """Parent class for all browsers. Do not use directly.""" args = ['%s'] def __init__(self, name=""): self.name = name self.basename = name def open(self, url, new=0, autoraise=True): raise NotImplementedError def open_new(self, url): return self.open(url, 1) def open_new_tab(self, url): return self.open(url, 2) class GenericBrowser(BaseBrowser): """Class for all browsers started with a command and without remote functionality.""" def __init__(self, name): if isinstance(name, basestring): self.name = name self.args = ["%s"] else: # name should be a list with arguments self.name = name[0] self.args = name[1:] self.basename = os.path.basename(self.name) def open(self, url, new=0, autoraise=True): cmdline = [self.name] + [arg.replace("%s", url) for arg in self.args] try: if sys.platform[:3] == 'win': p = subprocess.Popen(cmdline) else: p = subprocess.Popen(cmdline, close_fds=True) return not p.wait() except OSError: return False class BackgroundBrowser(GenericBrowser): """Class for all browsers which are to be started in the background.""" def open(self, url, new=0, autoraise=True): cmdline = [self.name] + [arg.replace("%s", url) for arg in self.args] try: if sys.platform[:3] == 'win': p = subprocess.Popen(cmdline) else: setsid = getattr(os, 'setsid', None) if not setsid: setsid = getattr(os, 'setpgrp', None) p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid) return (p.poll() is None) except OSError: return False class UnixBrowser(BaseBrowser): """Parent class for all Unix browsers with remote functionality.""" raise_opts = None remote_args = ['%action', '%s'] remote_action = None remote_action_newwin = None remote_action_newtab = None background = False redirect_stdout = True def _invoke(self, args, remote, autoraise): raise_opt = [] if remote and self.raise_opts: # use autoraise argument only for remote invocation autoraise = int(autoraise) opt = self.raise_opts[autoraise] if opt: raise_opt = [opt] cmdline = [self.name] + raise_opt + args if remote or self.background: inout = file(os.devnull, "r+") else: # for TTY browsers, we need stdin/out inout = None # if possible, put browser in separate process group, so # keyboard interrupts don't affect browser as well as Python setsid = getattr(os, 'setsid', None) if not setsid: setsid = getattr(os, 'setpgrp', None) p = subprocess.Popen(cmdline, close_fds=True, stdin=inout, stdout=(self.redirect_stdout and inout or None), stderr=inout, preexec_fn=setsid) if remote: # wait five seconds. If the subprocess is not finished, the # remote invocation has (hopefully) started a new instance. time.sleep(1) rc = p.poll() if rc is None: time.sleep(4) rc = p.poll() if rc is None: return True # if remote call failed, open() will try direct invocation return not rc elif self.background: if p.poll() is None: return True else: return False else: return not p.wait() def open(self, url, new=0, autoraise=True): if new == 0: action = self.remote_action elif new == 1: action = self.remote_action_newwin elif new == 2: if self.remote_action_newtab is None: action = self.remote_action_newwin else: action = self.remote_action_newtab else: raise Error("Bad 'new' parameter to open(); " + "expected 0, 1, or 2, got %s" % new) args = [arg.replace("%s", url).replace("%action", action) for arg in self.remote_args] success = self._invoke(args, True, autoraise) if not success: # remote invocation failed, try straight way args = [arg.replace("%s", url) for arg in self.args] return self._invoke(args, False, False) else: return True class Mozilla(UnixBrowser): """Launcher class for Mozilla/Netscape browsers.""" raise_opts = [] remote_args = ['%action', '%s'] remote_action = "-new-tab" remote_action_newwin = "-new-window" remote_action_newtab = "-new-tab" background = True Netscape = Mozilla class Galeon(UnixBrowser): """Launcher class for Galeon/Epiphany browsers.""" raise_opts = ["-noraise", ""] remote_args = ['%action', '%s'] remote_action = "-n" remote_action_newwin = "-w" background = True class Opera(UnixBrowser): "Launcher class for Opera browser." raise_opts = ["-noraise", ""] #JR: Se corrige error cuando el opera no estaba abierto #remote_args = ['-remote', 'openURL(%s%action)'] remote_args = ['%action', '%s'] remote_action = "" remote_action_newwin = ",new-window" remote_action_newtab = ",new-page" background = True class Chrome(UnixBrowser): "Launcher class for Google Chrome browser." remote_args = ['%action', '%s'] remote_action = "" remote_action_newwin = "--new-window" remote_action_newtab = "" background = True Chromium = Chrome class Elinks(UnixBrowser): "Launcher class for Elinks browsers." remote_args = ['-remote', 'openURL(%s%action)'] remote_action = "" remote_action_newwin = ",new-window" remote_action_newtab = ",new-tab" background = False # elinks doesn't like its stdout to be redirected - # it uses redirected stdout as a signal to do -dump redirect_stdout = False class Konqueror(BaseBrowser): """Controller for the KDE File Manager (kfm, or Konqueror). See the output of ``kfmclient --commands`` for more information on the Konqueror remote-control interface. """ def open(self, url, new=0, autoraise=True): # XXX Currently I know no way to prevent KFM from opening a new win. if new == 2: action = "newTab" else: action = "openURL" devnull = file(os.devnull, "r+") # if possible, put browser in separate process group, so # keyboard interrupts don't affect browser as well as Python setsid = getattr(os, 'setsid', None) if not setsid: setsid = getattr(os, 'setpgrp', None) try: p = subprocess.Popen(["kfmclient", action, url], close_fds=True, stdin=devnull, stdout=devnull, stderr=devnull) except OSError: # fall through to next variant pass else: p.wait() # kfmclient's return code unfortunately has no meaning as it seems return True try: p = subprocess.Popen(["konqueror", "--silent", url], close_fds=True, stdin=devnull, stdout=devnull, stderr=devnull, preexec_fn=setsid) except OSError: # fall through to next variant pass else: if p.poll() is None: # Should be running now. return True try: p = subprocess.Popen(["kfm", "-d", url], close_fds=True, stdin=devnull, stdout=devnull, stderr=devnull, preexec_fn=setsid) except OSError: return False else: return (p.poll() is None) class Grail(BaseBrowser): # There should be a way to maintain a connection to Grail, but the # Grail remote control protocol doesn't really allow that at this # point. It probably never will! def _find_grail_rc(self): import glob import pwd import socket import tempfile tempdir = os.path.join(tempfile.gettempdir(), ".grail-unix") user = pwd.getpwuid(os.getuid())[0] filename = os.path.join(tempdir, user + "-*") maybes = glob.glob(filename) if not maybes: return None s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) for fn in maybes: # need to PING each one until we find one that's live try: s.connect(fn) except socket.error: # no good; attempt to clean it out, but don't fail: try: os.unlink(fn) except IOError: pass else: return s def _remote(self, action): s = self._find_grail_rc() if not s: return 0 s.send(action) s.close() return 1 def open(self, url, new=0, autoraise=True): if new: ok = self._remote("LOADNEW " + url) else: ok = self._remote("LOAD " + url) return ok # # Platform support for Unix # # These are the right tests because all these Unix browsers require either # a console terminal or an X display to run. def register_X_browsers(): # use xdg-open if around if _iscommand("xdg-open"): register("xdg-open", None, BackgroundBrowser("xdg-open")) # The default GNOME3 browser if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gvfs-open"): register("gvfs-open", None, BackgroundBrowser("gvfs-open")) # The default GNOME browser if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gnome-open"): register("gnome-open", None, BackgroundBrowser("gnome-open")) # The default KDE browser if "KDE_FULL_SESSION" in os.environ and _iscommand("kfmclient"): register("kfmclient", Konqueror, Konqueror("kfmclient")) if _iscommand("x-www-browser"): register("x-www-browser", None, BackgroundBrowser("x-www-browser")) # The Mozilla/Netscape browsers for browser in ("mozilla-firefox", "firefox", "mozilla-firebird", "firebird", "iceweasel", "iceape", "seamonkey", "mozilla", "netscape"): if _iscommand(browser): register(browser, None, Mozilla(browser)) # Konqueror/kfm, the KDE browser. if _iscommand("kfm"): register("kfm", Konqueror, Konqueror("kfm")) elif _iscommand("konqueror"): register("konqueror", Konqueror, Konqueror("konqueror")) # Gnome's Galeon and Epiphany for browser in ("galeon", "epiphany"): if _iscommand(browser): register(browser, None, Galeon(browser)) # Skipstone, another Gtk/Mozilla based browser if _iscommand("skipstone"): register("skipstone", None, BackgroundBrowser("skipstone")) # Opera, quite popular if _iscommand("opera"): register("opera", None, Opera("opera")) # Next, Mosaic -- old but still in use. if _iscommand("mosaic"): register("mosaic", None, BackgroundBrowser("mosaic")) # Grail, the Python browser. Does anybody still use it? if _iscommand("grail"): register("grail", Grail, None) # JR: Register Google Chrome/Chromium browsers for browser in ("google-chrome", "chrome", "chromium", "chromium-browser"): if _iscommand(browser): register(browser, None, Chrome(browser)) # Prefer X browsers if present if os.environ.get("DISPLAY"): register_X_browsers() # Also try console browsers if os.environ.get("TERM"): if _iscommand("www-browser"): register("www-browser", None, GenericBrowser("www-browser")) # The Links/elinks browsers <http://artax.karlin.mff.cuni.cz/~mikulas/links/> if _iscommand("links"): register("links", None, GenericBrowser("links")) if _iscommand("elinks"): register("elinks", None, Elinks("elinks")) # The Lynx browser <http://lynx.isc.org/>, <http://lynx.browser.org/> if _iscommand("lynx"): register("lynx", None, GenericBrowser("lynx")) # The w3m browser <http://w3m.sourceforge.net/> if _iscommand("w3m"): register("w3m", None, GenericBrowser("w3m")) # # Platform support for Windows # if sys.platform[:3] == "win": class WindowsDefault(BaseBrowser): def open(self, url, new=0, autoraise=True): try: os.startfile(url) except WindowsError: # [Error 22] No application is associated with the specified # file for this operation: '<URL>' return False else: return True _tryorder = [] _browsers = {} # First try to use the default Windows browser register("windows-default", WindowsDefault) # Detect some common Windows browsers from _winreg import OpenKey, QueryValue, EnumKey, HKEY_LOCAL_MACHINE key = None try: key = OpenKey(HKEY_LOCAL_MACHINE, r'SOFTWARE\Clients\StartMenuInternet') i = 0 while True: try: bkey_name = EnumKey(key, i) except: break bkey = OpenKey(key, bkey_name) bpath = QueryValue(bkey, r'shell\open\command') bname = QueryValue(bkey, '') register(bname, None, BackgroundBrowser(bpath.strip('"'))) bkey.Close() i = i + 1 except: pass finally: if key: key.Close() # # Platform support for MacOS # if sys.platform == 'darwin': # Adapted from patch submitted to SourceForge by Steven J. Burr class MacOSX(BaseBrowser): """Launcher class for Aqua browsers on Mac OS X Optionally specify a browser name on instantiation. Note that this will not work for Aqua browsers if the user has moved the application package after installation. If no browser is specified, the default browser, as specified in the Internet System Preferences panel, will be used. """ def open(self, url, new=0, autoraise=True): assert "'" not in url # hack for local urls if not ':' in url: url = 'file:'+url # new must be 0 or 1 new = int(bool(new)) if self.name == "default": # User called open, open_new or get without a browser parameter script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser else: # User called get and chose a browser if self.name == "OmniWeb": toWindow = "" else: # Include toWindow parameter of OpenURL command for browsers # that support it. 0 == new window; -1 == existing toWindow = "toWindow %d" % (new - 1) cmd = 'OpenURL "%s"' % url.replace('"', '%22') script = '''tell application "%s" activate %s %s end tell''' % (self.name, cmd, toWindow) # Open pipe to AppleScript through osascript command osapipe = os.popen("osascript", "w") if osapipe is None: return False # Write script to osascript's stdin osapipe.write(script) rc = osapipe.close() return not rc class MacOSXOSAScript(BaseBrowser): def open(self, url, new=0, autoraise=True): if self.name == 'default': script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser else: script = ''' tell application "%s" activate open location "%s" end '''%(self.name, url.replace('"', '%22')) osapipe = os.popen("osascript", "w") if osapipe is None: return False osapipe.write(script) rc = osapipe.close() return not rc def _isinstalled(browser): script = ''' get version of application "%s" ''' % browser f = __builtin__.open(os.devnull, 'w') rc = subprocess.call("osascript -e '%s'" % script, shell=True, stdout=f, stderr=f) return not rc # Don't clear _tryorder or _browsers since OS X can use above Unix support # (but we prefer using the OS X specific stuff) for browser in ['Google Chrome', 'Firefox', 'Safari', 'Opera']: if _isinstalled(browser): register(browser, None, MacOSXOSAScript(browser)) register("MacOSX", None, MacOSXOSAScript('default'), -1) # # Platform support for OS/2 # if sys.platform[:3] == "os2" and _iscommand("netscape"): _tryorder = [] _browsers = {} register("os2netscape", None, GenericBrowser(["start", "netscape", "%s"]), -1) # OK, now that we know what the default preference orders for each # platform are, allow user to override them with the BROWSER variable. if "BROWSER" in os.environ: _userchoices = os.environ["BROWSER"].split(os.pathsep) _userchoices.reverse() # Treat choices in same way as if passed into get() but do register # and prepend to _tryorder for cmdline in _userchoices: if cmdline != '': cmd = _synthesize(cmdline, -1) if cmd[1] is None: register(cmdline, None, GenericBrowser(cmdline), -1) cmdline = None # to make del work if _userchoices was empty del cmdline del _userchoices # what to do if _tryorder is now empty? def main(): import getopt usage = """Usage: %s [-n | -t] url -n: open new window -t: open new tab""" % sys.argv[0] try: opts, args = getopt.getopt(sys.argv[1:], 'ntd') except getopt.error, msg: print >>sys.stderr, msg print >>sys.stderr, usage sys.exit(1) new_win = 0 for o, a in opts: if o == '-n': new_win = 1 elif o == '-t': new_win = 2 if len(args) != 1: print >>sys.stderr, usage sys.exit(1) url = args[0] open(url, new_win) print "\a" if __name__ == "__main__": main()
gpl-2.0
mne-tools/mne-tools.github.io
0.14/_downloads/plot_stockwell.py
20
1690
""" ======================================================= Time frequency with Stockwell transform in sensor space ======================================================= This script shows how to compute induced power and intertrial coherence using the Stockwell transform, a.k.a. S-Transform. """ # Authors: Denis A. Engemann <[email protected]> # Alexandre Gramfort <[email protected]> # # License: BSD (3-clause) import mne from mne import io from mne.time_frequency import tfr_stockwell from mne.datasets import somato print(__doc__) ############################################################################### # Set parameters data_path = somato.data_path() raw_fname = data_path + '/MEG/somato/sef_raw_sss.fif' event_id, tmin, tmax = 1, -1., 3. # Setup for reading the raw data raw = io.Raw(raw_fname) baseline = (None, 0) events = mne.find_events(raw, stim_channel='STI 014') # picks MEG gradiometers picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True, stim=False) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6), preload=True) ############################################################################### # Calculate power and intertrial coherence epochs = epochs.pick_channels([epochs.ch_names[82]]) # reduce computation power, itc = tfr_stockwell(epochs, fmin=6., fmax=30., decim=4, n_jobs=1, width=.3, return_itc=True) power.plot([0], baseline=(-0.5, 0), mode=None, title='S-transform (power)') itc.plot([0], baseline=None, mode=None, title='S-transform (ITC)')
bsd-3-clause
zouzhberk/ambaridemo
demo-server/src/main/resources/stacks/BIGTOP/0.8/services/GANGLIA/package/scripts/ganglia_monitor.py
1
7069
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys import os from os import path from resource_management import * from ganglia import generate_daemon import ganglia import functions import ganglia_monitor_service class GangliaMonitor(Script): def install(self, env): import params self.install_packages(env) env.set_params(params) self.configure(env) functions.turn_off_autostart(params.gmond_service_name) functions.turn_off_autostart("gmetad") # since the package is installed as well def start(self, env): import params env.set_params(params) self.configure(env) ganglia_monitor_service.monitor("start") def stop(self, env): ganglia_monitor_service.monitor("stop") def status(self, env): import status_params pid_file_name = 'gmond.pid' pid_file_count = 0 pid_dir = status_params.pid_dir # Recursively check all existing gmond pid files for cur_dir, subdirs, files in os.walk(pid_dir): for file_name in files: if file_name == pid_file_name: pid_file = os.path.join(cur_dir, file_name) check_process_status(pid_file) pid_file_count += 1 if pid_file_count == 0: # If no any pid file is present raise ComponentIsNotRunning() def configure(self, env): import params ganglia.groups_and_users() Directory(params.ganglia_conf_dir, owner="root", group=params.user_group, recursive=True ) ganglia.config() self.generate_slave_configs() Directory(path.join(params.ganglia_dir, "conf.d"), owner="root", group=params.user_group ) File(path.join(params.ganglia_dir, "conf.d/modgstatus.conf"), owner="root", group=params.user_group ) File(path.join(params.ganglia_dir, "conf.d/multicpu.conf"), owner="root", group=params.user_group ) File(path.join(params.ganglia_dir, "gmond.conf"), owner="root", group=params.user_group ) if params.is_ganglia_server_host: self.generate_master_configs() if len(params.gmond_apps) != 0: self.generate_app_configs() pass pass def generate_app_configs(self): import params for gmond_app in params.gmond_apps: generate_daemon("gmond", name=gmond_app[0], role="server", owner="root", group=params.user_group) generate_daemon("gmond", name = gmond_app[0], role = "monitor", owner = "root", group = params.user_group) pass def generate_slave_configs(self): import params generate_daemon("gmond", name = "HDPSlaves", role = "monitor", owner = "root", group = params.user_group) def generate_master_configs(self): import params if params.has_namenodes: generate_daemon("gmond", name = "HDPNameNode", role = "server", owner = "root", group = params.user_group) if params.has_jobtracker: generate_daemon("gmond", name = "HDPJobTracker", role = "server", owner = "root", group = params.user_group) if params.has_hbase_masters: generate_daemon("gmond", name = "HDPHBaseMaster", role = "server", owner = "root", group = params.user_group) if params.has_resourcemanager: generate_daemon("gmond", name = "HDPResourceManager", role = "server", owner = "root", group = params.user_group) if params.has_nodemanager: generate_daemon("gmond", name = "HDPNodeManager", role = "server", owner = "root", group = params.user_group) if params.has_historyserver: generate_daemon("gmond", name = "HDPHistoryServer", role = "server", owner = "root", group = params.user_group) if params.has_slaves: generate_daemon("gmond", name = "HDPDataNode", role = "server", owner = "root", group = params.user_group) if params.has_tasktracker: generate_daemon("gmond", name = "HDPTaskTracker", role = "server", owner = "root", group = params.user_group) if params.has_hbase_rs: generate_daemon("gmond", name = "HDPHBaseRegionServer", role = "server", owner = "root", group = params.user_group) if params.has_nimbus_server: generate_daemon("gmond", name = "HDPNimbus", role = "server", owner = "root", group = params.user_group) if params.has_supervisor_server: generate_daemon("gmond", name = "HDPSupervisor", role = "server", owner = "root", group = params.user_group) if params.has_flume: generate_daemon("gmond", name = "HDPFlumeServer", role = "server", owner = "root", group = params.user_group) if params.has_journalnode: generate_daemon("gmond", name = "HDPJournalNode", role = "server", owner = "root", group = params.user_group) generate_daemon("gmond", name = "HDPSlaves", role = "server", owner = "root", group = params.user_group) if __name__ == "__main__": GangliaMonitor().execute()
apache-2.0
shingonoide/odoo
addons/mail/mail_vote.py
439
1647
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-Today OpenERP SA (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## from openerp.osv import fields, osv class mail_vote(osv.Model): ''' Mail vote feature allow users to like and unlike messages attached to a document. This allows for example to build a ranking-based displaying of messages, for FAQ. ''' _name = 'mail.vote' _description = 'Mail Vote' _columns = { 'message_id': fields.many2one('mail.message', 'Message', select=1, ondelete='cascade', required=True), 'user_id': fields.many2one('res.users', 'User', select=1, ondelete='cascade', required=True), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
pniedzielski/fb-hackathon-2013-11-21
src/repl.it/jsrepl/extern/python/reloop-closured/lib/python2.7/smtplib.py
74
30703
#! /usr/bin/env python '''SMTP/ESMTP client class. This should follow RFC 821 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Notes: Please remember, when doing ESMTP, that the names of the SMTP service extensions are NOT the same thing as the option keywords for the RCPT and MAIL commands! Example: >>> import smtplib >>> s=smtplib.SMTP("localhost") >>> print s.help() This is Sendmail version 8.8.4 Topics: HELO EHLO MAIL RCPT DATA RSET NOOP QUIT HELP VRFY EXPN VERB ETRN DSN For more info use "HELP <topic>". To report bugs in the implementation send email to [email protected]. For local information send email to Postmaster at your site. End of HELP info >>> s.putcmd("vrfy","someone@here") >>> s.getreply() (250, "Somebody OverHere <[email protected]>") >>> s.quit() ''' # Author: The Dragon De Monsyne <[email protected]> # ESMTP support, test code and doc fixes added by # Eric S. Raymond <[email protected]> # Better RFC 821 compliance (MAIL and RCPT, and CRLF in data) # by Carey Evans <[email protected]>, for picky mail servers. # RFC 2554 (authentication) support by Gerhard Haering <[email protected]>. # # This was modified from the Python 1.5 library HTTP lib. import socket import re import email.utils import base64 import hmac from email.base64mime import encode as encode_base64 from sys import stderr __all__ = ["SMTPException", "SMTPServerDisconnected", "SMTPResponseException", "SMTPSenderRefused", "SMTPRecipientsRefused", "SMTPDataError", "SMTPConnectError", "SMTPHeloError", "SMTPAuthenticationError", "quoteaddr", "quotedata", "SMTP"] SMTP_PORT = 25 SMTP_SSL_PORT = 465 CRLF = "\r\n" OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I) # Exception classes used by this module. class SMTPException(Exception): """Base class for all exceptions raised by this module.""" class SMTPServerDisconnected(SMTPException): """Not connected to any SMTP server. This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server. """ class SMTPResponseException(SMTPException): """Base class for all exceptions that include an SMTP error code. These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the `smtp_code' attribute of the error, and the `smtp_error' attribute is set to the error message. """ def __init__(self, code, msg): self.smtp_code = code self.smtp_error = msg self.args = (code, msg) class SMTPSenderRefused(SMTPResponseException): """Sender address refused. In addition to the attributes set by on all SMTPResponseException exceptions, this sets `sender' to the string that the SMTP refused. """ def __init__(self, code, msg, sender): self.smtp_code = code self.smtp_error = msg self.sender = sender self.args = (code, msg, sender) class SMTPRecipientsRefused(SMTPException): """All recipient addresses refused. The errors for each recipient are accessible through the attribute 'recipients', which is a dictionary of exactly the same sort as SMTP.sendmail() returns. """ def __init__(self, recipients): self.recipients = recipients self.args = (recipients,) class SMTPDataError(SMTPResponseException): """The SMTP server didn't accept the data.""" class SMTPConnectError(SMTPResponseException): """Error during connection establishment.""" class SMTPHeloError(SMTPResponseException): """The server refused our HELO reply.""" class SMTPAuthenticationError(SMTPResponseException): """Authentication error. Most probably the server didn't accept the username/password combination provided. """ def quoteaddr(addr): """Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything rfc822.parseaddr can handle. """ m = (None, None) try: m = email.utils.parseaddr(addr)[1] except AttributeError: pass if m == (None, None): # Indicates parse failure or AttributeError # something weird here.. punt -ddm return "<%s>" % addr elif m is None: # the sender wants an empty return address return "<>" else: return "<%s>" % m def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\\n', or Mac '\\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) try: import ssl except ImportError: _have_ssl = False else: class SSLFakeFile: """A fake file like object that really wraps a SSLObject. It only supports what is needed in smtplib. """ def __init__(self, sslobj): self.sslobj = sslobj def readline(self): str = "" chr = None while chr != "\n": chr = self.sslobj.read(1) if not chr: break str += chr return str def close(self): pass _have_ssl = True class SMTP: """This class manages a connection to an SMTP or ESMTP server. SMTP Objects: SMTP objects have the following attributes: helo_resp This is the message given by the server in response to the most recent HELO command. ehlo_resp This is the message given by the server in response to the most recent EHLO command. This is usually multiline. does_esmtp This is a True value _after you do an EHLO command_, if the server supports ESMTP. esmtp_features This is a dictionary, which, if the server supports ESMTP, will _after you do an EHLO command_, contain the names of the SMTP service extensions this server supports, and their parameters (if any). Note, all extension names are mapped to lower case in the dictionary. See each method's docstrings for details. In general, there is a method of the same name to perform each SMTP command. There is also a method called 'sendmail' that will do an entire mail transaction. """ debuglevel = 0 file = None helo_resp = None ehlo_msg = "ehlo" ehlo_resp = None does_esmtp = 0 default_port = SMTP_PORT def __init__(self, host='', port=0, local_hostname=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): """Initialize a new instance. If specified, `host' is the name of the remote host to which to connect. If specified, `port' specifies the port to which to connect. By default, smtplib.SMTP_PORT is used. An SMTPConnectError is raised if the specified `host' doesn't respond correctly. If specified, `local_hostname` is used as the FQDN of the local host. By default, the local hostname is found using socket.getfqdn(). """ self.timeout = timeout self.esmtp_features = {} if host: (code, msg) = self.connect(host, port) if code != 220: raise SMTPConnectError(code, msg) if local_hostname is not None: self.local_hostname = local_hostname else: # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and # if that can't be calculated, that we should use a domain literal # instead (essentially an encoded IP address like [A.B.C.D]). fqdn = socket.getfqdn() if '.' in fqdn: self.local_hostname = fqdn else: # We can't find an fqdn hostname, so use a domain literal addr = '127.0.0.1' try: addr = socket.gethostbyname(socket.gethostname()) except socket.gaierror: pass self.local_hostname = '[%s]' % addr def set_debuglevel(self, debuglevel): """Set the debug output level. A non-false value results in debug messages for connection and for all messages sent to and received from the server. """ self.debuglevel = debuglevel def _get_socket(self, port, host, timeout): # This makes it simpler for SMTP_SSL to use the SMTP connect code # and just alter the socket connection bit. if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) return socket.create_connection((port, host), timeout) def connect(self, host='localhost', port=0): """Connect to a host on a given port. If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. Note: This method is automatically invoked by __init__, if a host is specified during instantiation. """ if not port and (host.find(':') == host.rfind(':')): i = host.rfind(':') if i >= 0: host, port = host[:i], host[i + 1:] try: port = int(port) except ValueError: raise socket.error, "nonnumeric port" if not port: port = self.default_port if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) self.sock = self._get_socket(host, port, self.timeout) (code, msg) = self.getreply() if self.debuglevel > 0: print>>stderr, "connect:", msg return (code, msg) def send(self, str): """Send `str' to the server.""" if self.debuglevel > 0: print>>stderr, 'send:', repr(str) if hasattr(self, 'sock') and self.sock: try: self.sock.sendall(str) except socket.error: self.close() raise SMTPServerDisconnected('Server not connected') else: raise SMTPServerDisconnected('please run connect() first') def putcmd(self, cmd, args=""): """Send a command to the server.""" if args == "": str = '%s%s' % (cmd, CRLF) else: str = '%s %s%s' % (cmd, args, CRLF) self.send(str) def getreply(self): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (multiline responses are converted to a single, multiline string). Raises SMTPServerDisconnected if end-of-file is reached. """ resp = [] if self.file is None: self.file = self.sock.makefile('rb') while 1: try: line = self.file.readline() except socket.error: line = '' if line == '': self.close() raise SMTPServerDisconnected("Connection unexpectedly closed") if self.debuglevel > 0: print>>stderr, 'reply:', repr(line) resp.append(line[4:].strip()) code = line[:3] # Check that the error code is syntactically correct. # Don't attempt to read a continuation line if it is broken. try: errcode = int(code) except ValueError: errcode = -1 break # Check if multiline response. if line[3:4] != "-": break errmsg = "\n".join(resp) if self.debuglevel > 0: print>>stderr, 'reply: retcode (%s); Msg: %s' % (errcode, errmsg) return errcode, errmsg def docmd(self, cmd, args=""): """Send a command, and return its response code.""" self.putcmd(cmd, args) return self.getreply() # std smtp commands def helo(self, name=''): """SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host. """ self.putcmd("helo", name or self.local_hostname) (code, msg) = self.getreply() self.helo_resp = msg return (code, msg) def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. """ self.esmtp_features = {} self.putcmd(self.ehlo_msg, name or self.local_hostname) (code, msg) = self.getreply() # According to RFC1869 some (badly written) # MTA's will disconnect on an ehlo. Toss an exception if # that happens -ddm if code == -1 and len(msg) == 0: self.close() raise SMTPServerDisconnected("Server not connected") self.ehlo_resp = msg if code != 250: return (code, msg) self.does_esmtp = 1 #parse the ehlo response -ddm resp = self.ehlo_resp.split('\n') del resp[0] for each in resp: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account, # because: # 1) Else our SMTP feature parser gets confused. # 2) There are some servers that only advertise the auth methods we # support using the old style. auth_match = OLDSTYLE_AUTH.match(each) if auth_match: # This doesn't remove duplicates, but that's no problem self.esmtp_features["auth"] = self.esmtp_features.get("auth", "") \ + " " + auth_match.groups(0)[0] continue # RFC 1869 requires a space between ehlo keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. Note # that the space isn't present if there are no parameters. m = re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?', each) if m: feature = m.group("feature").lower() params = m.string[m.end("feature"):].strip() if feature == "auth": self.esmtp_features[feature] = self.esmtp_features.get(feature, "") \ + " " + params else: self.esmtp_features[feature] = params return (code, msg) def has_extn(self, opt): """Does the server support a given SMTP service extension?""" return opt.lower() in self.esmtp_features def help(self, args=''): """SMTP 'help' command. Returns help text from server.""" self.putcmd("help", args) return self.getreply()[1] def rset(self): """SMTP 'rset' command -- resets session.""" return self.docmd("rset") def noop(self): """SMTP 'noop' command -- doesn't do anything :>""" return self.docmd("noop") def mail(self, sender, options=[]): """SMTP 'mail' command -- begins mail xfer session.""" optionlist = '' if options and self.does_esmtp: optionlist = ' ' + ' '.join(options) self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist)) return self.getreply() def rcpt(self, recip, options=[]): """SMTP 'rcpt' command -- indicates 1 recipient for this mail.""" optionlist = '' if options and self.does_esmtp: optionlist = ' ' + ' '.join(options) self.putcmd("rcpt", "TO:%s%s" % (quoteaddr(recip), optionlist)) return self.getreply() def data(self, msg): """SMTP 'DATA' command -- sends message data to server. Automatically quotes lines beginning with a period per rfc821. Raises SMTPDataError if there is an unexpected reply to the DATA command; the return value from this method is the final response code received when the all data is sent. """ self.putcmd("data") (code, repl) = self.getreply() if self.debuglevel > 0: print>>stderr, "data:", (code, repl) if code != 354: raise SMTPDataError(code, repl) else: q = quotedata(msg) if q[-2:] != CRLF: q = q + CRLF q = q + "." + CRLF self.send(q) (code, msg) = self.getreply() if self.debuglevel > 0: print>>stderr, "data:", (code, msg) return (code, msg) def verify(self, address): """SMTP 'verify' command -- checks for address validity.""" self.putcmd("vrfy", quoteaddr(address)) return self.getreply() # a.k.a. vrfy = verify def expn(self, address): """SMTP 'expn' command -- expands a mailing list.""" self.putcmd("expn", quoteaddr(address)) return self.getreply() # some useful methods def ehlo_or_helo_if_needed(self): """Call self.ehlo() and/or self.helo() if needed. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. """ if self.helo_resp is None and self.ehlo_resp is None: if not (200 <= self.ehlo()[0] <= 299): (code, resp) = self.helo() if not (200 <= code <= 299): raise SMTPHeloError(code, resp) def login(self, user, password): """Log in on an SMTP server that requires authentication. The arguments are: - user: The user name to authenticate with. - password: The password for the authentication. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method will return normally if the authentication was successful. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. SMTPAuthenticationError The server didn't accept the username/ password combination. SMTPException No suitable authentication method was found. """ def encode_cram_md5(challenge, user, password): challenge = base64.decodestring(challenge) response = user + " " + hmac.HMAC(password, challenge).hexdigest() return encode_base64(response, eol="") def encode_plain(user, password): return encode_base64("\0%s\0%s" % (user, password), eol="") AUTH_PLAIN = "PLAIN" AUTH_CRAM_MD5 = "CRAM-MD5" AUTH_LOGIN = "LOGIN" self.ehlo_or_helo_if_needed() if not self.has_extn("auth"): raise SMTPException("SMTP AUTH extension not supported by server.") # Authentication methods the server supports: authlist = self.esmtp_features["auth"].split() # List of authentication methods we support: from preferred to # less preferred methods. Except for the purpose of testing the weaker # ones, we prefer stronger methods like CRAM-MD5: preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN] # Determine the authentication method we'll use authmethod = None for method in preferred_auths: if method in authlist: authmethod = method break if authmethod == AUTH_CRAM_MD5: (code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5) if code == 503: # 503 == 'Error: already authenticated' return (code, resp) (code, resp) = self.docmd(encode_cram_md5(resp, user, password)) elif authmethod == AUTH_PLAIN: (code, resp) = self.docmd("AUTH", AUTH_PLAIN + " " + encode_plain(user, password)) elif authmethod == AUTH_LOGIN: (code, resp) = self.docmd("AUTH", "%s %s" % (AUTH_LOGIN, encode_base64(user, eol=""))) if code != 334: raise SMTPAuthenticationError(code, resp) (code, resp) = self.docmd(encode_base64(password, eol="")) elif authmethod is None: raise SMTPException("No suitable authentication method found.") if code not in (235, 503): # 235 == 'Authentication successful' # 503 == 'Error: already authenticated' raise SMTPAuthenticationError(code, resp) return (code, resp) def starttls(self, keyfile=None, certfile=None): """Puts the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports TLS, this will encrypt the rest of the SMTP session. If you provide the keyfile and certfile parameters, the identity of the SMTP server and client can be checked. This, however, depends on whether the socket module really checks the certificates. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. """ self.ehlo_or_helo_if_needed() if not self.has_extn("starttls"): raise SMTPException("STARTTLS extension not supported by server.") (resp, reply) = self.docmd("STARTTLS") if resp == 220: if not _have_ssl: raise RuntimeError("No SSL support included in this Python") self.sock = ssl.wrap_socket(self.sock, keyfile, certfile) self.file = SSLFakeFile(self.sock) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. self.helo_resp = None self.ehlo_resp = None self.esmtp_features = {} self.does_esmtp = 0 return (resp, reply) def sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]): """This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - msg : The message to send. - mail_options : List of ESMTP options (such as 8bitmime) for the mail command. - rcpt_options : List of ESMTP options (such as DSN commands) for all the rcpt commands. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it. If EHLO fails, HELO will be tried and ESMTP options suppressed. This method will return normally if the mail is accepted for at least one recipient. It returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. SMTPRecipientsRefused The server rejected ALL recipients (no mail was sent). SMTPSenderRefused The server didn't accept the from_addr. SMTPDataError The server replied with an unexpected error code (other than a refusal of a recipient). Note: the connection will be open even after an exception is raised. Example: >>> import smtplib >>> s=smtplib.SMTP("localhost") >>> tolist=["[email protected]","[email protected]","[email protected]","[email protected]"] >>> msg = '''\\ ... From: [email protected] ... Subject: testin'... ... ... This is a test ''' >>> s.sendmail("[email protected]",tolist,msg) { "[email protected]" : ( 550 ,"User unknown" ) } >>> s.quit() In the above example, the message was accepted for delivery to three of the four addresses, and one was rejected, with the error code 550. If all addresses are accepted, then the method will return an empty dictionary. """ self.ehlo_or_helo_if_needed() esmtp_opts = [] if self.does_esmtp: # Hmmm? what's this? -ddm # self.esmtp_features['7bit']="" if self.has_extn('size'): esmtp_opts.append("size=%d" % len(msg)) for option in mail_options: esmtp_opts.append(option) (code, resp) = self.mail(from_addr, esmtp_opts) if code != 250: self.rset() raise SMTPSenderRefused(code, resp, from_addr) senderrs = {} if isinstance(to_addrs, basestring): to_addrs = [to_addrs] for each in to_addrs: (code, resp) = self.rcpt(each, rcpt_options) if (code != 250) and (code != 251): senderrs[each] = (code, resp) if len(senderrs) == len(to_addrs): # the server refused all our recipients self.rset() raise SMTPRecipientsRefused(senderrs) (code, resp) = self.data(msg) if code != 250: self.rset() raise SMTPDataError(code, resp) #if we got here then somebody got our mail return senderrs def close(self): """Close the connection to the SMTP server.""" if self.file: self.file.close() self.file = None if self.sock: self.sock.close() self.sock = None def quit(self): """Terminate the SMTP session.""" res = self.docmd("quit") self.close() return res if _have_ssl: class SMTP_SSL(SMTP): """ This is a subclass derived from SMTP that connects over an SSL encrypted socket (to use this class you need a socket module that was compiled with SSL support). If host is not specified, '' (the local host) is used. If port is omitted, the standard SMTP-over-SSL port (465) is used. keyfile and certfile are also optional - they can contain a PEM formatted private key and certificate chain file for the SSL connection. """ default_port = SMTP_SSL_PORT def __init__(self, host='', port=0, local_hostname=None, keyfile=None, certfile=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): self.keyfile = keyfile self.certfile = certfile SMTP.__init__(self, host, port, local_hostname, timeout) def _get_socket(self, host, port, timeout): if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) new_socket = socket.create_connection((host, port), timeout) new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile) self.file = SSLFakeFile(new_socket) return new_socket __all__.append("SMTP_SSL") # # LMTP extension # LMTP_PORT = 2003 class LMTP(SMTP): """LMTP - Local Mail Transfer Protocol The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. It's common to use Unix sockets for LMTP, so our connect() method must support that as well as a regular host:port server. To specify a Unix socket, you must use an absolute path as the host, starting with a '/'. Authentication is supported, using the regular SMTP mechanism. When using a Unix socket, LMTP generally don't support or require any authentication, but your mileage might vary.""" ehlo_msg = "lhlo" def __init__(self, host='', port=LMTP_PORT, local_hostname=None): """Initialize a new instance.""" SMTP.__init__(self, host, port, local_hostname) def connect(self, host='localhost', port=0): """Connect to the LMTP daemon, on either a Unix or a TCP socket.""" if host[0] != '/': return SMTP.connect(self, host, port) # Handle Unix-domain sockets. try: self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.connect(host) except socket.error, msg: if self.debuglevel > 0: print>>stderr, 'connect fail:', host if self.sock: self.sock.close() self.sock = None raise socket.error, msg (code, msg) = self.getreply() if self.debuglevel > 0: print>>stderr, "connect:", msg return (code, msg) # Test the sendmail method, which tests most of the others. # Note: This always sends to localhost. if __name__ == '__main__': import sys def prompt(prompt): sys.stdout.write(prompt + ": ") return sys.stdin.readline().strip() fromaddr = prompt("From") toaddrs = prompt("To").split(',') print "Enter message, end with ^D:" msg = '' while 1: line = sys.stdin.readline() if not line: break msg = msg + line print "Message length is %d" % len(msg) server = SMTP('localhost') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit()
agpl-3.0
toshywoshy/ansible
lib/ansible/module_utils/network/junos/argspec/vlans/vlans.py
23
1549
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ############################################# # WARNING # ############################################# # # This file is auto generated by the resource # module builder playbook. # # Do not edit this file manually. # # Changes to this file will be over written # by the resource module builder. # # Changes should be made in the model used to # generate this file or in the resource module # builder template. # ############################################# """ The arg spec for the junos_vlans module """ from __future__ import absolute_import, division, print_function __metaclass__ = type class VlansArgs(object): # pylint: disable=R0903 """The arg spec for the junos_vlans module """ def __init__(self, **kwargs): pass argument_spec = {'config': {'elements': 'dict', 'options': { 'description': {}, 'name': {'required': True, 'type': 'str'}, 'vlan_id': {'type': 'int'}}, 'type': 'list'}, 'state': { 'choices': ['merged', 'replaced', 'overridden', 'deleted'], 'default': 'merged', 'type': 'str'}} # pylint: disable=C0301
gpl-3.0
Tranzystorek/servo
tests/wpt/web-platform-tests/tools/pytest/testing/code/test_excinfo.py
165
30814
# -*- coding: utf-8 -*- import _pytest import py import pytest from _pytest._code.code import FormattedExcinfo, ReprExceptionInfo queue = py.builtin._tryimport('queue', 'Queue') failsonjython = pytest.mark.xfail("sys.platform.startswith('java')") from test_source import astonly try: import importlib except ImportError: invalidate_import_caches = None else: invalidate_import_caches = getattr(importlib, "invalidate_caches", None) import pytest pytest_version_info = tuple(map(int, pytest.__version__.split(".")[:3])) class TWMock: def __init__(self): self.lines = [] def sep(self, sep, line=None): self.lines.append((sep, line)) def line(self, line, **kw): self.lines.append(line) def markup(self, text, **kw): return text fullwidth = 80 def test_excinfo_simple(): try: raise ValueError except ValueError: info = _pytest._code.ExceptionInfo() assert info.type == ValueError def test_excinfo_getstatement(): def g(): raise ValueError def f(): g() try: f() except ValueError: excinfo = _pytest._code.ExceptionInfo() linenumbers = [_pytest._code.getrawcode(f).co_firstlineno - 1 + 3, _pytest._code.getrawcode(f).co_firstlineno - 1 + 1, _pytest._code.getrawcode(g).co_firstlineno - 1 + 1, ] l = list(excinfo.traceback) foundlinenumbers = [x.lineno for x in l] assert foundlinenumbers == linenumbers #for x in info: # print "%s:%d %s" %(x.path.relto(root), x.lineno, x.statement) #xxx # testchain for getentries test below def f(): # raise ValueError # def g(): # __tracebackhide__ = True f() # def h(): # g() # class TestTraceback_f_g_h: def setup_method(self, method): try: h() except ValueError: self.excinfo = _pytest._code.ExceptionInfo() def test_traceback_entries(self): tb = self.excinfo.traceback entries = list(tb) assert len(tb) == 4 # maybe fragile test assert len(entries) == 4 # maybe fragile test names = ['f', 'g', 'h'] for entry in entries: try: names.remove(entry.frame.code.name) except ValueError: pass assert not names def test_traceback_entry_getsource(self): tb = self.excinfo.traceback s = str(tb[-1].getsource() ) assert s.startswith("def f():") assert s.endswith("raise ValueError") @astonly @failsonjython def test_traceback_entry_getsource_in_construct(self): source = _pytest._code.Source("""\ def xyz(): try: raise ValueError except somenoname: pass xyz() """) try: exec (source.compile()) except NameError: tb = _pytest._code.ExceptionInfo().traceback print (tb[-1].getsource()) s = str(tb[-1].getsource()) assert s.startswith("def xyz():\n try:") assert s.strip().endswith("except somenoname:") def test_traceback_cut(self): co = _pytest._code.Code(f) path, firstlineno = co.path, co.firstlineno traceback = self.excinfo.traceback newtraceback = traceback.cut(path=path, firstlineno=firstlineno) assert len(newtraceback) == 1 newtraceback = traceback.cut(path=path, lineno=firstlineno+2) assert len(newtraceback) == 1 def test_traceback_cut_excludepath(self, testdir): p = testdir.makepyfile("def f(): raise ValueError") excinfo = pytest.raises(ValueError, "p.pyimport().f()") basedir = py.path.local(pytest.__file__).dirpath() newtraceback = excinfo.traceback.cut(excludepath=basedir) for x in newtraceback: if hasattr(x, 'path'): assert not py.path.local(x.path).relto(basedir) assert newtraceback[-1].frame.code.path == p def test_traceback_filter(self): traceback = self.excinfo.traceback ntraceback = traceback.filter() assert len(ntraceback) == len(traceback) - 1 def test_traceback_recursion_index(self): def f(n): if n < 10: n += 1 f(n) excinfo = pytest.raises(RuntimeError, f, 8) traceback = excinfo.traceback recindex = traceback.recursionindex() assert recindex == 3 def test_traceback_only_specific_recursion_errors(self, monkeypatch): def f(n): if n == 0: raise RuntimeError("hello") f(n-1) excinfo = pytest.raises(RuntimeError, f, 100) monkeypatch.delattr(excinfo.traceback.__class__, "recursionindex") repr = excinfo.getrepr() assert "RuntimeError: hello" in str(repr.reprcrash) def test_traceback_no_recursion_index(self): def do_stuff(): raise RuntimeError def reraise_me(): import sys exc, val, tb = sys.exc_info() py.builtin._reraise(exc, val, tb) def f(n): try: do_stuff() except: reraise_me() excinfo = pytest.raises(RuntimeError, f, 8) traceback = excinfo.traceback recindex = traceback.recursionindex() assert recindex is None def test_traceback_messy_recursion(self): #XXX: simplified locally testable version decorator = pytest.importorskip('decorator').decorator def log(f, *k, **kw): print('%s %s' % (k, kw)) f(*k, **kw) log = decorator(log) def fail(): raise ValueError('') fail = log(log(fail)) excinfo = pytest.raises(ValueError, fail) assert excinfo.traceback.recursionindex() is None def test_traceback_getcrashentry(self): def i(): __tracebackhide__ = True raise ValueError def h(): i() def g(): __tracebackhide__ = True h() def f(): g() excinfo = pytest.raises(ValueError, f) tb = excinfo.traceback entry = tb.getcrashentry() co = _pytest._code.Code(h) assert entry.frame.code.path == co.path assert entry.lineno == co.firstlineno + 1 assert entry.frame.code.name == 'h' def test_traceback_getcrashentry_empty(self): def g(): __tracebackhide__ = True raise ValueError def f(): __tracebackhide__ = True g() excinfo = pytest.raises(ValueError, f) tb = excinfo.traceback entry = tb.getcrashentry() co = _pytest._code.Code(g) assert entry.frame.code.path == co.path assert entry.lineno == co.firstlineno + 2 assert entry.frame.code.name == 'g' def hello(x): x + 5 def test_tbentry_reinterpret(): try: hello("hello") except TypeError: excinfo = _pytest._code.ExceptionInfo() tbentry = excinfo.traceback[-1] msg = tbentry.reinterpret() assert msg.startswith("TypeError: ('hello' + 5)") def test_excinfo_exconly(): excinfo = pytest.raises(ValueError, h) assert excinfo.exconly().startswith('ValueError') excinfo = pytest.raises(ValueError, "raise ValueError('hello\\nworld')") msg = excinfo.exconly(tryshort=True) assert msg.startswith('ValueError') assert msg.endswith("world") def test_excinfo_repr(): excinfo = pytest.raises(ValueError, h) s = repr(excinfo) assert s == "<ExceptionInfo ValueError tblen=4>" def test_excinfo_str(): excinfo = pytest.raises(ValueError, h) s = str(excinfo) assert s.startswith(__file__[:-9]) # pyc file and $py.class assert s.endswith("ValueError") assert len(s.split(":")) >= 3 # on windows it's 4 def test_excinfo_errisinstance(): excinfo = pytest.raises(ValueError, h) assert excinfo.errisinstance(ValueError) def test_excinfo_no_sourcecode(): try: exec ("raise ValueError()") except ValueError: excinfo = _pytest._code.ExceptionInfo() s = str(excinfo.traceback[-1]) if py.std.sys.version_info < (2,5): assert s == " File '<string>':1 in ?\n ???\n" else: assert s == " File '<string>':1 in <module>\n ???\n" def test_excinfo_no_python_sourcecode(tmpdir): #XXX: simplified locally testable version tmpdir.join('test.txt').write("{{ h()}}:") jinja2 = pytest.importorskip('jinja2') loader = jinja2.FileSystemLoader(str(tmpdir)) env = jinja2.Environment(loader=loader) template = env.get_template('test.txt') excinfo = pytest.raises(ValueError, template.render, h=h) for item in excinfo.traceback: print(item) #XXX: for some reason jinja.Template.render is printed in full item.source # shouldnt fail if item.path.basename == 'test.txt': assert str(item.source) == '{{ h()}}:' def test_entrysource_Queue_example(): try: queue.Queue().get(timeout=0.001) except queue.Empty: excinfo = _pytest._code.ExceptionInfo() entry = excinfo.traceback[-1] source = entry.getsource() assert source is not None s = str(source).strip() assert s.startswith("def get") def test_codepath_Queue_example(): try: queue.Queue().get(timeout=0.001) except queue.Empty: excinfo = _pytest._code.ExceptionInfo() entry = excinfo.traceback[-1] path = entry.path assert isinstance(path, py.path.local) assert path.basename.lower() == "queue.py" assert path.check() class TestFormattedExcinfo: def pytest_funcarg__importasmod(self, request): def importasmod(source): source = _pytest._code.Source(source) tmpdir = request.getfuncargvalue("tmpdir") modpath = tmpdir.join("mod.py") tmpdir.ensure("__init__.py") modpath.write(source) if invalidate_import_caches is not None: invalidate_import_caches() return modpath.pyimport() return importasmod def excinfo_from_exec(self, source): source = _pytest._code.Source(source).strip() try: exec (source.compile()) except KeyboardInterrupt: raise except: return _pytest._code.ExceptionInfo() assert 0, "did not raise" def test_repr_source(self): pr = FormattedExcinfo() source = _pytest._code.Source(""" def f(x): pass """).strip() pr.flow_marker = "|" lines = pr.get_source(source, 0) assert len(lines) == 2 assert lines[0] == "| def f(x):" assert lines[1] == " pass" def test_repr_source_excinfo(self): """ check if indentation is right """ pr = FormattedExcinfo() excinfo = self.excinfo_from_exec(""" def f(): assert 0 f() """) pr = FormattedExcinfo() source = pr._getentrysource(excinfo.traceback[-1]) lines = pr.get_source(source, 1, excinfo) assert lines == [ ' def f():', '> assert 0', 'E assert 0' ] def test_repr_source_not_existing(self): pr = FormattedExcinfo() co = compile("raise ValueError()", "", "exec") try: exec (co) except ValueError: excinfo = _pytest._code.ExceptionInfo() repr = pr.repr_excinfo(excinfo) assert repr.reprtraceback.reprentries[1].lines[0] == "> ???" def test_repr_many_line_source_not_existing(self): pr = FormattedExcinfo() co = compile(""" a = 1 raise ValueError() """, "", "exec") try: exec (co) except ValueError: excinfo = _pytest._code.ExceptionInfo() repr = pr.repr_excinfo(excinfo) assert repr.reprtraceback.reprentries[1].lines[0] == "> ???" def test_repr_source_failing_fullsource(self): pr = FormattedExcinfo() class FakeCode(object): class raw: co_filename = '?' path = '?' firstlineno = 5 def fullsource(self): return None fullsource = property(fullsource) class FakeFrame(object): code = FakeCode() f_locals = {} f_globals = {} class FakeTracebackEntry(_pytest._code.Traceback.Entry): def __init__(self, tb): self.lineno = 5+3 @property def frame(self): return FakeFrame() class Traceback(_pytest._code.Traceback): Entry = FakeTracebackEntry class FakeExcinfo(_pytest._code.ExceptionInfo): typename = "Foo" def __init__(self): pass def exconly(self, tryshort): return "EXC" def errisinstance(self, cls): return False excinfo = FakeExcinfo() class FakeRawTB(object): tb_next = None tb = FakeRawTB() excinfo.traceback = Traceback(tb) fail = IOError() # noqa repr = pr.repr_excinfo(excinfo) assert repr.reprtraceback.reprentries[0].lines[0] == "> ???" fail = py.error.ENOENT # noqa repr = pr.repr_excinfo(excinfo) assert repr.reprtraceback.reprentries[0].lines[0] == "> ???" def test_repr_local(self): p = FormattedExcinfo(showlocals=True) loc = {'y': 5, 'z': 7, 'x': 3, '@x': 2, '__builtins__': {}} reprlocals = p.repr_locals(loc) assert reprlocals.lines assert reprlocals.lines[0] == '__builtins__ = <builtins>' assert reprlocals.lines[1] == 'x = 3' assert reprlocals.lines[2] == 'y = 5' assert reprlocals.lines[3] == 'z = 7' def test_repr_tracebackentry_lines(self, importasmod): mod = importasmod(""" def func1(): raise ValueError("hello\\nworld") """) excinfo = pytest.raises(ValueError, mod.func1) excinfo.traceback = excinfo.traceback.filter() p = FormattedExcinfo() reprtb = p.repr_traceback_entry(excinfo.traceback[-1]) # test as intermittent entry lines = reprtb.lines assert lines[0] == ' def func1():' assert lines[1] == '> raise ValueError("hello\\nworld")' # test as last entry p = FormattedExcinfo(showlocals=True) repr_entry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo) lines = repr_entry.lines assert lines[0] == ' def func1():' assert lines[1] == '> raise ValueError("hello\\nworld")' assert lines[2] == 'E ValueError: hello' assert lines[3] == 'E world' assert not lines[4:] loc = repr_entry.reprlocals is not None loc = repr_entry.reprfileloc assert loc.path == mod.__file__ assert loc.lineno == 3 #assert loc.message == "ValueError: hello" def test_repr_tracebackentry_lines2(self, importasmod): mod = importasmod(""" def func1(m, x, y, z): raise ValueError("hello\\nworld") """) excinfo = pytest.raises(ValueError, mod.func1, "m"*90, 5, 13, "z"*120) excinfo.traceback = excinfo.traceback.filter() entry = excinfo.traceback[-1] p = FormattedExcinfo(funcargs=True) reprfuncargs = p.repr_args(entry) assert reprfuncargs.args[0] == ('m', repr("m"*90)) assert reprfuncargs.args[1] == ('x', '5') assert reprfuncargs.args[2] == ('y', '13') assert reprfuncargs.args[3] == ('z', repr("z" * 120)) p = FormattedExcinfo(funcargs=True) repr_entry = p.repr_traceback_entry(entry) assert repr_entry.reprfuncargs.args == reprfuncargs.args tw = TWMock() repr_entry.toterminal(tw) assert tw.lines[0] == "m = " + repr('m' * 90) assert tw.lines[1] == "x = 5, y = 13" assert tw.lines[2] == "z = " + repr('z' * 120) def test_repr_tracebackentry_lines_var_kw_args(self, importasmod): mod = importasmod(""" def func1(x, *y, **z): raise ValueError("hello\\nworld") """) excinfo = pytest.raises(ValueError, mod.func1, 'a', 'b', c='d') excinfo.traceback = excinfo.traceback.filter() entry = excinfo.traceback[-1] p = FormattedExcinfo(funcargs=True) reprfuncargs = p.repr_args(entry) assert reprfuncargs.args[0] == ('x', repr('a')) assert reprfuncargs.args[1] == ('y', repr(('b',))) assert reprfuncargs.args[2] == ('z', repr({'c': 'd'})) p = FormattedExcinfo(funcargs=True) repr_entry = p.repr_traceback_entry(entry) assert repr_entry.reprfuncargs.args == reprfuncargs.args tw = TWMock() repr_entry.toterminal(tw) assert tw.lines[0] == "x = 'a', y = ('b',), z = {'c': 'd'}" def test_repr_tracebackentry_short(self, importasmod): mod = importasmod(""" def func1(): raise ValueError("hello") def entry(): func1() """) excinfo = pytest.raises(ValueError, mod.entry) p = FormattedExcinfo(style="short") reprtb = p.repr_traceback_entry(excinfo.traceback[-2]) lines = reprtb.lines basename = py.path.local(mod.__file__).basename assert lines[0] == ' func1()' assert basename in str(reprtb.reprfileloc.path) assert reprtb.reprfileloc.lineno == 5 # test last entry p = FormattedExcinfo(style="short") reprtb = p.repr_traceback_entry(excinfo.traceback[-1], excinfo) lines = reprtb.lines assert lines[0] == ' raise ValueError("hello")' assert lines[1] == 'E ValueError: hello' assert basename in str(reprtb.reprfileloc.path) assert reprtb.reprfileloc.lineno == 3 def test_repr_tracebackentry_no(self, importasmod): mod = importasmod(""" def func1(): raise ValueError("hello") def entry(): func1() """) excinfo = pytest.raises(ValueError, mod.entry) p = FormattedExcinfo(style="no") p.repr_traceback_entry(excinfo.traceback[-2]) p = FormattedExcinfo(style="no") reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo) lines = reprentry.lines assert lines[0] == 'E ValueError: hello' assert not lines[1:] def test_repr_traceback_tbfilter(self, importasmod): mod = importasmod(""" def f(x): raise ValueError(x) def entry(): f(0) """) excinfo = pytest.raises(ValueError, mod.entry) p = FormattedExcinfo(tbfilter=True) reprtb = p.repr_traceback(excinfo) assert len(reprtb.reprentries) == 2 p = FormattedExcinfo(tbfilter=False) reprtb = p.repr_traceback(excinfo) assert len(reprtb.reprentries) == 3 def test_traceback_short_no_source(self, importasmod, monkeypatch): mod = importasmod(""" def func1(): raise ValueError("hello") def entry(): func1() """) excinfo = pytest.raises(ValueError, mod.entry) from _pytest._code.code import Code monkeypatch.setattr(Code, 'path', 'bogus') excinfo.traceback[0].frame.code.path = "bogus" p = FormattedExcinfo(style="short") reprtb = p.repr_traceback_entry(excinfo.traceback[-2]) lines = reprtb.lines last_p = FormattedExcinfo(style="short") last_reprtb = last_p.repr_traceback_entry(excinfo.traceback[-1], excinfo) last_lines = last_reprtb.lines monkeypatch.undo() assert lines[0] == ' func1()' assert last_lines[0] == ' raise ValueError("hello")' assert last_lines[1] == 'E ValueError: hello' def test_repr_traceback_and_excinfo(self, importasmod): mod = importasmod(""" def f(x): raise ValueError(x) def entry(): f(0) """) excinfo = pytest.raises(ValueError, mod.entry) for style in ("long", "short"): p = FormattedExcinfo(style=style) reprtb = p.repr_traceback(excinfo) assert len(reprtb.reprentries) == 2 assert reprtb.style == style assert not reprtb.extraline repr = p.repr_excinfo(excinfo) assert repr.reprtraceback assert len(repr.reprtraceback.reprentries) == len(reprtb.reprentries) assert repr.reprcrash.path.endswith("mod.py") assert repr.reprcrash.message == "ValueError: 0" def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch): mod = importasmod(""" def f(x): raise ValueError(x) def entry(): f(0) """) excinfo = pytest.raises(ValueError, mod.entry) p = FormattedExcinfo() def raiseos(): raise OSError(2) monkeypatch.setattr(py.std.os, 'getcwd', raiseos) assert p._makepath(__file__) == __file__ p.repr_traceback(excinfo) def test_repr_excinfo_addouterr(self, importasmod): mod = importasmod(""" def entry(): raise ValueError() """) excinfo = pytest.raises(ValueError, mod.entry) repr = excinfo.getrepr() repr.addsection("title", "content") twmock = TWMock() repr.toterminal(twmock) assert twmock.lines[-1] == "content" assert twmock.lines[-2] == ("-", "title") def test_repr_excinfo_reprcrash(self, importasmod): mod = importasmod(""" def entry(): raise ValueError() """) excinfo = pytest.raises(ValueError, mod.entry) repr = excinfo.getrepr() assert repr.reprcrash.path.endswith("mod.py") assert repr.reprcrash.lineno == 3 assert repr.reprcrash.message == "ValueError" assert str(repr.reprcrash).endswith("mod.py:3: ValueError") def test_repr_traceback_recursion(self, importasmod): mod = importasmod(""" def rec2(x): return rec1(x+1) def rec1(x): return rec2(x-1) def entry(): rec1(42) """) excinfo = pytest.raises(RuntimeError, mod.entry) for style in ("short", "long", "no"): p = FormattedExcinfo(style="short") reprtb = p.repr_traceback(excinfo) assert reprtb.extraline == "!!! Recursion detected (same locals & position)" assert str(reprtb) def test_tb_entry_AssertionError(self, importasmod): # probably this test is a bit redundant # as py/magic/testing/test_assertion.py # already tests correctness of # assertion-reinterpretation logic mod = importasmod(""" def somefunc(): x = 1 assert x == 2 """) excinfo = pytest.raises(AssertionError, mod.somefunc) p = FormattedExcinfo() reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo) lines = reprentry.lines assert lines[-1] == "E assert 1 == 2" def test_reprexcinfo_getrepr(self, importasmod): mod = importasmod(""" def f(x): raise ValueError(x) def entry(): f(0) """) excinfo = pytest.raises(ValueError, mod.entry) for style in ("short", "long", "no"): for showlocals in (True, False): repr = excinfo.getrepr(style=style, showlocals=showlocals) assert isinstance(repr, ReprExceptionInfo) assert repr.reprtraceback.style == style def test_reprexcinfo_unicode(self): from _pytest._code.code import TerminalRepr class MyRepr(TerminalRepr): def toterminal(self, tw): tw.line(py.builtin._totext("я", "utf-8")) x = py.builtin._totext(MyRepr()) assert x == py.builtin._totext("я", "utf-8") def test_toterminal_long(self, importasmod): mod = importasmod(""" def g(x): raise ValueError(x) def f(): g(3) """) excinfo = pytest.raises(ValueError, mod.f) excinfo.traceback = excinfo.traceback.filter() repr = excinfo.getrepr() tw = TWMock() repr.toterminal(tw) assert tw.lines[0] == "" tw.lines.pop(0) assert tw.lines[0] == " def f():" assert tw.lines[1] == "> g(3)" assert tw.lines[2] == "" assert tw.lines[3].endswith("mod.py:5: ") assert tw.lines[4] == ("_ ", None) assert tw.lines[5] == "" assert tw.lines[6] == " def g(x):" assert tw.lines[7] == "> raise ValueError(x)" assert tw.lines[8] == "E ValueError: 3" assert tw.lines[9] == "" assert tw.lines[10].endswith("mod.py:3: ValueError") def test_toterminal_long_missing_source(self, importasmod, tmpdir): mod = importasmod(""" def g(x): raise ValueError(x) def f(): g(3) """) excinfo = pytest.raises(ValueError, mod.f) tmpdir.join('mod.py').remove() excinfo.traceback = excinfo.traceback.filter() repr = excinfo.getrepr() tw = TWMock() repr.toterminal(tw) assert tw.lines[0] == "" tw.lines.pop(0) assert tw.lines[0] == "> ???" assert tw.lines[1] == "" assert tw.lines[2].endswith("mod.py:5: ") assert tw.lines[3] == ("_ ", None) assert tw.lines[4] == "" assert tw.lines[5] == "> ???" assert tw.lines[6] == "E ValueError: 3" assert tw.lines[7] == "" assert tw.lines[8].endswith("mod.py:3: ValueError") def test_toterminal_long_incomplete_source(self, importasmod, tmpdir): mod = importasmod(""" def g(x): raise ValueError(x) def f(): g(3) """) excinfo = pytest.raises(ValueError, mod.f) tmpdir.join('mod.py').write('asdf') excinfo.traceback = excinfo.traceback.filter() repr = excinfo.getrepr() tw = TWMock() repr.toterminal(tw) assert tw.lines[0] == "" tw.lines.pop(0) assert tw.lines[0] == "> ???" assert tw.lines[1] == "" assert tw.lines[2].endswith("mod.py:5: ") assert tw.lines[3] == ("_ ", None) assert tw.lines[4] == "" assert tw.lines[5] == "> ???" assert tw.lines[6] == "E ValueError: 3" assert tw.lines[7] == "" assert tw.lines[8].endswith("mod.py:3: ValueError") def test_toterminal_long_filenames(self, importasmod): mod = importasmod(""" def f(): raise ValueError() """) excinfo = pytest.raises(ValueError, mod.f) tw = TWMock() path = py.path.local(mod.__file__) old = path.dirpath().chdir() try: repr = excinfo.getrepr(abspath=False) repr.toterminal(tw) line = tw.lines[-1] x = py.path.local().bestrelpath(path) if len(x) < len(str(path)): assert line == "mod.py:3: ValueError" repr = excinfo.getrepr(abspath=True) repr.toterminal(tw) line = tw.lines[-1] assert line == "%s:3: ValueError" %(path,) finally: old.chdir() @pytest.mark.parametrize('reproptions', [ {'style': style, 'showlocals': showlocals, 'funcargs': funcargs, 'tbfilter': tbfilter } for style in ("long", "short", "no") for showlocals in (True, False) for tbfilter in (True, False) for funcargs in (True, False)]) def test_format_excinfo(self, importasmod, reproptions): mod = importasmod(""" def g(x): raise ValueError(x) def f(): g(3) """) excinfo = pytest.raises(ValueError, mod.f) tw = py.io.TerminalWriter(stringio=True) repr = excinfo.getrepr(**reproptions) repr.toterminal(tw) assert tw.stringio.getvalue() def test_native_style(self): excinfo = self.excinfo_from_exec(""" assert 0 """) repr = excinfo.getrepr(style='native') assert "assert 0" in str(repr.reprcrash) s = str(repr) assert s.startswith('Traceback (most recent call last):\n File') assert s.endswith('\nAssertionError: assert 0') assert 'exec (source.compile())' in s # python 2.4 fails to get the source line for the assert if py.std.sys.version_info >= (2, 5): assert s.count('assert 0') == 2 def test_traceback_repr_style(self, importasmod): mod = importasmod(""" def f(): g() def g(): h() def h(): i() def i(): raise ValueError() """) excinfo = pytest.raises(ValueError, mod.f) excinfo.traceback = excinfo.traceback.filter() excinfo.traceback[1].set_repr_style("short") excinfo.traceback[2].set_repr_style("short") r = excinfo.getrepr(style="long") tw = TWMock() r.toterminal(tw) for line in tw.lines: print (line) assert tw.lines[0] == "" assert tw.lines[1] == " def f():" assert tw.lines[2] == "> g()" assert tw.lines[3] == "" assert tw.lines[4].endswith("mod.py:3: ") assert tw.lines[5] == ("_ ", None) assert tw.lines[6].endswith("in g") assert tw.lines[7] == " h()" assert tw.lines[8].endswith("in h") assert tw.lines[9] == " i()" assert tw.lines[10] == ("_ ", None) assert tw.lines[11] == "" assert tw.lines[12] == " def i():" assert tw.lines[13] == "> raise ValueError()" assert tw.lines[14] == "E ValueError" assert tw.lines[15] == "" assert tw.lines[16].endswith("mod.py:9: ValueError")
mpl-2.0
madPO/cod4
votePlugin.py
1
8741
# # votePlugin for BigBrotherBot(B3) (www.bigbrotherbot.net) # Copyright (C) 2013 Simon "madPO" Zor'kin # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # Changelog: # # __author__ = 'madPO' __version__ = '27.08.13' import b3 import b3.events import b3.plugin import re import time class VotepluginPlugin(b3.plugin.Plugin): requiresConfigFile = True _commands = {} _adminPlugin = None _voteState = 'off' _voteTarget = '' _playerToVote = None _voteIniter = '' _votedList = [] _numYes = 0 _numNo = 0 _voteTime = 45 _countdown = 0 _minVotes = 0 _minVoteRatio = 2 _mapList = [] _voteTimeAlowed = 45 _voteAlowed = False _voteK = 0 def getCmd(self, cmd): cmd = 'cmd_%s' % cmd if hasattr(self, cmd): func = getattr(self, cmd) return func return None def onLoadConfig(self): # load our settings self.verbose('Loading config <Started> ...') self._voteTime = self.config.getint('settings','voteTime') self._minVoteRatio = self.config.getint('settings','minVoteRatio') self._voteTimeAlowed = self.config.getint('settings','votetimestart') for e in self.config.get('maps/map'): self._mapList.append(e.text) self.verbose('Loading config <Stoped>.') def onStartup(self): """\ Initialize plugin settings """ # get the admin plugin so we can register commands self.registerEvent(b3.events.EVT_GAME_MAP_CHANGE) self._adminPlugin = self.console.getPlugin('admin') self.verbose('Loading admin plugin') if not self._adminPlugin: # something is wrong, can't start without admin plugin self.error('Could not find admin plugin') return False self.verbose('Loading commans...') #register our commands\ if 'commands' in self.config.sections(): for cmd in self.config.options('commands'): level = self.config.get('commands', cmd) sp = cmd.split('-') alias = None if len(sp) == 2: cmd, alias = sp func = self.getCmd(cmd) if func: self._adminPlugin.registerCommand(self, cmd, level, func, alias) self.verbose('votePlugin start!!!') def onEvent(self, event): if event.type == b3.events.EVT_GAME_MAP_CHANGE: self.resetVotes() self._voteAlowed = True self.verbose('Start vote') time.sleep(5) self.console.cron + b3.cron.OneTimeCronTab(self.startVote, '*/%d'%(self._voteTimeAlowed)) #cmd !maplist def cmd_maplist(self, data, client, cmd=None): cmd.sayLoudOrPM(client,"Maps available for voting: " + ", ".join(self._mapList)) def resetVotes(self): self._voteState = "off" self._voteTarget = "" self._playerToVote = None self._voteIniter = "" self._voteReason = "" self._votedList = [] self._numYes = 0 self._numNo = 0 self._countdown = -1 self.console.write("b3_message ^7") def startVote(self): if self._voteAlowed != False: self.console.say('^2Voting is open in the next %d seconds'%(self._voteTimeAlowed*2)) time.sleep(5) self.console.say('^2Use !votemap mp_name') self.console.cron + b3.cron.OneTimeCronTab(self.stopVote, '*/%d'%(self._voteTimeAlowed)) def stopVote(self): if self._voteAlowed != False: self.console.say('^2Voting is closed') self._voteAlowed = False self.verbose('Stop vote') self.console.cron + b3.cron.OneTimeCronTab(self.stopVote, "") def resolveVote(self): if self._numYes >= self._minVotes: self.console.say('^2Vote passed') time.sleep(1) if self._voteState == "Map": self.console.say('^2Changing map to %s'%self._voteTarget) time.sleep(3) self.console.write("b3_message ^7") self.console.write('map %s'%self._voteTarget) self.resetVotes() else: self.console.say('^2Vote failed. Yes:(^2%d^2) No:(^1%d^2)'%(self._numYes,self._numNo)) self.resetVotes() def minVotes(self): return len(self.console.clients.getList())/self._minVoteRatio + 1 #cmd !yes def cmd_voteyes(self, data, client=None, cmd=None): if self._voteState == "off": cmd.sayLoudOrPM(client, '^7Voting impossible') else: if client not in self._votedList: self._numYes += 1 self._votedList.append(client) client.message('^7 You have voted ^2yes') else: client.message('^7 You have already voted') #cmd !no def cmd_voteno(self, data, client=None, cmd=None): if self._voteState == "off": cmd.sayLoudOrPM(client, '^7Voting impossible') else: if client not in self._votedList: self._numNo += 1 self._votedList.append(client) client.message('^7 You have voted ^1no') else: client.message('^7 You have already voted') def updateCountdown(self): self.console.write('b3_message ^7%s vote for %s ending in %d (%d/%d)'%(self._voteState, self._voteTarget,self._countdown,self._numYes,self._minVotes)) self._countdown -= 1 if self._countdown >= 0 and self._numYes < self._minVotes: self.console.cron + b3.cron.OneTimeCronTab(self.updateCountdown, "*/1") else: self.resolveVote() #cmd !veto def cmd_veto(self, data, client=None, cmd=None): """ <veto> - Veto the current vote """ if self._voteState == "off": cmd.sayLoudOrPM(client, '^7Voting impossible') else: self.console.say('^2Administrator vetoes vote') self.resetVotes() #cmd !votestatus def cmd_votestatus(self, data, client=None, cmd=None): if self._voteState == "off": cmd.sayLoudOrPM(client, '^7No vote in session') else: cmd.sayLoudOrPM(client, '^7Current votes ^2yes^7:%d of %d,^1no^7:%d'%(self._numYes, self._minVotes, self._numNo)) #cmd !votemap def cmd_votemap(self, data, client=None, cmd=None): """\ <map> - Map to vote on """ if self._voteAlowed == False: client.message('^7Voting impossible') else: if self._voteState != "off": client.message('^2Vote is already in session') return True m = self._adminPlugin.parseUserCmd(data) if not m: client.message('^7Invalid parameters, you must supply a map') return False elif m[0] not in self._mapList: client.message('^7%s is an invalid map'%m[0]) time.sleep(1) client.message('^7Use !maplist') return False else: self._voteTarget = m[0] self._voteState = "Map" self._countdown = self._voteTime self._minVotes = self.minVotes() self.console.say('^2Map voting for %s has commenced'%self._voteTarget) time.sleep(0.2) self.console.say('^2%s votes needed to pass'%self._minVotes) time.sleep(0.2) self.console.say('^2Type !yes or !no to vote') self.updateCountdown() return True #cmd !maprestart def cmd_maprestart(self, data, client, cmd=None): """\ Restart the current map. """ self.console.say('^2Fast restart will be executed') time.sleep(5) self.console.write('fast_restart') return True
gpl-2.0
aaronkaplan/intelmq-beta
intelmq/bots/parsers/malwaredomainlist__/parser.py
1
1774
import unicodecsv from cStringIO import StringIO from intelmq.lib.bot import Bot, sys from intelmq.lib.message import Event from intelmq.lib.harmonization import DateTime from intelmq.bots import utils class MalwareDomainListParserBot(Bot): def process(self): report = self.receive_message() if not report.contains("raw"): self.acknowledge_message() columns = [ "time.source", "source.url", "source.ip", "source.reverse_domain_name", "malware.name", "__IGNORE__", "source.asn" ] for row in unicodecsv.reader(StringIO(report.value("raw")), encoding='utf-8'): event = Event() for key, value in zip(columns, row): if key is "__IGNORE__": continue if key is "time.source": value = value.replace('_',' ') value += " UTC" event.add(key, value, sanitize=True) time_observation = DateTime().generate_datetime_now() event.add('time.observation', time_observation, sanitize=True) event.add("raw", ",".join(row), sanitize=True) event.add('feed.name', u'malwaredomainslist') event.add('feed.url', u'http://www.malwaredomainlist.com/updatescsv.php') event.add('classification.type', u'malware') # FIXME self.send_message(event) self.acknowledge_message() if __name__ == "__main__": bot = MalwareDomainListParserBot(sys.argv[1]) bot.start()
agpl-3.0
Werkov/PyQt4
contrib/lang/lang.py
17
5333
#!/usr/bin/env python # switch translations dynamically in a PyQt4 application # # PyQt version by Hans-Peter Jansen <[email protected]> # # Based on an example from jpn on July 17 2006 found here: # # http://www.qtcentre.org/wiki/index.php?title=Dynamic_translation_in_Qt4_applications # # Since the original version didn't carry any license, # I've add this one: # # This program is free software. It comes without any warranty, to # the extent permitted by applicable law. You can redistribute it # and/or modify it under the terms of the Do What The Fuck You Want # To Public License, Version 2, as published by Sam Hocevar. See # http://sam.zoy.org/wtfpl/COPYING for more details. import sys import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) from PyQt4 import QtCore, QtGui from ui_mainwindow import Ui_MainWindow import lang_rc class Application(QtGui.QApplication): translators = {} current = None def __init__(self, argv): super(Application, self).__init__(argv) def loadTranslations(self, folder): if not isinstance(folder, QtCore.QDir): folder = QtCore.QDir(folder) pattern = "*_*.qm" # <language>_<country>.qm filters = QtCore.QDir.Files | QtCore.QDir.Readable sort = QtCore.QDir.SortFlags(QtCore.QDir.Name) for langFile in folder.entryInfoList([pattern], filters, sort): # pick country and language out of the file name language, country = langFile.baseName().split("_", 1) language = language.lower() country = country.upper() locale = language + "_" + country # only load translation, if it does not exist already if not locale in Application.translators: # create and load translator translator = QtCore.QTranslator(self.instance()) if translator.load(langFile.absoluteFilePath()): Application.translators[locale] = translator @staticmethod def availableLanguages(): return sorted(Application.translators.keys()) @staticmethod def setLanguage(locale): #print "Application.setLanguage(%s)" % locale if Application.current: Application.removeTranslator(Application.current) Application.current = Application.translators.get(locale, None) if Application.current is not None: Application.installTranslator(Application.current) class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None, flags = 0): super(MainWindow, self).__init__(parent, QtCore.Qt.WindowFlags(flags)) self.languages = QtGui.QMenu() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.fillLanguages() self.retranslate() def changeEvent(self, event): if event.type() == QtCore.QEvent.LanguageChange: # all designed forms have a retranslateUi() method self.ui.retranslateUi(self) # retranslate other widgets which weren't added in the designer self.retranslate() super(MainWindow, self).changeEvent(event) @QtCore.pyqtSlot(QtGui.QAction) def setLanguage(self, action): Application.setLanguage(action.data()) def fillLanguages(self): self.languages = self.menuBar().addMenu("") # make a group of language actions actions = QtGui.QActionGroup(self) actions.triggered.connect(self.setLanguage) system = QtCore.QLocale.system() default = None for lang in Application.availableLanguages(): # figure out nice names for locales locale = QtCore.QLocale(lang) language = QtCore.QLocale.languageToString(locale.language()) country = QtCore.QLocale.countryToString(locale.country()) name = "%s (%s)" % (language, country) # create an action action = self.languages.addAction(name) action.setData(lang) action.setCheckable(True) if lang == system.name(): # language match the current system action.setChecked(True) Application.setLanguage(lang) default = lang actions.addAction(action) if default is None: # no exact match found, try language only for lang in Application.availableLanguages(): locale = QtCore.QLocale(lang) if locale.language() == system.language(): # at least a language match for action in actions.actions(): if lang == action.data(): # use first entry of this language action.setChecked(True) Application.setLanguage(lang) default = lang break if default is not None: break return default def retranslate(self): self.languages.setTitle(self.tr("Language")) if __name__ == "__main__": app = Application(sys.argv) app.loadTranslations(":/lang") mainWindow = MainWindow() mainWindow.show() app.lastWindowClosed.connect(app.quit) sys.exit(app.exec_())
gpl-2.0
pkappesser/youtube-dl
youtube_dl/extractor/m6.py
147
1952
# encoding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor class M6IE(InfoExtractor): IE_NAME = 'm6' _VALID_URL = r'http://(?:www\.)?m6\.fr/[^/]+/videos/(?P<id>\d+)-[^\.]+\.html' _TEST = { 'url': 'http://www.m6.fr/emission-les_reines_du_shopping/videos/11323908-emeline_est_la_reine_du_shopping_sur_le_theme_ma_fete_d_8217_anniversaire.html', 'md5': '242994a87de2c316891428e0176bcb77', 'info_dict': { 'id': '11323908', 'ext': 'mp4', 'title': 'Emeline est la Reine du Shopping sur le thème « Ma fête d’anniversaire ! »', 'description': 'md5:1212ae8fb4b7baa4dc3886c5676007c2', 'duration': 100, } } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') rss = self._download_xml('http://ws.m6.fr/v1/video/info/m6/bonus/%s' % video_id, video_id, 'Downloading video RSS') title = rss.find('./channel/item/title').text description = rss.find('./channel/item/description').text thumbnail = rss.find('./channel/item/visuel_clip_big').text duration = int(rss.find('./channel/item/duration').text) view_count = int(rss.find('./channel/item/nombre_vues').text) formats = [] for format_id in ['lq', 'sd', 'hq', 'hd']: video_url = rss.find('./channel/item/url_video_%s' % format_id) if video_url is None: continue formats.append({ 'url': video_url.text, 'format_id': format_id, }) return { 'id': video_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'duration': duration, 'view_count': view_count, 'formats': formats, }
unlicense
DavidNorman/tensorflow
tensorflow/python/ops/distributions/bernoulli.py
17
7105
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The Bernoulli distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.ops import random_ops from tensorflow.python.ops.distributions import distribution from tensorflow.python.ops.distributions import kullback_leibler from tensorflow.python.ops.distributions import util as distribution_util from tensorflow.python.util import deprecation from tensorflow.python.util.tf_export import tf_export @tf_export(v1=["distributions.Bernoulli"]) class Bernoulli(distribution.Distribution): """Bernoulli distribution. The Bernoulli distribution with `probs` parameter, i.e., the probability of a `1` outcome (vs a `0` outcome). """ @deprecation.deprecated( "2019-01-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.distributions`.", warn_once=True) def __init__(self, logits=None, probs=None, dtype=dtypes.int32, validate_args=False, allow_nan_stats=True, name="Bernoulli"): """Construct Bernoulli distributions. Args: logits: An N-D `Tensor` representing the log-odds of a `1` event. Each entry in the `Tensor` parametrizes an independent Bernoulli distribution where the probability of an event is sigmoid(logits). Only one of `logits` or `probs` should be passed in. probs: An N-D `Tensor` representing the probability of a `1` event. Each entry in the `Tensor` parameterizes an independent Bernoulli distribution. Only one of `logits` or `probs` should be passed in. dtype: The type of the event samples. Default: `int32`. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Raises: ValueError: If p and logits are passed, or if neither are passed. """ parameters = dict(locals()) with ops.name_scope(name) as name: self._logits, self._probs = distribution_util.get_logits_and_probs( logits=logits, probs=probs, validate_args=validate_args, name=name) super(Bernoulli, self).__init__( dtype=dtype, reparameterization_type=distribution.NOT_REPARAMETERIZED, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, graph_parents=[self._logits, self._probs], name=name) @staticmethod def _param_shapes(sample_shape): return {"logits": ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)} @property def logits(self): """Log-odds of a `1` outcome (vs `0`).""" return self._logits @property def probs(self): """Probability of a `1` outcome (vs `0`).""" return self._probs def _batch_shape_tensor(self): return array_ops.shape(self._logits) def _batch_shape(self): return self._logits.get_shape() def _event_shape_tensor(self): return array_ops.constant([], dtype=dtypes.int32) def _event_shape(self): return tensor_shape.TensorShape([]) def _sample_n(self, n, seed=None): new_shape = array_ops.concat([[n], self.batch_shape_tensor()], 0) uniform = random_ops.random_uniform( new_shape, seed=seed, dtype=self.probs.dtype) sample = math_ops.less(uniform, self.probs) return math_ops.cast(sample, self.dtype) def _log_prob(self, event): if self.validate_args: event = distribution_util.embed_check_integer_casting_closed( event, target_dtype=dtypes.bool) # TODO(jaana): The current sigmoid_cross_entropy_with_logits has # inconsistent behavior for logits = inf/-inf. event = math_ops.cast(event, self.logits.dtype) logits = self.logits # sigmoid_cross_entropy_with_logits doesn't broadcast shape, # so we do this here. def _broadcast(logits, event): return (array_ops.ones_like(event) * logits, array_ops.ones_like(logits) * event) if not (event.get_shape().is_fully_defined() and logits.get_shape().is_fully_defined() and event.get_shape() == logits.get_shape()): logits, event = _broadcast(logits, event) return -nn.sigmoid_cross_entropy_with_logits(labels=event, logits=logits) def _entropy(self): return (-self.logits * (math_ops.sigmoid(self.logits) - 1) + nn.softplus(-self.logits)) def _mean(self): return array_ops.identity(self.probs) def _variance(self): return self._mean() * (1. - self.probs) def _mode(self): """Returns `1` if `prob > 0.5` and `0` otherwise.""" return math_ops.cast(self.probs > 0.5, self.dtype) @kullback_leibler.RegisterKL(Bernoulli, Bernoulli) def _kl_bernoulli_bernoulli(a, b, name=None): """Calculate the batched KL divergence KL(a || b) with a and b Bernoulli. Args: a: instance of a Bernoulli distribution object. b: instance of a Bernoulli distribution object. name: (optional) Name to use for created operations. default is "kl_bernoulli_bernoulli". Returns: Batchwise KL(a || b) """ with ops.name_scope(name, "kl_bernoulli_bernoulli", values=[a.logits, b.logits]): delta_probs0 = nn.softplus(-b.logits) - nn.softplus(-a.logits) delta_probs1 = nn.softplus(b.logits) - nn.softplus(a.logits) return (math_ops.sigmoid(a.logits) * delta_probs0 + math_ops.sigmoid(-a.logits) * delta_probs1)
apache-2.0
kinsamanka/machinekit
src/emc/usr_intf/stepconf/build_HAL.py
8
29367
#!/usr/bin/env python # # This is stepconf, a graphical configuration editor for LinuxCNC # Copyright 2007 Jeff Epler <[email protected]> # stepconf 1.1 revamped by Chris Morley 2014 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # This builds the HAL files from the collected data. # import os import time import shutil class HAL: def __init__(self,app): # access to: self.d = app.d # collected data global SIG SIG = app._p # private data (signal names) self.a = app # The parent, stepconf def write_halfile(self, base): inputs = self.a.build_input_set() outputs = self.a.build_output_set() filename = os.path.join(base, self.d.machinename + ".hal") file = open(filename, "w") print >>file, _("# Generated by stepconf 1.1 at %s") % time.asctime() print >>file, _("# If you make changes to this file, they will be") print >>file, _("# overwritten when you run stepconf again") print >>file, "loadrt trivkins" print >>file, "loadrt tp" print >>file, "loadrt [EMCMOT]EMCMOT base_period_nsec=[EMCMOT]BASE_PERIOD servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[TRAJ]AXES kins=trivkins tp=tp" port3name=port2name=port2dir=port3dir="" if self.d.number_pports>2: port3name = ' '+self.d.ioaddr3 if self.d.pp3_direction: # Input option port3dir =" in" else: port3dir =" out" if self.d.number_pports>1: port2name = ' '+self.d.ioaddr2 if self.d.pp2_direction: # Input option port2dir =" in" else: port2dir =" out" if not self.d.sim_hardware: print >>file, "loadrt hal_parport cfg=\"%s out%s%s%s%s\"" % (self.d.ioaddr, port2name, port2dir, port3name, port3dir) else: name='parport.0' if self.d.number_pports>1: name='parport.0,parport.1' print >>file, "loadrt sim_parport names=%s"%name if self.a.doublestep(): print >>file, "setp parport.0.reset-time %d" % self.d.steptime encoder = SIG.PHA in inputs counter = SIG.PHB not in inputs probe = SIG.PROBE in inputs limits_homes = SIG.ALL_LIMIT_HOME in inputs pwm = SIG.PWM in outputs pump = SIG.PUMP in outputs if self.d.axes == 2: print >>file, "loadrt stepgen step_type=0,0" elif self.d.axes == 1: print >>file, "loadrt stepgen step_type=0,0,0,0" else: print >>file, "loadrt stepgen step_type=0,0,0" if encoder: print >>file, "loadrt encoder num_chan=1" if self.d.pyvcphaltype == 1 and self.d.pyvcpconnect == 1: if encoder: print >>file, "loadrt abs count=1" print >>file, "loadrt scale count=1" print >>file, "loadrt lowpass count=1" if self.d.usespindleatspeed: print >>file, "loadrt near" if pump: print >>file, "loadrt charge_pump" print >>file, "net estop-out charge-pump.enable iocontrol.0.user-enable-out" print >>file, "net charge-pump <= charge-pump.out" if limits_homes: print >>file, "loadrt lut5" if pwm: print >>file, "loadrt pwmgen output_type=1" if self.d.classicladder: print >>file, "loadrt classicladder_rt numPhysInputs=%d numPhysOutputs=%d numS32in=%d numS32out=%d numFloatIn=%d numFloatOut=%d" % (self.d.digitsin , self.d.digitsout , self.d.s32in, self.d.s32out, self.d.floatsin, self.d.floatsout) print >>file print >>file, "addf parport.0.read base-thread" if self.d.number_pports > 1: print >>file, "addf parport.1.read base-thread" if self.d.number_pports > 2: print >>file, "addf parport.2.read base-thread" if self.d.sim_hardware: print >>file, "source sim_hardware.hal" if encoder: print >>file, "addf sim-encoder.make-pulses base-thread" print >>file, "addf stepgen.make-pulses base-thread" if encoder: print >>file, "addf encoder.update-counters base-thread" if pump: print >>file, "addf charge-pump base-thread" if pwm: print >>file, "addf pwmgen.make-pulses base-thread" print >>file, "addf parport.0.write base-thread" if self.a.doublestep(): print >>file, "addf parport.0.reset base-thread" if self.d.number_pports > 1: print >>file, "addf parport.1.write base-thread" if self.d.number_pports > 2: print >>file, "addf parport.2.write base-thread" print >>file print >>file, "addf stepgen.capture-position servo-thread" if self.d.sim_hardware: if encoder: print >>file, "addf sim-encoder.update-speed servo-thread" print >>file, "addf sim-hardware.update servo-thread" if encoder: print >>file, "addf encoder.capture-position servo-thread" print >>file, "addf motion-command-handler servo-thread" print >>file, "addf motion-controller servo-thread" if self.d.classicladder: print >>file,"addf classicladder.0.refresh servo-thread" print >>file, "addf stepgen.update-freq servo-thread" if limits_homes: print >>file, "addf lut5.0 servo-thread" if pwm: print >>file, "addf pwmgen.update servo-thread" if self.d.pyvcphaltype == 1 and self.d.pyvcpconnect == 1: if encoder: print >>file, "addf abs.0 servo-thread" print >>file, "addf scale.0 servo-thread" print >>file, "addf lowpass.0 servo-thread" if self.d.usespindleatspeed: print >>file, "addf near.0 servo-thread" if pwm: x1 = self.d.spindlepwm1 x2 = self.d.spindlepwm2 y1 = self.d.spindlespeed1 y2 = self.d.spindlespeed2 scale = (y2-y1) / (x2-x1) offset = x1 - y1 / scale print >>file print >>file, "net spindle-cmd-rpm => pwmgen.0.value" print >>file, "net spindle-on <= motion.spindle-on => pwmgen.0.enable" print >>file, "net spindle-pwm <= pwmgen.0.pwm" print >>file, "setp pwmgen.0.pwm-freq %s" % self.d.spindlecarrier print >>file, "setp pwmgen.0.scale %s" % scale print >>file, "setp pwmgen.0.offset %s" % offset print >>file, "setp pwmgen.0.dither-pwm true" print >>file, "net spindle-cmd-rpm <= motion.spindle-speed-out" print >>file, "net spindle-cmd-rpm-abs <= motion.spindle-speed-out-abs" print >>file, "net spindle-cmd-rps <= motion.spindle-speed-out-rps" print >>file, "net spindle-cmd-rps-abs <= motion.spindle-speed-out-rps-abs" print >>file, "net spindle-at-speed => motion.spindle-at-speed" if SIG.ON in outputs and not pwm: print >>file, "net spindle-on <= motion.spindle-on" if SIG.CW in outputs: print >>file, "net spindle-cw <= motion.spindle-forward" if SIG.CCW in outputs: print >>file, "net spindle-ccw <= motion.spindle-reverse" if SIG.BRAKE in outputs: print >>file, "net spindle-brake <= motion.spindle-brake" if SIG.MIST in outputs: print >>file, "net coolant-mist <= iocontrol.0.coolant-mist" if SIG.FLOOD in outputs: print >>file, "net coolant-flood <= iocontrol.0.coolant-flood" if encoder: print >>file if SIG.PHB not in inputs: print >>file, "setp encoder.0.position-scale %f"\ % self.d.spindlecpr print >>file, "setp encoder.0.counter-mode 1" else: print >>file, "setp encoder.0.position-scale %f" \ % ( 4.0 * int(self.d.spindlecpr)) print >>file, "net spindle-position encoder.0.position => motion.spindle-revs" print >>file, "net spindle-velocity-feedback-rps encoder.0.velocity => motion.spindle-speed-in" print >>file, "net spindle-index-enable encoder.0.index-enable <=> motion.spindle-index-enable" print >>file, "net spindle-phase-a encoder.0.phase-A" print >>file, "net spindle-phase-b encoder.0.phase-B" print >>file, "net spindle-index encoder.0.phase-Z" if probe: print >>file print >>file, "net probe-in => motion.probe-input" for i in range(4): dout = "dout-%02d" % i if dout in outputs: print >>file, "net %s <= motion.digital-out-%02d" % (dout, i) for i in range(4): din = "din-%02d" % i if din in inputs: print >>file, "net %s => motion.digital-in-%02d" % (din, i) print >>file for o in (1,2,3,4,5,6,7,8,9,14,16,17): self.connect_output(file, o) if self.d.number_pports>1: if self.d.pp2_direction:# Input option pinlist = (1,14,16,17) else: pinlist = (1,2,3,4,5,6,7,8,9,14,16,17) print >>file for i in pinlist: self.connect_output(file, i,1) print >>file for i in (10,11,12,13,15): self.connect_input(file, i) if self.d.number_pports>1: if self.d.pp2_direction: # Input option pinlist = (2,3,4,5,6,7,8,9,10,11,12,13,15) else: pinlist = (10,11,12,13,15) print >>file for i in pinlist: self.connect_input(file, i,1) print >>file if limits_homes: print >>file, "setp lut5.0.function 0x10000" print >>file, "net all-limit-home => lut5.0.in-4" print >>file, "net all-limit <= lut5.0.out" if self.d.axes == 2: print >>file, "net homing-x <= axis.0.homing => lut5.0.in-0" print >>file, "net homing-z <= axis.1.homing => lut5.0.in-1" elif self.d.axes == 0: print >>file, "net homing-x <= axis.0.homing => lut5.0.in-0" print >>file, "net homing-y <= axis.1.homing => lut5.0.in-1" print >>file, "net homing-z <= axis.2.homing => lut5.0.in-2" elif self.d.axes == 1: print >>file, "net homing-x <= axis.0.homing => lut5.0.in-0" print >>file, "net homing-y <= axis.1.homing => lut5.0.in-1" print >>file, "net homing-z <= axis.2.homing => lut5.0.in-2" print >>file, "net homing-a <= axis.3.homing => lut5.0.in-3" if self.d.axes == 2: self.connect_axis(file, 0, 'x') self.connect_axis(file, 1, 'z') elif self.d.axes == 0: self.connect_axis(file, 0, 'x') self.connect_axis(file, 1, 'y') self.connect_axis(file, 2, 'z') elif self.d.axes == 1: self.connect_axis(file, 0, 'x') self.connect_axis(file, 1, 'y') self.connect_axis(file, 2, 'z') self.connect_axis(file, 3, 'a') print >>file print >>file, "net estop-out <= iocontrol.0.user-enable-out" if self.d.classicladder and self.d.ladderhaltype == 1 and self.d.ladderconnect: # external estop program print >>file print >>file, _("# **** Setup for external estop ladder program -START ****") print >>file print >>file, "net estop-out => classicladder.0.in-00" print >>file, "net estop-ext => classicladder.0.in-01" print >>file, "net estop-strobe classicladder.0.in-02 <= iocontrol.0.user-request-enable" print >>file, "net estop-outcl classicladder.0.out-00 => iocontrol.0.emc-enable-in" print >>file print >>file, _("# **** Setup for external estop ladder program -END ****") elif SIG.ESTOP_IN in inputs: print >>file, "net estop-ext => iocontrol.0.emc-enable-in" else: print >>file, "net estop-out => iocontrol.0.emc-enable-in" print >>file if self.d.manualtoolchange: print >>file, "loadusr -W hal_manualtoolchange" print >>file, "net tool-change iocontrol.0.tool-change => hal_manualtoolchange.change" print >>file, "net tool-changed iocontrol.0.tool-changed <= hal_manualtoolchange.changed" print >>file, "net tool-number iocontrol.0.tool-prep-number => hal_manualtoolchange.number" else: print >>file, "net tool-number <= iocontrol.0.tool-prep-number" print >>file, "net tool-change-loopback iocontrol.0.tool-change => iocontrol.0.tool-changed" print >>file, "net tool-prepare-loopback iocontrol.0.tool-prepare => iocontrol.0.tool-prepared" if self.d.classicladder: print >>file if self.d.modbus: print >>file, _("# Load Classicladder with modbus master included (GUI must run for Modbus)") print >>file, "loadusr classicladder --modmaster custom.clp" else: print >>file, _("# Load Classicladder without GUI (can reload LADDER GUI in AXIS GUI") print >>file, "loadusr classicladder --nogui custom.clp" if self.d.pyvcp: vcp = os.path.join(base, "custompanel.xml") if not os.path.exists(vcp): f1 = open(vcp, "w") print >>f1, "<?xml version='1.0' encoding='UTF-8'?>" print >>f1, "<!-- " print >>f1, _("Include your PyVCP panel here.\n") print >>f1, "-->" print >>f1, "<pyvcp>" print >>f1, "</pyvcp>" if self.d.pyvcp or self.d.customhal: custom = os.path.join(base, "custom_postgui.hal") if os.path.exists(custom): shutil.copy( custom,os.path.join(base,"postgui_backup.hal") ) f1 = open(custom, "w") print >>f1, _("# Include your customized HAL commands here") print >>f1, _("# The commands in this file are run after the AXIS GUI (including PyVCP panel) starts") print >>f1 if self.d.pyvcp and self.d.pyvcphaltype == 1 and self.d.pyvcpconnect: # spindle speed/tool # display print >>f1, _("# **** Setup of spindle speed display using pyvcp -START ****") if encoder: print >>f1, _("# **** Use ACTUAL spindle velocity from spindle encoder") print >>f1, _("# **** spindle-velocity-feedback-rps bounces around so we filter it with lowpass") print >>f1, _("# **** spindle-velocity-feedback-rps is signed so we use absolute component to remove sign") print >>f1, _("# **** ACTUAL velocity is in RPS not RPM so we scale it.") print >>f1 print >>f1, ("setp scale.0.gain 60") print >>f1, ("setp lowpass.0.gain %f")% self.d.spindlefiltergain print >>f1, ("net spindle-velocity-feedback-rps => lowpass.0.in") print >>f1, ("net spindle-fb-filtered-rps lowpass.0.out => abs.0.in") print >>f1, ("net spindle-fb-filtered-abs-rps abs.0.out => scale.0.in") print >>f1, ("net spindle-fb-filtered-abs-rpm scale.0.out => pyvcp.spindle-speed") print >>f1 print >>f1, _("# **** set up spindle at speed indicator ****") if self.d.usespindleatspeed: print >>f1 print >>f1, ("net spindle-cmd-rps-abs => near.0.in1") print >>f1, ("net spindle-velocity-feedback-rps => near.0.in2") print >>f1, ("net spindle-at-speed <= near.0.out") print >>f1, ("setp near.0.scale %f")% self.d.spindlenearscale else: print >>f1, ("# **** force spindle at speed indicator true because we chose no feedback ****") print >>f1 print >>f1, ("sets spindle-at-speed true") print >>f1, ("net spindle-at-speed => pyvcp.spindle-at-speed-led") else: print >>f1, _("# **** Use COMMANDED spindle velocity from LinuxCNC because no spindle encoder was specified") print >>f1 print >>f1, ("net spindle-cmd-rpm-abs => pyvcp.spindle-speed") print >>f1 print >>f1, ("# **** force spindle at speed indicator true because we have no feedback ****") print >>f1 print >>f1, ("net spindle-at-speed => pyvcp.spindle-at-speed-led") print >>f1, ("sets spindle-at-speed true") else: print >>f1, ("sets spindle-at-speed true") if self.d.customhal or self.d.classicladder or self.d.halui: custom = os.path.join(base, "custom.hal") if not os.path.exists(custom): f1 = open(custom, "w") print >>f1, _("# Include your customized HAL commands here") print >>f1, _("# This file will not be overwritten when you run stepconf again") file.close() self.sim_hardware_halfile(base) self.d.add_md5sum(filename) #****************** # HELPER FUNCTIONS #****************** def connect_axis(self, file, num, let): axnum = "xyza".index(let) lat = self.d.latency print >>file print >>file, "setp stepgen.%d.position-scale [AXIS_%d]SCALE" % (num, axnum) print >>file, "setp stepgen.%d.steplen 1" % num if self.a.doublestep(): print >>file, "setp stepgen.%d.stepspace 0" % num else: print >>file, "setp stepgen.%d.stepspace 1" % num print >>file, "setp stepgen.%d.dirhold %d" % (num, self.d.dirhold + lat) print >>file, "setp stepgen.%d.dirsetup %d" % (num, self.d.dirsetup + lat) print >>file, "setp stepgen.%d.maxaccel [AXIS_%d]STEPGEN_MAXACCEL" % (num, axnum) print >>file, "net %spos-cmd axis.%d.motor-pos-cmd => stepgen.%d.position-cmd" % (let, axnum, num) print >>file, "net %spos-fb stepgen.%d.position-fb => axis.%d.motor-pos-fb" % (let, num, axnum) print >>file, "net %sstep <= stepgen.%d.step" % (let, num) print >>file, "net %sdir <= stepgen.%d.dir" % (let, num) print >>file, "net %senable axis.%d.amp-enable-out => stepgen.%d.enable" % (let, axnum, num) homesig = self.a.home_sig(let) if homesig: print >>file, "net %s => axis.%d.home-sw-in" % (homesig, axnum) min_limsig = self.min_lim_sig(let) if min_limsig: print >>file, "net %s => axis.%d.neg-lim-sw-in" % (min_limsig, axnum) max_limsig = self.max_lim_sig(let) if max_limsig: print >>file, "net %s => axis.%d.pos-lim-sw-in" % (max_limsig, axnum) def sim_hardware_halfile(self,base): custom = os.path.join(base, "sim_hardware.hal") if self.d.sim_hardware: f1 = open(custom, "w") print >>f1, _("# This file sets up simulated limits/home/spindle encoder hardware.") print >>f1, _("# This is a generated file do not edit.") print >>f1 inputs = self.a.build_input_set() if SIG.PHA in inputs: print >>f1, "loadrt sim_encoder names=sim-encoder" print >>f1, "setp sim-encoder.ppr %d"%int(self.d.spindlecpr) print >>f1, "setp sim-encoder.scale 1" print >>f1 print >>f1, "net spindle-cmd-rps sim-encoder.speed" print >>f1, "net fake-spindle-phase-a sim-encoder.phase-A" print >>f1, "net fake-spindle-phase-b sim-encoder.phase-B" print >>f1, "net fake-spindle-index sim-encoder.phase-Z" print >>f1 print >>f1, "loadrt sim_axis_hardware names=sim-hardware" print >>f1 print >>f1, "net Xjoint-pos-fb axis.0.joint-pos-fb sim-hardware.Xcurrent-pos" if not self.d.axes == 2: print >>f1, "net Yjoint-pos-fb axis.1.joint-pos-fb sim-hardware.Ycurrent-pos" print >>f1, "net Zjoint-pos-fb axis.2.joint-pos-fb sim-hardware.Zcurrent-pos" if self.d.axes == 1: print >>f1, "net Ajoint-pos-fb axis.3.joint-pos-fb sim-hardware.Acurrent-pos" print >>f1 print >>f1, "setp sim-hardware.Xmaxsw-upper 1000" print >>f1, "setp sim-hardware.Xmaxsw-lower [AXIS_0]MAX_LIMIT" print >>f1, "setp sim-hardware.Xminsw-upper [AXIS_0]MIN_LIMIT" print >>f1, "setp sim-hardware.Xminsw-lower -1000" print >>f1, "setp sim-hardware.Xhomesw-pos [AXIS_0]HOME_OFFSET" print >>f1 if not self.d.axes == 2: print >>f1, "setp sim-hardware.Ymaxsw-upper 1000" print >>f1, "setp sim-hardware.Ymaxsw-lower [AXIS_1]MAX_LIMIT" print >>f1, "setp sim-hardware.Yminsw-upper [AXIS_1]MIN_LIMIT" print >>f1, "setp sim-hardware.Yminsw-lower -1000" print >>f1, "setp sim-hardware.Yhomesw-pos [AXIS_1]HOME_OFFSET" print >>f1 print >>f1, "setp sim-hardware.Zmaxsw-upper 1000" print >>f1, "setp sim-hardware.Zmaxsw-lower [AXIS_2]MAX_LIMIT" print >>f1, "setp sim-hardware.Zminsw-upper [AXIS_2]MIN_LIMIT" print >>f1, "setp sim-hardware.Zminsw-lower -1000" print >>f1, "setp sim-hardware.Zhomesw-pos [AXIS_2]HOME_OFFSET" print >>f1 if self.d.axes == 1: print >>f1, "setp sim-hardware.Amaxsw-upper 20000" print >>f1, "setp sim-hardware.Amaxsw-lower [AXIS_3]MAX_LIMIT" print >>f1, "setp sim-hardware.Aminsw-upper [AXIS_3]MIN_LIMIT" print >>f1, "setp sim-hardware.Aminsw-lower -20000" print >>f1, "setp sim-hardware.Ahomesw-pos [AXIS_3]HOME_OFFSET" print >>f1 for port in range(0,self.d.number_pports): print >>f1 if port==0 or not self.d.pp2_direction: # output option pinlist = (10,11,12,13,15) else: pinlist = (2,3,4,5,6,7,8,9,10,11,12,13,15) for i in pinlist: self.connect_input(f1, i, port, True) print >>f1 if port==0 or not self.d.pp2_direction: # output option pinlist = (1,2,3,4,5,6,7,8,9,14,16,17) else: pinlist = (1,14,16,17) for o in pinlist: self.connect_output(f1, o, port, True) print >>f1 print >>f1, "net fake-all-home sim-hardware.homesw-all" print >>f1, "net fake-all-limit sim-hardware.limitsw-all" print >>f1, "net fake-all-limit-home sim-hardware.limitsw-homesw-all" print >>f1, "net fake-both-x sim-hardware.Xbothsw-out" print >>f1, "net fake-max-x sim-hardware.Xmaxsw-out" print >>f1, "net fake-min-x sim-hardware.Xminsw-out" print >>f1, "net fake-both-y sim-hardware.Ybothsw-out" print >>f1, "net fake-max-y sim-hardware.Ymaxsw-out" print >>f1, "net fake-min-y sim-hardware.Yminsw-out" print >>f1, "net fake-both-z sim-hardware.Zbothsw-out" print >>f1, "net fake-max-z sim-hardware.Zmaxsw-out" print >>f1, "net fake-min-z sim-hardware.Zminsw-out" print >>f1, "net fake-both-a sim-hardware.Abothsw-out" print >>f1, "net fake-max-a sim-hardware.Amaxsw-out" print >>f1, "net fake-min-a sim-hardware.Aminsw-out" print >>f1, "net fake-home-x sim-hardware.Xhomesw-out" print >>f1, "net fake-home-y sim-hardware.Yhomesw-out" print >>f1, "net fake-home-z sim-hardware.Zhomesw-out" print >>f1, "net fake-home-a sim-hardware.Ahomesw-out" print >>f1, "net fake-both-home-x sim-hardware.Xbothsw-homesw-out" print >>f1, "net fake-max-home-x sim-hardware.Xmaxsw-homesw-out" print >>f1, "net fake-min-home-x sim-hardware.Xminsw-homesw-out" print >>f1, "net fake-both-home-y sim-hardware.Ybothsw-homesw-out" print >>f1, "net fake-max-home-y sim-hardware.Ymaxsw-homesw-out" print >>f1, "net fake-min-home-y sim-hardware.Yminsw-homesw-out" print >>f1, "net fake-both-home-z sim-hardware.Zbothsw-homesw-out" print >>f1, "net fake-max-home-z sim-hardware.Zmaxsw-homesw-out" print >>f1, "net fake-min-home-z sim-hardware.Zminsw-homesw-out" print >>f1, "net fake-both-home-a sim-hardware.Abothsw-homesw-out" print >>f1, "net fake-max-home-a sim-hardware.Amaxsw-homesw-out" print >>f1, "net fake-min-home-a sim-hardware.Aminsw-homesw-out" f1.close() else: if os.path.exists(custom): os.remove(custom) def connect_input(self, file, num,port=0,fake=False): ending='' if port == 0: p = self.d['pin%d' % num] i = self.d['pin%dinv' % num] else: p = self.d['pp2_pin%d_in' % num] i = self.d['pp2_pin%d_in_inv' % num] if p == SIG.UNUSED_INPUT: return if fake: p='fake-'+p ending='-fake' p ='{0:<20}'.format(p) else: p ='{0:<15}'.format(p) if i: print >>file, "net %s <= parport.%d.pin-%02d-in-not%s" \ % (p, port, num,ending) else: print >>file, "net %s <= parport.%d.pin-%02d-in%s" \ % (p, port, num,ending) def connect_output(self, file, num,port=0,fake=False): ending='' if port == 0: p = self.d['pin%d' % num] i = self.d['pin%dinv' % num] else: p = self.d['pp2_pin%d' % num] i = self.d['pp2_pin%dinv' % num] if p == SIG.UNUSED_OUTPUT: return if fake: p='fake-'+p ending='-fake' p ='{0:<20}'.format(p) else: p ='{0:<15}'.format(p) if i: print >>file, "setp parport.%d.pin-%02d-out-invert%s 1" %(port, num, ending) print >>file, "net %s => parport.%d.pin-%02d-out%s" % (p, port, num, ending) if self.a.doublestep(): if p in (SIG.XSTEP, SIG.YSTEP, SIG.ZSTEP, SIG.ASTEP): print >>file, "setp parport.0.pin-%02d-out-reset%s 1" % (num,ending) def min_lim_sig(self, axis): inputs = self.a.build_input_set() thisaxisminlimits = set((SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME, "min-" + axis, "min-home-" + axis, "both-" + axis, "both-home-" + axis)) for i in inputs: if i in thisaxisminlimits: if i==SIG.ALL_LIMIT_HOME: # ALL_LIMIT is reused here as filtered signal return SIG.ALL_LIMIT else: return i def max_lim_sig(self, axis): inputs = self.a.build_input_set() thisaxismaxlimits = set((SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME, "max-" + axis, "max-home-" + axis, "both-" + axis, "both-home-" + axis)) for i in inputs: if i in thisaxismaxlimits: if i==SIG.ALL_LIMIT_HOME: # ALL_LIMIT is reused here as filtered signal return SIG.ALL_LIMIT else: return i # Boiler code def __getitem__(self, item): return getattr(self, item) def __setitem__(self, item, value): return setattr(self, item, value)
lgpl-2.1
nuess0r/raspberry_preserve
www/cgi/serverside_js.py
1
1364
#!/usr/bin/env python # encoding: utf-8 # # Copyright 2014 Daniel Fairchild # # This file is part of raspberry_preserve. # # 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, 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; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import plot import pconfig import json def webreq(): cfg = pconfig.read('rb_preserve.cfg') first_value, last_value = plot.data_span() return """ function min_secs(){ return %f; } function max_secs(){ return %f; } function default_begin(){ return %s; } function config_json(){ return %s; } """ % (first_value *1000, last_value *1000, cfg.get('settings', 'default_view_hours'), pconfig.json_out()) if __name__ == "__main__": print "Content-type:application/javascript\r\n\r\n%s" % webreq()
gpl-2.0
dharmabumstead/ansible
test/units/modules/web_infrastructure/test_jenkins_plugin.py
70
7046
import collections from io import BytesIO from ansible.modules.web_infrastructure.jenkins_plugin import JenkinsPlugin def pass_function(*args, **kwargs): pass GITHUB_DATA = {"url": u'https://api.github.com/repos/ansible/ansible', "response": b""" { "id": 3638964, "name": "ansible", "full_name": "ansible/ansible", "owner": { "login": "ansible", "id": 1507452, "avatar_url": "https://avatars2.githubusercontent.com/u/1507452?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ansible", "html_url": "https://github.com/ansible", "followers_url": "https://api.github.com/users/ansible/followers", "following_url": "https://api.github.com/users/ansible/following{/other_user}", "gists_url": "https://api.github.com/users/ansible/gists{/gist_id}", "starred_url": "https://api.github.com/users/ansible/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ansible/subscriptions", "organizations_url": "https://api.github.com/users/ansible/orgs", "repos_url": "https://api.github.com/users/ansible/repos", "events_url": "https://api.github.com/users/ansible/events{/privacy}", "received_events_url": "https://api.github.com/users/ansible/received_events", "type": "Organization", "site_admin": false }, "private": false, "html_url": "https://github.com/ansible/ansible", "description": "Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy.", "fork": false, "url": "https://api.github.com/repos/ansible/ansible", "forks_url": "https://api.github.com/repos/ansible/ansible/forks", "keys_url": "https://api.github.com/repos/ansible/ansible/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/ansible/ansible/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/ansible/ansible/teams", "hooks_url": "https://api.github.com/repos/ansible/ansible/hooks", "issue_events_url": "https://api.github.com/repos/ansible/ansible/issues/events{/number}", "events_url": "https://api.github.com/repos/ansible/ansible/events", "assignees_url": "https://api.github.com/repos/ansible/ansible/assignees{/user}", "branches_url": "https://api.github.com/repos/ansible/ansible/branches{/branch}", "tags_url": "https://api.github.com/repos/ansible/ansible/tags", "blobs_url": "https://api.github.com/repos/ansible/ansible/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/ansible/ansible/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/ansible/ansible/git/refs{/sha}", "trees_url": "https://api.github.com/repos/ansible/ansible/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/ansible/ansible/statuses/{sha}", "languages_url": "https://api.github.com/repos/ansible/ansible/languages", "stargazers_url": "https://api.github.com/repos/ansible/ansible/stargazers", "contributors_url": "https://api.github.com/repos/ansible/ansible/contributors", "subscribers_url": "https://api.github.com/repos/ansible/ansible/subscribers", "subscription_url": "https://api.github.com/repos/ansible/ansible/subscription", "commits_url": "https://api.github.com/repos/ansible/ansible/commits{/sha}", "git_commits_url": "https://api.github.com/repos/ansible/ansible/git/commits{/sha}", "comments_url": "https://api.github.com/repos/ansible/ansible/comments{/number}", "issue_comment_url": "https://api.github.com/repos/ansible/ansible/issues/comments{/number}", "contents_url": "https://api.github.com/repos/ansible/ansible/contents/{+path}", "compare_url": "https://api.github.com/repos/ansible/ansible/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/ansible/ansible/merges", "archive_url": "https://api.github.com/repos/ansible/ansible/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/ansible/ansible/downloads", "issues_url": "https://api.github.com/repos/ansible/ansible/issues{/number}", "pulls_url": "https://api.github.com/repos/ansible/ansible/pulls{/number}", "milestones_url": "https://api.github.com/repos/ansible/ansible/milestones{/number}", "notifications_url": "https://api.github.com/repos/ansible/ansible/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/ansible/ansible/labels{/name}", "releases_url": "https://api.github.com/repos/ansible/ansible/releases{/id}", "deployments_url": "https://api.github.com/repos/ansible/ansible/deployments", "created_at": "2012-03-06T14:58:02Z", "updated_at": "2017-09-19T18:10:54Z", "pushed_at": "2017-09-19T18:04:51Z", "git_url": "git://github.com/ansible/ansible.git", "ssh_url": "[email protected]:ansible/ansible.git", "clone_url": "https://github.com/ansible/ansible.git", "svn_url": "https://github.com/ansible/ansible", "homepage": "https://www.ansible.com/", "size": 91174, "stargazers_count": 25552, "watchers_count": 25552, "language": "Python", "has_issues": true, "has_projects": true, "has_downloads": true, "has_wiki": false, "has_pages": false, "forks_count": 8893, "mirror_url": null, "open_issues_count": 4283, "forks": 8893, "open_issues": 4283, "watchers": 25552, "default_branch": "devel", "organization": { "login": "ansible", "id": 1507452, "avatar_url": "https://avatars2.githubusercontent.com/u/1507452?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ansible", "html_url": "https://github.com/ansible", "followers_url": "https://api.github.com/users/ansible/followers", "following_url": "https://api.github.com/users/ansible/following{/other_user}", "gists_url": "https://api.github.com/users/ansible/gists{/gist_id}", "starred_url": "https://api.github.com/users/ansible/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ansible/subscriptions", "organizations_url": "https://api.github.com/users/ansible/orgs", "repos_url": "https://api.github.com/users/ansible/repos", "events_url": "https://api.github.com/users/ansible/events{/privacy}", "received_events_url": "https://api.github.com/users/ansible/received_events", "type": "Organization", "site_admin": false }, "network_count": 8893, "subscribers_count": 1733 } """ } def test__get_json_data(mocker): "test the json conversion of _get_url_data" timeout = 30 params = { 'url': GITHUB_DATA['url'], 'timeout': timeout } module = mocker.Mock() module.params = params JenkinsPlugin._csrf_enabled = pass_function JenkinsPlugin._get_installed_plugins = pass_function JenkinsPlugin._get_url_data = mocker.Mock() JenkinsPlugin._get_url_data.return_value = BytesIO(GITHUB_DATA['response']) jenkins_plugin = JenkinsPlugin(module) json_data = jenkins_plugin._get_json_data( "{url}".format(url=GITHUB_DATA['url']), 'CSRF') assert isinstance(json_data, collections.Mapping)
gpl-3.0
Duoxilian/home-assistant
tests/components/config/test_group.py
10
4081
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import patch from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from tests.common import mock_http_component_app VIEW_NAME = 'api:config:group:config' @asyncio.coroutine def test_get_device_config(hass, test_client): """Test getting device config.""" app = mock_http_component_app(hass) with patch.object(config, 'SECTIONS', ['group']): yield from async_setup_component(hass, 'config', {}) hass.http.views[VIEW_NAME].register(app.router) client = yield from test_client(app) def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/group/config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(hass, test_client): """Test updating device config.""" app = mock_http_component_app(hass) with patch.object(config, 'SECTIONS', ['group']): yield from async_setup_component(hass, 'config', {}) hass.http.views[VIEW_NAME].register(app.router) client = yield from test_client(app) orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/group/config/hello_beer', data=json.dumps({ 'name': 'Beer', 'entities': ['light.top', 'light.bottom'], })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello_beer']['name'] = 'Beer' orig_data['hello_beer']['entities'] = ['light.top', 'light.bottom'] assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(hass, test_client): """Test updating device config.""" app = mock_http_component_app(hass) with patch.object(config, 'SECTIONS', ['group']): yield from async_setup_component(hass, 'config', {}) hass.http.views[VIEW_NAME].register(app.router) client = yield from test_client(app) resp = yield from client.post( '/api/config/group/config/not a slug', data=json.dumps({ 'name': 'YO', })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(hass, test_client): """Test updating device config.""" app = mock_http_component_app(hass) with patch.object(config, 'SECTIONS', ['group']): yield from async_setup_component(hass, 'config', {}) hass.http.views[VIEW_NAME].register(app.router) client = yield from test_client(app) resp = yield from client.post( '/api/config/group/config/hello_beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(hass, test_client): """Test updating device config.""" app = mock_http_component_app(hass) with patch.object(config, 'SECTIONS', ['group']): yield from async_setup_component(hass, 'config', {}) hass.http.views[VIEW_NAME].register(app.router) client = yield from test_client(app) resp = yield from client.post( '/api/config/group/config/hello_beer', data='not json') assert resp.status == 400
mit
soldag/home-assistant
homeassistant/components/nest/sensor_sdm.py
3
4246
"""Support for Google Nest SDM sensors.""" from typing import Optional from google_nest_sdm.device import Device from google_nest_sdm.device_traits import HumidityTrait, TemperatureTrait from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import HomeAssistantType from .const import DOMAIN, SIGNAL_NEST_UPDATE from .device_info import DeviceInfo DEVICE_TYPE_MAP = { "sdm.devices.types.CAMERA": "Camera", "sdm.devices.types.DISPLAY": "Display", "sdm.devices.types.DOORBELL": "Doorbell", "sdm.devices.types.THERMOSTAT": "Thermostat", } async def async_setup_sdm_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the sensors.""" subscriber = hass.data[DOMAIN][entry.entry_id] device_manager = await subscriber.async_get_device_manager() # Fetch initial data so we have data when entities subscribe. entities = [] for device in device_manager.devices.values(): if TemperatureTrait.NAME in device.traits: entities.append(TemperatureSensor(device)) if HumidityTrait.NAME in device.traits: entities.append(HumiditySensor(device)) async_add_entities(entities) class SensorBase(Entity): """Representation of a dynamically updated Sensor.""" def __init__(self, device: Device): """Initialize the sensor.""" self._device = device self._device_info = DeviceInfo(device) @property def should_poll(self) -> bool: """Disable polling since entities have state pushed via pubsub.""" return False @property def unique_id(self) -> Optional[str]: """Return a unique ID.""" # The API "name" field is a unique device identifier. return f"{self._device.name}-{self.device_class}" @property def device_info(self): """Return device specific attributes.""" return self._device_info.device_info async def async_added_to_hass(self): """Run when entity is added to register update signal handler.""" # Event messages trigger the SIGNAL_NEST_UPDATE, which is intercepted # here to re-fresh the signals from _device. Unregister this callback # when the entity is removed. self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_NEST_UPDATE, self.async_write_ha_state, ) ) class TemperatureSensor(SensorBase): """Representation of a Temperature Sensor.""" @property def name(self): """Return the name of the sensor.""" return f"{self._device_info.device_name} Temperature" @property def state(self): """Return the state of the sensor.""" trait = self._device.traits[TemperatureTrait.NAME] return trait.ambient_temperature_celsius @property def unit_of_measurement(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def device_class(self): """Return the class of this device.""" return DEVICE_CLASS_TEMPERATURE class HumiditySensor(SensorBase): """Representation of a Humidity Sensor.""" @property def unique_id(self) -> Optional[str]: """Return a unique ID.""" # The API returns the identifier under the name field. return f"{self._device.name}-humidity" @property def name(self): """Return the name of the sensor.""" return f"{self._device_info.device_name} Humidity" @property def state(self): """Return the state of the sensor.""" trait = self._device.traits[HumidityTrait.NAME] return trait.ambient_humidity_percent @property def unit_of_measurement(self): """Return the unit of measurement.""" return PERCENTAGE @property def device_class(self): """Return the class of this device.""" return DEVICE_CLASS_HUMIDITY
apache-2.0
cyberark-bizdev/ansible
lib/ansible/module_utils/facts/network/aix.py
143
5982
# 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 re from ansible.module_utils.facts.network.base import NetworkCollector from ansible.module_utils.facts.network.generic_bsd import GenericBsdIfconfigNetwork class AIXNetwork(GenericBsdIfconfigNetwork): """ This is the AIX Network Class. It uses the GenericBsdIfconfigNetwork unchanged. """ platform = 'AIX' def get_default_interfaces(self, route_path): netstat_path = self.module.get_bin_path('netstat') rc, out, err = self.module.run_command([netstat_path, '-nr']) interface = dict(v4={}, v6={}) lines = out.splitlines() for line in lines: words = line.split() if len(words) > 1 and words[0] == 'default': if '.' in words[1]: interface['v4']['gateway'] = words[1] interface['v4']['interface'] = words[5] elif ':' in words[1]: interface['v6']['gateway'] = words[1] interface['v6']['interface'] = words[5] return interface['v4'], interface['v6'] # AIX 'ifconfig -a' does not have three words in the interface line def get_interfaces_info(self, ifconfig_path, ifconfig_options='-a'): interfaces = {} current_if = {} ips = dict( all_ipv4_addresses=[], all_ipv6_addresses=[], ) uname_rc = None uname_out = None uname_err = None uname_path = self.module.get_bin_path('uname') if uname_path: uname_rc, uname_out, uname_err = self.module.run_command([uname_path, '-W']) rc, out, err = self.module.run_command([ifconfig_path, ifconfig_options]) for line in out.splitlines(): if line: words = line.split() # only this condition differs from GenericBsdIfconfigNetwork if re.match(r'^\w*\d*:', line): current_if = self.parse_interface_line(words) interfaces[current_if['device']] = current_if elif words[0].startswith('options='): self.parse_options_line(words, current_if, ips) elif words[0] == 'nd6': self.parse_nd6_line(words, current_if, ips) elif words[0] == 'ether': self.parse_ether_line(words, current_if, ips) elif words[0] == 'media:': self.parse_media_line(words, current_if, ips) elif words[0] == 'status:': self.parse_status_line(words, current_if, ips) elif words[0] == 'lladdr': self.parse_lladdr_line(words, current_if, ips) elif words[0] == 'inet': self.parse_inet_line(words, current_if, ips) elif words[0] == 'inet6': self.parse_inet6_line(words, current_if, ips) else: self.parse_unknown_line(words, current_if, ips) # don't bother with wpars it does not work # zero means not in wpar if not uname_rc and uname_out.split()[0] == '0': if current_if['macaddress'] == 'unknown' and re.match('^en', current_if['device']): entstat_path = self.module.get_bin_path('entstat') if entstat_path: rc, out, err = self.module.run_command([entstat_path, current_if['device']]) if rc != 0: break for line in out.splitlines(): if not line: pass buff = re.match('^Hardware Address: (.*)', line) if buff: current_if['macaddress'] = buff.group(1) buff = re.match('^Device Type:', line) if buff and re.match('.*Ethernet', line): current_if['type'] = 'ether' # device must have mtu attribute in ODM if 'mtu' not in current_if: lsattr_path = self.module.get_bin_path('lsattr') if lsattr_path: rc, out, err = self.module.run_command([lsattr_path, '-El', current_if['device']]) if rc != 0: break for line in out.splitlines(): if line: words = line.split() if words[0] == 'mtu': current_if['mtu'] = words[1] return interfaces, ips # AIX 'ifconfig -a' does not inform about MTU, so remove current_if['mtu'] here def parse_interface_line(self, words): device = words[0][0:-1] current_if = {'device': device, 'ipv4': [], 'ipv6': [], 'type': 'unknown'} current_if['flags'] = self.get_options(words[1]) current_if['macaddress'] = 'unknown' # will be overwritten later return current_if class AIXNetworkCollector(NetworkCollector): _fact_class = AIXNetwork _platform = 'AIX'
gpl-3.0
felixfontein/ansible
lib/ansible/galaxy/dependency_resolution/__init__.py
20
2137
# -*- coding: utf-8 -*- # Copyright: (c) 2020-2021, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """Dependency resolution machinery.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type try: from typing import TYPE_CHECKING except ImportError: TYPE_CHECKING = False if TYPE_CHECKING: from typing import Iterable from ansible.galaxy.api import GalaxyAPI from ansible.galaxy.collection.concrete_artifact_manager import ( ConcreteArtifactsManager, ) from ansible.galaxy.dependency_resolution.dataclasses import ( Candidate, Requirement, ) from ansible.galaxy.collection.galaxy_api_proxy import MultiGalaxyAPIProxy from ansible.galaxy.dependency_resolution.providers import CollectionDependencyProvider from ansible.galaxy.dependency_resolution.reporters import CollectionDependencyReporter from ansible.galaxy.dependency_resolution.resolvers import CollectionDependencyResolver def build_collection_dependency_resolver( galaxy_apis, # type: Iterable[GalaxyAPI] concrete_artifacts_manager, # type: ConcreteArtifactsManager user_requirements, # type: Iterable[Requirement] preferred_candidates=None, # type: Iterable[Candidate] with_deps=True, # type: bool with_pre_releases=False, # type: bool upgrade=False, # type: bool ): # type: (...) -> CollectionDependencyResolver """Return a collection dependency resolver. The returned instance will have a ``resolve()`` method for further consumption. """ return CollectionDependencyResolver( CollectionDependencyProvider( apis=MultiGalaxyAPIProxy(galaxy_apis, concrete_artifacts_manager), concrete_artifacts_manager=concrete_artifacts_manager, user_requirements=user_requirements, preferred_candidates=preferred_candidates, with_deps=with_deps, with_pre_releases=with_pre_releases, upgrade=upgrade, ), CollectionDependencyReporter(), )
gpl-3.0
LPgenerator/django-mmc
mmc/admin.py
1
3184
__author__ = 'gotlium' from django.contrib import admin from mmc.models import MMCLog, MMCScript, MMCHost, MMCEmail class MMCLogAdmin(admin.ModelAdmin): list_display = ( 'script', 'hostname', 'success', 'elapsed', 'memory', 'cpu_time', 'start', 'end', 'is_fixed') list_filter = ('success', 'is_fixed', 'script', 'hostname', 'created',) list_display_links = ('script',) list_editable = ['is_fixed'] readonly_fields = ( 'start', 'end', 'elapsed', 'hostname', 'script', 'queries', 'sys_argv', 'success', 'error_message', 'memory', 'cpu_time') fields = ( 'start', 'end', 'elapsed', 'hostname', 'script', 'memory', 'cpu_time', 'queries', 'sys_argv', 'success', 'error_message', 'traceback', 'stdout_messages') date_hierarchy = 'created' ordering = ('-id',) search_fields = ( 'error_message', 'traceback', 'hostname__name', 'script__name', ) def has_add_permission(self, request): return False def has_change_permission(self, request, obj=None): return request.method != 'POST' def has_delete_permission(self, request, obj=None): return False class MMCHostAdmin(admin.ModelAdmin): list_display = ('name', 'ignore', 'created', 'id',) list_filter = ('created', 'ignore',) list_display_links = ('name',) readonly_fields = ('name',) date_hierarchy = 'created' ordering = ('-id',) search_fields = ('name',) def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False class MMCScriptAdmin(MMCHostAdmin): list_display = ( 'name', 'calls', 'max_elapsed_sec', 'ignore', 'one_copy', 'save_on_error', 'real_time', 'enable_queries', 'temporarily_disabled', 'enable_triggers', 'created', 'last_call', 'id') list_filter = ( 'temporarily_disabled', 'ignore', 'one_copy', 'save_on_error', 'real_time', 'enable_queries', 'enable_triggers', 'track_at_exit',) # list_editable = list_filter fieldsets = [ ('Basic', {'fields': [ 'temporarily_disabled', 'ignore', 'one_copy', 'save_on_error', 'real_time', 'enable_queries', 'track_at_exit', 'interval_restriction', ]}), ('Triggers', {'fields': [ 'enable_triggers', 'trigger_time', 'trigger_memory', 'trigger_cpu', 'trigger_queries', ]}), ] def max_elapsed_sec(self, cls): return '%0.2f sec' % cls.max_elapsed max_elapsed_sec.admin_order_field = 'max_elapsed' max_elapsed_sec.short_description = 'Max elapsed' class MMCEmailAdmin(admin.ModelAdmin): list_display = ('email', 'is_active', 'created', 'id',) list_filter = ('created', 'is_active',) list_display_links = ('email',) filter_horizontal = ('ignore',) date_hierarchy = 'created' ordering = ('-id',) search_fields = ('email',) admin.site.register(MMCLog, MMCLogAdmin) admin.site.register(MMCHost, MMCHostAdmin) admin.site.register(MMCScript, MMCScriptAdmin) admin.site.register(MMCEmail, MMCEmailAdmin)
gpl-2.0
schristiaens/raft
core/tester/CSRFTester.py
11
3532
# # Author: Nathan Hamiel # # Copyright (c) 2013 RAFT Team # # This file is part of RAFT. # # RAFT 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. # # RAFT 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 RAFT. If not, see <http://www.gnu.org/licenses/>. # import lxml from urllib.parse import parse_qs, urlsplit from xml.sax.saxutils import escape from lxml.html import builder as E from actions import encoderlib def form_to_get(url, html): """ Convert POST to GET """ query_params = "" newhtml = lxml.html.fromstring(html) form = newhtml.forms[0] for item in form.form_values(): query_params += item[0] + "=" + item[1] enc_params = encoderlib.url_encode(query_params) full_url = url + "/" + enc_params return full_url def generate_csrf_form(url, reqData, method): """ Generate a CSRF form with a submit button """ RAFT_CSRF_STATEMENT = "<!-- Generated by the RAFT CSRF Generator -->" if method == "get": splitted = urlsplit(url) parsed = parse_qs(splitted.query) inputs = "" for value in parsed: # print(parsed[value][0]) inputs += 'E.INPUT(name="%s", value="%s"), ' % (value, parsed[value][0]) collected_inputs = inputs.rstrip(",") if method == "post": inputs = "" parsed = parse_qs(reqData) for value in parsed: # print(parsed[value][0]) inputs += 'E.INPUT(name="%s", value="%s"), ' % (value, parsed[value][0]) collected_inputs = inputs.rstrip(",") """ inputs = "" parsed = parse_qs(reqData) for value in parsed: # print(parsed[value][0]) inputs += 'E.INPUT(name="%s", value="%s"), ' % (value, parsed[value][0]) collected_inputs = inputs.rstrip(",") """ HTML = """E.HTML( E.HEAD(E.SCRIPT(RAFT_CSRF_STATEMENT)), E.BODY( E.FORM(%s E.INPUT(type="submit", value="submit"), action="%s", method="%s") ) )""" % (inputs, url, method) #Ensure the object is properly converted and decoded prior to being returned return lxml.html.tostring(eval(HTML), pretty_print=True).decode("utf8") def generate_csrf_img(url, html): """ Create a piece of HTML that contains an image tag with the CSRF values """ img_url = form_to_get(url, html) # Create an img tag that is 1x1 pixel HTML = E.HTML( E.HEAD(), E.BODY( E.IMG(src=img_url, height="1", width="1") ) ) # print(lxml.html.tostring(HTML).decode("utf8")) return lxml.html.tostring(HTML, pretty_print=True).decode("utf8") def generate_csrf_html(url, reqData, method): """ Generate the initial response for the CSRF tester """ htmlresult = generate_csrf_form(url, reqData, method) return htmlresult
gpl-3.0
mazaclub/mazabot-core
test/test_schedule.py
9
2808
### # Copyright (c) 2002-2005, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # 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 supybot.test import * import time import supybot.schedule as schedule class TestSchedule(SupyTestCase): def testSchedule(self): sched = schedule.Schedule() i = [0] def add10(): i[0] = i[0] + 10 def add1(): i[0] = i[0] + 1 sched.addEvent(add10, time.time() + 3) sched.addEvent(add1, time.time() + 1) time.sleep(1.2) sched.run() self.assertEqual(i[0], 1) time.sleep(1.9) sched.run() self.assertEqual(i[0], 11) sched.addEvent(add10, time.time() + 3, 'test') sched.run() self.assertEqual(i[0], 11) sched.removeEvent('test') self.assertEqual(i[0], 11) time.sleep(3) self.assertEqual(i[0], 11) def testReschedule(self): sched = schedule.Schedule() i = [0] def inc(): i[0] += 1 n = sched.addEvent(inc, time.time() + 1) sched.rescheduleEvent(n, time.time() + 3) time.sleep(1.2) sched.run() self.assertEqual(i[0], 0) time.sleep(2) sched.run() self.assertEqual(i[0], 1) # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
bsd-3-clause
dwillmer/rust
src/etc/regex-match-tests.py
58
3565
#!/usr/bin/env python2 # Copyright 2014 The Rust Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution and at # http://rust-lang.org/COPYRIGHT. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. from __future__ import absolute_import, division, print_function import argparse import datetime import os.path as path def print_tests(tests): print('\n'.join([test_tostr(t) for t in tests])) def read_tests(f): basename, _ = path.splitext(path.basename(f)) tests = [] for lineno, line in enumerate(open(f), 1): fields = filter(None, map(str.strip, line.split('\t'))) if not (4 <= len(fields) <= 5) \ or 'E' not in fields[0] or fields[0][0] == '#': continue opts, pat, text, sgroups = fields[0:4] groups = [] # groups as integer ranges if sgroups == 'NOMATCH': groups = [None] elif ',' in sgroups: noparen = map(lambda s: s.strip('()'), sgroups.split(')(')) for g in noparen: s, e = map(str.strip, g.split(',')) if s == '?' and e == '?': groups.append(None) else: groups.append((int(s), int(e))) else: # This skips tests that should result in an error. # There aren't many, so I think we can just capture those # manually. Possibly fix this in future. continue if pat == 'SAME': pat = tests[-1][1] if '$' in opts: pat = pat.decode('string_escape') text = text.decode('string_escape') if 'i' in opts: pat = '(?i)%s' % pat name = '%s_%d' % (basename, lineno) tests.append((name, pat, text, groups)) return tests def test_tostr(t): lineno, pat, text, groups = t options = map(group_tostr, groups) return 'mat!{match_%s, r"%s", r"%s", %s}' \ % (lineno, pat, '' if text == "NULL" else text, ', '.join(options)) def group_tostr(g): if g is None: return 'None' else: return 'Some((%d, %d))' % (g[0], g[1]) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Generate match tests from an AT&T POSIX test file.') aa = parser.add_argument aa('files', nargs='+', help='A list of dat AT&T POSIX test files. See src/libregexp/testdata') args = parser.parse_args() tests = [] for f in args.files: tests += read_tests(f) tpl = '''// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-tidy-linelength // DO NOT EDIT. Automatically generated by 'src/etc/regexp-match-tests' // on {date}. ''' print(tpl.format(date=str(datetime.datetime.now()))) for f in args.files: print('// Tests from %s' % path.basename(f)) print_tests(read_tests(f)) print('')
apache-2.0
Sarah-Alsinan/muypicky
lib/python3.6/site-packages/setuptools/command/test.py
55
8535
import os import operator import sys import contextlib import itertools from distutils.errors import DistutilsOptionError from unittest import TestLoader from setuptools.extern import six from setuptools.extern.six.moves import map, filter from pkg_resources import (resource_listdir, resource_exists, normalize_path, working_set, _namespace_packages, add_activation_listener, require, EntryPoint) from setuptools import Command from setuptools.py31compat import unittest_main class ScanningLoader(TestLoader): def loadTestsFromModule(self, module, pattern=None): """Return a suite of all tests cases contained in the given module If the module is a package, load tests from all the modules in it. If the module has an ``additional_tests`` function, call it and add the return value to the tests. """ tests = [] tests.append(TestLoader.loadTestsFromModule(self, module)) if hasattr(module, "additional_tests"): tests.append(module.additional_tests()) if hasattr(module, '__path__'): for file in resource_listdir(module.__name__, ''): if file.endswith('.py') and file != '__init__.py': submodule = module.__name__ + '.' + file[:-3] else: if resource_exists(module.__name__, file + '/__init__.py'): submodule = module.__name__ + '.' + file else: continue tests.append(self.loadTestsFromName(submodule)) if len(tests) != 1: return self.suiteClass(tests) else: return tests[0] # don't create a nested suite for only one return # adapted from jaraco.classes.properties:NonDataProperty class NonDataProperty(object): def __init__(self, fget): self.fget = fget def __get__(self, obj, objtype=None): if obj is None: return self return self.fget(obj) class test(Command): """Command to run unit tests after in-place build""" description = "run unit tests after in-place build" user_options = [ ('test-module=', 'm', "Run 'test_suite' in specified module"), ('test-suite=', 's', "Test suite to run (e.g. 'some_module.test_suite')"), ('test-runner=', 'r', "Test runner to use"), ] def initialize_options(self): self.test_suite = None self.test_module = None self.test_loader = None self.test_runner = None def finalize_options(self): if self.test_suite and self.test_module: msg = "You may specify a module or a suite, but not both" raise DistutilsOptionError(msg) if self.test_suite is None: if self.test_module is None: self.test_suite = self.distribution.test_suite else: self.test_suite = self.test_module + ".test_suite" if self.test_loader is None: self.test_loader = getattr(self.distribution, 'test_loader', None) if self.test_loader is None: self.test_loader = "setuptools.command.test:ScanningLoader" if self.test_runner is None: self.test_runner = getattr(self.distribution, 'test_runner', None) @NonDataProperty def test_args(self): return list(self._test_args()) def _test_args(self): if self.verbose: yield '--verbose' if self.test_suite: yield self.test_suite def with_project_on_sys_path(self, func): """ Backward compatibility for project_on_sys_path context. """ with self.project_on_sys_path(): func() @contextlib.contextmanager def project_on_sys_path(self, include_dists=[]): with_2to3 = six.PY3 and getattr(self.distribution, 'use_2to3', False) if with_2to3: # If we run 2to3 we can not do this inplace: # Ensure metadata is up-to-date self.reinitialize_command('build_py', inplace=0) self.run_command('build_py') bpy_cmd = self.get_finalized_command("build_py") build_path = normalize_path(bpy_cmd.build_lib) # Build extensions self.reinitialize_command('egg_info', egg_base=build_path) self.run_command('egg_info') self.reinitialize_command('build_ext', inplace=0) self.run_command('build_ext') else: # Without 2to3 inplace works fine: self.run_command('egg_info') # Build extensions in-place self.reinitialize_command('build_ext', inplace=1) self.run_command('build_ext') ei_cmd = self.get_finalized_command("egg_info") old_path = sys.path[:] old_modules = sys.modules.copy() try: project_path = normalize_path(ei_cmd.egg_base) sys.path.insert(0, project_path) working_set.__init__() add_activation_listener(lambda dist: dist.activate()) require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version)) with self.paths_on_pythonpath([project_path]): yield finally: sys.path[:] = old_path sys.modules.clear() sys.modules.update(old_modules) working_set.__init__() @staticmethod @contextlib.contextmanager def paths_on_pythonpath(paths): """ Add the indicated paths to the head of the PYTHONPATH environment variable so that subprocesses will also see the packages at these paths. Do this in a context that restores the value on exit. """ nothing = object() orig_pythonpath = os.environ.get('PYTHONPATH', nothing) current_pythonpath = os.environ.get('PYTHONPATH', '') try: prefix = os.pathsep.join(paths) to_join = filter(None, [prefix, current_pythonpath]) new_path = os.pathsep.join(to_join) if new_path: os.environ['PYTHONPATH'] = new_path yield finally: if orig_pythonpath is nothing: os.environ.pop('PYTHONPATH', None) else: os.environ['PYTHONPATH'] = orig_pythonpath @staticmethod def install_dists(dist): """ Install the requirements indicated by self.distribution and return an iterable of the dists that were built. """ ir_d = dist.fetch_build_eggs(dist.install_requires or []) tr_d = dist.fetch_build_eggs(dist.tests_require or []) return itertools.chain(ir_d, tr_d) def run(self): installed_dists = self.install_dists(self.distribution) cmd = ' '.join(self._argv) if self.dry_run: self.announce('skipping "%s" (dry run)' % cmd) return self.announce('running "%s"' % cmd) paths = map(operator.attrgetter('location'), installed_dists) with self.paths_on_pythonpath(paths): with self.project_on_sys_path(): self.run_tests() def run_tests(self): # Purge modules under test from sys.modules. The test loader will # re-import them from the build location. Required when 2to3 is used # with namespace packages. if six.PY3 and getattr(self.distribution, 'use_2to3', False): module = self.test_suite.split('.')[0] if module in _namespace_packages: del_modules = [] if module in sys.modules: del_modules.append(module) module += '.' for name in sys.modules: if name.startswith(module): del_modules.append(name) list(map(sys.modules.__delitem__, del_modules)) unittest_main( None, None, self._argv, testLoader=self._resolve_as_ep(self.test_loader), testRunner=self._resolve_as_ep(self.test_runner), ) @property def _argv(self): return ['unittest'] + self.test_args @staticmethod def _resolve_as_ep(val): """ Load the indicated attribute value, called, as a as if it were specified as an entry point. """ if val is None: return parsed = EntryPoint.parse("x=" + val) return parsed.resolve()()
mit
mkaluza/external_chromium_org
tools/telemetry/telemetry/core/heap/chrome_js_heap_snapshot_parser_unittest.py
38
2528
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import unittest from telemetry.core.heap import chrome_js_heap_snapshot_parser class ChromeJsHeapSnapshotParserUnittest(unittest.TestCase): def _HeapSnapshotData(self, node_types, edge_types, node_fields, edge_fields, node_list, edge_list, strings): """Helper for creating heap snapshot data.""" return {'snapshot': {'meta': {'node_types': [node_types], 'edge_types': [edge_types], 'node_fields': node_fields, 'edge_fields': edge_fields}}, 'nodes': node_list, 'edges': edge_list, 'strings': strings} def testParseSimpleSnapshot(self): # Create a snapshot containing 2 nodes and an edge between them. node_types = ['object'] edge_types = ['property'] node_fields = ['type', 'name', 'id', 'edge_count'] edge_fields = ['type', 'name_or_index', 'to_node'] node_list = [0, 0, 0, 1, 0, 1, 1, 0] edge_list = [0, 2, 4] strings = ['node1', 'node2', 'edge1'] heap = self._HeapSnapshotData(node_types, edge_types, node_fields, edge_fields, node_list, edge_list, strings) objects = list(chrome_js_heap_snapshot_parser.ChromeJsHeapSnapshotParser( json.dumps(heap)).GetAllLiveHeapObjects()) self.assertEqual(2, len(objects)) if objects[0].edges_from: from_ix = 0 to_ix = 1 else: from_ix = 1 to_ix = 0 self.assertEqual('node1', objects[from_ix].class_name) self.assertEqual('node2', objects[to_ix].class_name) self.assertEqual(1, len(objects[from_ix].edges_from)) self.assertEqual(0, len(objects[from_ix].edges_to)) self.assertEqual(0, len(objects[to_ix].edges_from)) self.assertEqual(1, len(objects[to_ix].edges_to)) self.assertEqual('node1', objects[from_ix].edges_from[0].from_object.class_name) self.assertEqual('node2', objects[from_ix].edges_from[0].to_object.class_name) self.assertEqual('edge1', objects[from_ix].edges_from[0].name_string) self.assertEqual('node1', objects[to_ix].edges_to[0].from_object.class_name) self.assertEqual('node2', objects[to_ix].edges_to[0].to_object.class_name) self.assertEqual('edge1', objects[to_ix].edges_to[0].name_string)
bsd-3-clause
picoCTF/picoCTF-web
api/config.py
1
4633
""" CTF API Configuration File Note this is just a python script. It does config things. """ from api.common import WebException import api import datetime import json import api.app """ FLASK """ #api.app.session_cookie_domain = "0.0.0.0" api.app.session_cookie_path = "/" api.app.session_cookie_name = "flask" # KEEP THIS SECRET api.app.secret_key = "5XVbne3AjPH35eEH8yQI" """ SECURITY """ api.common.allowed_protocols = ["https", "http"] api.common.allowed_ports = [8080] """ MONGO """ api.common.mongo_db_name = "ctf" api.common.mongo_addr = "127.0.0.1" api.common.mongo_port = 27017 """ TESTING """ testing_mongo_db_name = "ctf_test" testing_mongo_addr = "127.0.0.1" testing_mongo_port = 27017 """ SETUP """ competition_name = "ctf" competition_urls = ["http://192.168.2.2"] # Helper class for timezones class EST(datetime.tzinfo): def __init__(self, utc_offset): self.utc_offset = utc_offset def utcoffset(self, dt): return datetime.timedelta(hours=-self.utc_offset) def dst(self, dt): return datetime.timedelta(0) """ CTF Settings These are the default settings that will be loaded into the database if no settings are already loaded. """ default_settings = { "enable_teachers": True, "enable_feedback": True, # TIME WINDOW "start_time": datetime.datetime.utcnow(), "end_time": datetime.datetime.utcnow(), # EMAIL WHITELIST "email_filter": [], # TEAMS "max_team_size": 1, # ACHIEVEMENTS "achievements": { "enable_achievements": True, "processor_base_path": "./achievements", }, "username_blacklist": [ "root", "daemon", "bin", "sys", "adm", "tty", "disk", "lp", "mail", "news", "uucp", "man", "proxy", "kmem", "dialout", "fax", "voice", "cdrom", "floppy", "tape", "sudo", "audio", "dip", "backup", "operator", "list", "irc", "src", "gnats", "shadow", "utmp", "video", "sasl", "plugdev", "staff", "games", "users", "nogroup", "input", "netdev", "crontab", "syslog", "fuse", "messagebus", "uuidd", "mlocate", "ssh", "landscape", "admin", "vagrant", "scanner", "colord", "vboxsf", "puppet", "ubuntu", "utempter", "shellinabox", "docker", "competitors", "hacksports", ], # EMAIL (SMTP) "email":{ "enable_email": False, "email_verification": False, "smtp_url":"", "smtp_port": 587, "email_username": "", "email_password": "", "from_addr": "", "from_name": "", "max_verification_emails": 3, "smtp_security": "TLS" }, # CAPTCHA "captcha": { "enable_captcha": False, "captcha_url": "https://www.google.com/recaptcha/api/siteverify", "reCAPTCHA_public_key": "", "reCAPTCHA_private_key": "", }, # LOGGING # Will be emailed any severe internal exceptions! # Requires email block to be setup. "logging": { "admin_emails": ["[email protected]", "[email protected]"], "critical_error_timeout": 600 } } """ Helper functions to get settings. Do not change these """ def get_settings(): db = api.common.get_conn() settings = db.settings.find_one({}, {"_id":0}) if settings is None: db.settings.insert(default_settings) return default_settings return settings def change_settings(changes): db = api.common.get_conn() settings = db.settings.find_one({}) def check_keys(real, changed): keys = list(changed.keys()) for key in keys: if key not in real: raise WebException("Cannot update setting for '{}'".format(key)) elif type(real[key]) != type(changed[key]): raise WebException("Cannot update setting for '{}'".format(key)) elif isinstance(real[key], dict): check_keys(real[key], changed[key]) # change the key so mongo $set works correctly for key2 in changed[key]: changed["{}.{}".format(key,key2)] = changed[key][key2] changed.pop(key) check_keys(settings, changes) db.settings.update({"_id":settings["_id"]}, {"$set": changes})
mit
zzzombat/lucid-python-django
django/contrib/gis/gdal/libgdal.py
156
3390
import os, re, sys from ctypes import c_char_p, CDLL from ctypes.util import find_library from django.contrib.gis.gdal.error import OGRException # Custom library path set? try: from django.conf import settings lib_path = settings.GDAL_LIBRARY_PATH except (AttributeError, EnvironmentError, ImportError): lib_path = None if lib_path: lib_names = None elif os.name == 'nt': # Windows NT shared libraries lib_names = ['gdal18', 'gdal17', 'gdal16', 'gdal15'] elif os.name == 'posix': # *NIX library names. lib_names = ['gdal', 'GDAL', 'gdal1.7.0', 'gdal1.6.0', 'gdal1.5.0', 'gdal1.4.0'] else: raise OGRException('Unsupported OS "%s"' % os.name) # Using the ctypes `find_library` utility to find the # path to the GDAL library from the list of library names. if lib_names: for lib_name in lib_names: lib_path = find_library(lib_name) if not lib_path is None: break if lib_path is None: raise OGRException('Could not find the GDAL library (tried "%s"). ' 'Try setting GDAL_LIBRARY_PATH in your settings.' % '", "'.join(lib_names)) # This loads the GDAL/OGR C library lgdal = CDLL(lib_path) # On Windows, the GDAL binaries have some OSR routines exported with # STDCALL, while others are not. Thus, the library will also need to # be loaded up as WinDLL for said OSR functions that require the # different calling convention. if os.name == 'nt': from ctypes import WinDLL lwingdal = WinDLL(lib_path) def std_call(func): """ Returns the correct STDCALL function for certain OSR routines on Win32 platforms. """ if os.name == 'nt': return lwingdal[func] else: return lgdal[func] #### Version-information functions. #### # Returns GDAL library version information with the given key. _version_info = std_call('GDALVersionInfo') _version_info.argtypes = [c_char_p] _version_info.restype = c_char_p def gdal_version(): "Returns only the GDAL version number information." return _version_info('RELEASE_NAME') def gdal_full_version(): "Returns the full GDAL version information." return _version_info('') def gdal_release_date(date=False): """ Returns the release date in a string format, e.g, "2007/06/27". If the date keyword argument is set to True, a Python datetime object will be returned instead. """ from datetime import date as date_type rel = _version_info('RELEASE_DATE') yy, mm, dd = map(int, (rel[0:4], rel[4:6], rel[6:8])) d = date_type(yy, mm, dd) if date: return d else: return d.strftime('%Y/%m/%d') version_regex = re.compile(r'^(?P<major>\d+)\.(?P<minor>\d+)(\.(?P<subminor>\d+))?') def gdal_version_info(): ver = gdal_version() m = version_regex.match(ver) if not m: raise OGRException('Could not parse GDAL version string "%s"' % ver) return dict([(key, m.group(key)) for key in ('major', 'minor', 'subminor')]) _verinfo = gdal_version_info() GDAL_MAJOR_VERSION = int(_verinfo['major']) GDAL_MINOR_VERSION = int(_verinfo['minor']) GDAL_SUBMINOR_VERSION = _verinfo['subminor'] and int(_verinfo['subminor']) GDAL_VERSION = (GDAL_MAJOR_VERSION, GDAL_MINOR_VERSION, GDAL_SUBMINOR_VERSION) del _verinfo # GeoJSON support is available only in GDAL 1.5+. if GDAL_VERSION >= (1, 5): GEOJSON = True else: GEOJSON = False
bsd-3-clause
garthylou/pootle
pootle/apps/pootle_translationproject/urls.py
7
1200
#!/usr/bin/env python # -*- 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 django.conf.urls import patterns, url urlpatterns = patterns('pootle_translationproject.views', # Admin views url(r'^(?P<language_code>[^/]*)/(?P<project_code>[^/]*)' r'/admin/permissions/', 'admin_permissions', name='pootle-tp-admin-permissions'), # Translation url(r'^(?P<language_code>[^/]*)/(?P<project_code>[^/]*)/' r'translate/(?P<dir_path>(.*/)*)(?P<filename>.*\.*)?$', 'translate', name='pootle-tp-translate'), # Export view for proofreading url(r'^(?P<language_code>[^/]*)/(?P<project_code>[^/]*)/' r'export-view/(?P<dir_path>(.*/)*)(?P<filename>.*\.*)?$', 'export_view', name='pootle-tp-export-view'), # Browser url(r'^(?P<language_code>[^/]*)/(?P<project_code>[^/]*)/' r'(?P<dir_path>(.*/)*)(?P<filename>.*\.*)?$', 'browse', name='pootle-tp-browse'), )
gpl-3.0
wolfiex/AlarmPi
gcal_quickstart.py
1
2718
from __future__ import print_function import httplib2 import os from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage import datetime try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying these scopes, delete your previously saved credentials # at ~/.credentials/calendar-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/calendar' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Google Calendar API Python Quickstart' def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def main(): """Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') eventsResult = service.events().list( calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = eventsResult.get('items', []) if not events: print('No upcoming events found.') for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) #add event: #https://developers.google.com/api-client-library/python/ if __name__ == '__main__': main()
mit
gushedaoren/django-rest-auth
rest_auth/app_settings.py
29
1322
from django.conf import settings from rest_auth.serializers import ( TokenSerializer as DefaultTokenSerializer, UserDetailsSerializer as DefaultUserDetailsSerializer, LoginSerializer as DefaultLoginSerializer, PasswordResetSerializer as DefaultPasswordResetSerializer, PasswordResetConfirmSerializer as DefaultPasswordResetConfirmSerializer, PasswordChangeSerializer as DefaultPasswordChangeSerializer) from .utils import import_callable serializers = getattr(settings, 'REST_AUTH_SERIALIZERS', {}) TokenSerializer = import_callable( serializers.get('TOKEN_SERIALIZER', DefaultTokenSerializer)) UserDetailsSerializer = import_callable( serializers.get('USER_DETAILS_SERIALIZER', DefaultUserDetailsSerializer) ) LoginSerializer = import_callable( serializers.get('LOGIN_SERIALIZER', DefaultLoginSerializer) ) PasswordResetSerializer = import_callable( serializers.get( 'PASSWORD_RESET_SERIALIZER', DefaultPasswordResetSerializer ) ) PasswordResetConfirmSerializer = import_callable( serializers.get( 'PASSWORD_RESET_CONFIRM_SERIALIZER', DefaultPasswordResetConfirmSerializer ) ) PasswordChangeSerializer = import_callable( serializers.get( 'PASSWORD_CHANGE_SERIALIZER', DefaultPasswordChangeSerializer ) )
mit
robweber/maraschino
lib/sqlalchemy/log.py
39
6820
# sqlalchemy/log.py # Copyright (C) 2006-2011 the SQLAlchemy authors and contributors <see AUTHORS file> # Includes alterations by Vinay Sajip [email protected] # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Logging control and utilities. Control of logging for SA can be performed from the regular python logging module. The regular dotted module namespace is used, starting at 'sqlalchemy'. For class-level logging, the class name is appended. The "echo" keyword parameter, available on SQLA :class:`.Engine` and :class:`.Pool` objects, corresponds to a logger specific to that instance only. """ import logging import sys from sqlalchemy import util # set initial level to WARN. This so that # log statements don't occur in the absense of explicit # logging being enabled for 'sqlalchemy'. rootlogger = logging.getLogger('sqlalchemy') if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN) def _add_default_handler(logger): handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s %(name)s %(message)s')) logger.addHandler(handler) _logged_classes = set() def class_logger(cls, enable=False): logger = logging.getLogger(cls.__module__ + "." + cls.__name__) if enable == 'debug': logger.setLevel(logging.DEBUG) elif enable == 'info': logger.setLevel(logging.INFO) cls._should_log_debug = lambda self: logger.isEnabledFor(logging.DEBUG) cls._should_log_info = lambda self: logger.isEnabledFor(logging.INFO) cls.logger = logger _logged_classes.add(cls) class Identified(object): logging_name = None def _should_log_debug(self): return self.logger.isEnabledFor(logging.DEBUG) def _should_log_info(self): return self.logger.isEnabledFor(logging.INFO) class InstanceLogger(object): """A logger adapter (wrapper) for :class:`.Identified` subclasses. This allows multiple instances (e.g. Engine or Pool instances) to share a logger, but have its verbosity controlled on a per-instance basis. The basic functionality is to return a logging level which is based on an instance's echo setting. Default implementation is: 'debug' -> logging.DEBUG True -> logging.INFO False -> Effective level of underlying logger (logging.WARNING by default) None -> same as False """ # Map echo settings to logger levels _echo_map = { None: logging.NOTSET, False: logging.NOTSET, True: logging.INFO, 'debug': logging.DEBUG, } def __init__(self, echo, name): self.echo = echo self.logger = logging.getLogger(name) # if echo flag is enabled and no handlers, # add a handler to the list if self._echo_map[echo] <= logging.INFO \ and not self.logger.handlers: _add_default_handler(self.logger) # # Boilerplate convenience methods # def debug(self, msg, *args, **kwargs): """Delegate a debug call to the underlying logger.""" self.log(logging.DEBUG, msg, *args, **kwargs) def info(self, msg, *args, **kwargs): """Delegate an info call to the underlying logger.""" self.log(logging.INFO, msg, *args, **kwargs) def warning(self, msg, *args, **kwargs): """Delegate a warning call to the underlying logger.""" self.log(logging.WARNING, msg, *args, **kwargs) warn = warning def error(self, msg, *args, **kwargs): """ Delegate an error call to the underlying logger. """ self.log(logging.ERROR, msg, *args, **kwargs) def exception(self, msg, *args, **kwargs): """Delegate an exception call to the underlying logger.""" kwargs["exc_info"] = 1 self.log(logging.ERROR, msg, *args, **kwargs) def critical(self, msg, *args, **kwargs): """Delegate a critical call to the underlying logger.""" self.log(logging.CRITICAL, msg, *args, **kwargs) def log(self, level, msg, *args, **kwargs): """Delegate a log call to the underlying logger. The level here is determined by the echo flag as well as that of the underlying logger, and logger._log() is called directly. """ # inline the logic from isEnabledFor(), # getEffectiveLevel(), to avoid overhead. if self.logger.manager.disable >= level: return selected_level = self._echo_map[self.echo] if selected_level == logging.NOTSET: selected_level = self.logger.getEffectiveLevel() if level >= selected_level: self.logger._log(level, msg, args, **kwargs) def isEnabledFor(self, level): """Is this logger enabled for level 'level'?""" if self.logger.manager.disable >= level: return False return level >= self.getEffectiveLevel() def getEffectiveLevel(self): """What's the effective level for this logger?""" level = self._echo_map[self.echo] if level == logging.NOTSET: level = self.logger.getEffectiveLevel() return level def instance_logger(instance, echoflag=None): """create a logger for an instance that implements :class:`.Identified`.""" if instance.logging_name: name = "%s.%s.%s" % (instance.__class__.__module__, instance.__class__.__name__, instance.logging_name) else: name = "%s.%s" % (instance.__class__.__module__, instance.__class__.__name__) instance._echo = echoflag if echoflag in (False, None): # if no echo setting or False, return a Logger directly, # avoiding overhead of filtering logger = logging.getLogger(name) else: # if a specified echo flag, return an EchoLogger, # which checks the flag, overrides normal log # levels by calling logger._log() logger = InstanceLogger(echoflag, name) instance.logger = logger class echo_property(object): __doc__ = """\ When ``True``, enable log output for this element. This has the effect of setting the Python logging level for the namespace of this element's class and object reference. A value of boolean ``True`` indicates that the loglevel ``logging.INFO`` will be set for the logger, whereas the string value ``debug`` will set the loglevel to ``logging.DEBUG``. """ def __get__(self, instance, owner): if instance is None: return self else: return instance._echo def __set__(self, instance, value): instance_logger(instance, echoflag=value)
mit
nhenezi/kuma
vendor/packages/translate-toolkit/translate/convert/php2po.py
7
4751
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2002-2006 Zuza Software Foundation # # This file is part of translate. # # translate 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. # # translate 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 translate; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """convert PHP localization files to Gettext PO localization files See: http://translate.sourceforge.net/wiki/toolkit/php2po for examples and usage instructions """ import sys from translate.storage import po from translate.storage import php class php2po: """convert a .php file to a .po file for handling the translation...""" def convertstore(self, inputstore, duplicatestyle="msgctxt"): """converts a .php file to a .po file...""" outputstore = po.pofile() outputheader = outputstore.init_headers(charset="UTF-8", encoding="8bit") outputheader.addnote("extracted from %s" % inputstore.filename, "developer") for inputunit in inputstore.units: outputunit = self.convertunit(inputunit, "developer") if outputunit is not None: outputstore.addunit(outputunit) outputstore.removeduplicates(duplicatestyle) return outputstore def mergestore(self, templatestore, inputstore, blankmsgstr=False, duplicatestyle="msgctxt"): """converts two .properties files to a .po file...""" outputstore = po.pofile() outputheader = outputstore.init_headers(charset="UTF-8", encoding="8bit") outputheader.addnote("extracted from %s, %s" % (templatestore.filename, inputstore.filename), "developer") inputstore.makeindex() # loop through the original file, looking at units one by one for templateunit in templatestore.units: outputunit = self.convertunit(templateunit, "developer") # try and find a translation of the same name... if templateunit.name in inputstore.locationindex: translatedinputunit = inputstore.locationindex[templateunit.name] # Need to check that this comment is not a copy of the developer comments translatedoutputunit = self.convertunit(translatedinputunit, "translator") else: translatedoutputunit = None # if we have a valid po unit, get the translation and add it... if outputunit is not None: if translatedoutputunit is not None and not blankmsgstr: outputunit.target = translatedoutputunit.source outputstore.addunit(outputunit) elif translatedoutputunit is not None: print >> sys.stderr, "error converting original properties definition %s" % templateunit.name outputstore.removeduplicates(duplicatestyle) return outputstore def convertunit(self, inputunit, origin): """Converts a .php unit to a .po unit""" outputunit = po.pounit(encoding="UTF-8") outputunit.addnote(inputunit.getnotes(origin), origin) outputunit.addlocation("".join(inputunit.getlocations())) outputunit.source = inputunit.source outputunit.target = "" return outputunit def convertphp(inputfile, outputfile, templatefile, pot=False, duplicatestyle="msgctxt"): """reads in inputfile using php, converts using php2po, writes to outputfile""" inputstore = php.phpfile(inputfile) convertor = php2po() if templatefile is None: outputstore = convertor.convertstore(inputstore, duplicatestyle=duplicatestyle) else: templatestore = php.phpfile(templatefile) outputstore = convertor.mergestore(templatestore, inputstore, blankmsgstr=pot, duplicatestyle=duplicatestyle) if outputstore.isempty(): return 0 outputfile.write(str(outputstore)) return 1 def main(argv=None): from translate.convert import convert formats = {"php": ("po", convertphp), ("php", "php"): ("po", convertphp)} parser = convert.ConvertOptionParser(formats, usetemplates=True, usepots=True, description=__doc__) parser.add_duplicates_option() parser.passthrough.append("pot") parser.run(argv) if __name__ == '__main__': main()
mpl-2.0
xzturn/tensorflow
tensorflow/lite/testing/op_tests/nearest_upsample.py
17
3155
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Test configs for nearest upsample.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf from tensorflow.lite.testing.zip_test_utils import create_tensor_data from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests from tensorflow.lite.testing.zip_test_utils import register_make_test_function @register_make_test_function() def make_nearest_upsample_tests(options): """Make a set of tests to do nearest_upsample.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[1, 10, 10, 64], [3, 8, 32]], "scale_n_axis": [([2, 2], [1, 2]), ([3, 4], [1, 2]), ([3], [1])], "dtype": [tf.float32, tf.int32], }] def new_shape_for_upsample(original_shape, scales, axis): """Calculate the input shape & ones shape, also the upsample shape.""" input_new_shape = [] ones_new_shape = [] upsample_new_shape = [] j = 0 for i in range(len(original_shape)): input_new_shape.append(original_shape[i]) ones_new_shape.append(1) if j < len(scales) and axis[j] == i: input_new_shape.append(1) ones_new_shape.append(scales[j]) upsample_new_shape.append(original_shape[i] * scales[j]) j += 1 else: upsample_new_shape.append(original_shape[i]) return input_new_shape, ones_new_shape, upsample_new_shape def build_graph(parameters): """Build the nearest upsample testing graph.""" input_shape = parameters["input_shape"] input_tensor = tf.compat.v1.placeholder( dtype=parameters["dtype"], name="input", shape=input_shape) scales, axis = parameters["scale_n_axis"] input_new_shape, ones_new_shape, new_shape = new_shape_for_upsample( input_shape, scales, axis) out = tf.compat.v1.reshape(input_tensor, input_new_shape) * tf.compat.v1.ones( ones_new_shape, dtype=parameters["dtype"]) out = tf.compat.v1.reshape(out, new_shape) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( parameters["dtype"], parameters["input_shape"], min_value=-10, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs)
apache-2.0
OCA/l10n-usa
account_banking_ach_direct_debit/models/account_payment_order.py
1
2575
# Copyright 2018 Thinkwell Designs <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models, _ class AccountPaymentOrder(models.Model): _inherit = 'account.payment.order' @api.multi def generate_payment_file(self): """ Creates the ACH Direct Debit file by calling generate_ach_file in countinghouse_ach_base """ self.ensure_one() if self.payment_method_id.code == 'ACH-In': return self.generate_ach_file() return super(AccountPaymentOrder, self).generate_payment_file() @api.multi def generated2uploaded(self): """Write 'last debit date' on mandates Set mandates from first to recurring Set oneoff mandates to expired """ # I call super() BEFORE updating the sequence_type # from first to recurring, so that the account move # is generated BEFORE, which will allow the split # of the account move per sequence_type res = super(AccountPaymentOrder, self).generated2uploaded() mandate = self.env['account.banking.mandate'] for order in self: to_expire_mandates = first_mandates = all_mandates = mandate for bank_line in order.bank_line_ids: if bank_line.mandate_id in all_mandates: continue all_mandates += bank_line.mandate_id if bank_line.mandate_id.type == 'oneoff': to_expire_mandates += bank_line.mandate_id elif bank_line.mandate_id.type == 'recurrent': seq_type = bank_line.mandate_id.recurrent_sequence_type if seq_type == 'final': to_expire_mandates += bank_line.mandate_id elif seq_type == 'first': first_mandates += bank_line.mandate_id all_mandates.write({'last_debit_date': order.date_generated}) to_expire_mandates.write({'state': 'expired'}) first_mandates.write({'recurrent_sequence_type': 'recurring'}) for first_mandate in first_mandates: first_mandate.message_post(body=_( "Automatically switched from <b>First</b> to " "<b>Recurring</b> when the debit order " "<a href=# data-oe-model=account.payment.order " "data-oe-id=%d>%s</a> has been marked as uploaded.") % (order.id, order.name)) return res
agpl-3.0
johndpope/tensorflow
tensorflow/contrib/learn/python/learn/basic_session_run_hooks.py
118
1403
# 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. # ============================================================================== """Some common SessionRunHook classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.training import basic_session_run_hooks # pylint: disable=invalid-name LoggingTensorHook = basic_session_run_hooks.LoggingTensorHook StopAtStepHook = basic_session_run_hooks.StopAtStepHook CheckpointSaverHook = basic_session_run_hooks.CheckpointSaverHook StepCounterHook = basic_session_run_hooks.StepCounterHook NanLossDuringTrainingError = basic_session_run_hooks.NanLossDuringTrainingError NanTensorHook = basic_session_run_hooks.NanTensorHook SummarySaverHook = basic_session_run_hooks.SummarySaverHook # pylint: enable=invalid-name
apache-2.0
MartinNowak/mongo-connector
tests/util.py
69
1175
# Copyright 2013-2014 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for mongo-connector tests. There are no actual tests in here. """ import time def wait_for(condition, max_tries=60): """Wait for a condition to be true up to a maximum number of tries """ while not condition() and max_tries > 1: time.sleep(1) max_tries -= 1 return condition() def assert_soon(condition, message=None, max_tries=60): """Assert that a condition eventually evaluates to True after at most max_tries number of attempts """ if not wait_for(condition, max_tries=max_tries): raise AssertionError(message or "")
apache-2.0
bnkr/servequnit
tests/http.py
2
8919
import os, contextlib from tempfile import NamedTemporaryFile from mock import patch, Mock from unittest import TestCase from six.moves import urllib from servequnit.server import ReusableServer, HandlerSettings from servequnit.http import QunitRequestHandler from servequnit.factory import js_server from ._util import MockSocket, dump_page class QunitRequestHandlerTestCase(TestCase): def _make_request(self, url): """There really doesn't seem to be a way to create HTTP requests as strings...""" request = MockSocket() request.queue_recv("GET {url} HTTP/1.1".format(url=url)) return request def _make_settings(self, test_root=None, read=None, scripts=None, styles=None): # TODO: # Use a real server settings object. It's simple enough that there's # really not need to mock it. server = Mock(spec=ReusableServer) settings = Mock(spec=HandlerSettings) test_root = test_root or "/tmp" settings.test_root.return_value = test_root settings.bound_content.return_value = read settings.scripts.return_value = scripts or [] settings.styles.return_value = styles or [] server.get_handler_settings.return_value = settings return server @contextlib.contextmanager def _in_dir(self, where): old = os.getcwd() os.chdir(where) try: yield finally: os.chdir(old) def _make_handler(self, request, server=None): client_address = ("localhost", 42) server = server or self._make_settings() handler = QunitRequestHandler(request, client_address, server=server) return handler def _get_content(self, request): """Needs care because py2 does each line in an individual write whereas py3 does not.""" writes = request.files[-1].writes transmission = b"".join(writes) data = transmission.index(b'\r\n\r\n') + 4 return transmission[data:].decode("utf-8") def test_handler_works_with_socket_server(self): """Damn it is hard to create a fake server... so we'd better just check it works with the real one.""" with js_server(handler_factory=QunitRequestHandler) as server: dump_page(server.url, "/test/") def test_root_404_lists_prefixes(self): request = self._make_request("/asdasd") handler = self._make_handler(request) self.assertEqual(b"HTTP/1.0 404 Not Found\r\n", request.files[-1].writes[0]) last_line = request.files[-1].writes[-1] paths = [path for (path, _) in handler.get_handlers()] message = "404: '/asdasd': prefix must be one of {0!r}\n".format(paths) self.assertEqual(message, last_line) def test_static_response_serves_from_pwd(self): basename = os.path.basename(__file__) request = self._make_request("/static/{0}".format(basename)) with self._in_dir(os.path.dirname(__file__)): self._make_handler(request) self.assertEqual(b"HTTP/1.0 200 OK\r\n", request.files[-1].writes[0]) class_definition = b"class self.__class__.__name__(TestCase)" output = request.files[-1].writes self.assertTrue(any((class_definition in line) for line in output)) def test_static_respnds_404_when_file_missing(self): assert not os.path.exists("pants") request = self._make_request("/static/pants") self._make_handler(request) self.assertEqual(b"HTTP/1.0 404 Not Found\r\n", request.files[-1].writes[0]) last_line = request.files[-1].writes[-1] message = "404: '/static/pants' (maps to '{0}'): does not exist\n" fs_name = os.path.join(os.getcwd(), "pants") self.assertEquals(message.format(fs_name), last_line) def test_runner_response_displays_html(self): with NamedTemporaryFile() as io: io.write(b"summat") io.flush() settings = self._make_settings(test_root=os.path.dirname(io.name)) request = self._make_request("/test/{0}".format(os.path.basename(io.name))) self._make_handler(request, settings) self.assertEqual(b"HTTP/1.0 200 OK\r\n", request.files[-1].writes[0]) document = self._get_content(request) self.assertTrue('<html' in document) self.assertTrue('src="/unit/{0}"'.format(os.path.basename(io.name)) in document) self.assertTrue('</html>' in document) def test_runner_handles_no_test(self): settings = self._make_settings(test_root=None) settings.get_handler_settings.return_value.test_root.return_value = None request = self._make_request("/test/test/data/passes.js") self._make_handler(request, settings) self.assertEqual(b"HTTP/1.0 404 Not Found\r\n", request.files[-1].writes[0]) self.assertTrue("no test root" in request.files[-1].writes[-1]) def test_runner_reponds_404_if_test_case_missing(self): request = self._make_request("/test/blah.js") settings = self._make_settings(test_root="/tmp/") self._make_handler(request, settings) self.assertEqual(b"HTTP/1.0 404 Not Found\r\n", request.files[-1].writes[0]) message = "404: '/test/blah.js': test case '/unit/blah.js' (maps to " \ "'/tmp/blah.js'): does not exist\n" last_line = request.files[-1].writes[-1] self.assertEquals(message, last_line) def test_runner_inserts_libraries(self): request = self._make_request("/test/") settings = self._make_settings(scripts=["/static/a", '/blah/b']) self._make_handler(request, settings) document = self._get_content(request) self.assertTrue('src="/static/a"' in document) self.assertTrue('src="/blah/b"' in document) def test_runner_inserts_styles(self): request = self._make_request("/test/") settings = self._make_settings(styles=['/arbitrary_stuff/here'],) self._make_handler(request, settings) html = '<link rel="stylesheet" type="text/css" ' \ 'href="/arbitrary_stuff/here">' content = b"".join(request.files[-1].writes).decode("utf-8") self.assertTrue(html in content) def test_unit_test_js_responds_404_on_missing_test(self): request = self._make_request("/unit/blah.js") settings = self._make_settings(test_root="/tmp/") self._make_handler(request, settings) self.assertEqual(b"HTTP/1.0 404 Not Found\r\n", request.files[-1].writes[0]) message = "404: '/unit/blah.js' (maps to '/tmp/blah.js'): does not exist\n" last_line = request.files[-1].writes[-1] self.assertEquals(message, last_line) def test_unit_test_response_from_filesytem(self): with NamedTemporaryFile() as io: file_content = b"some stuff\n" io.write(file_content) io.flush() request = self._make_request("/unit/" + os.path.basename(io.name)) settings = self._make_settings(test_root=os.path.dirname(io.name)) self._make_handler(request, settings) last_line = request.files[-1].writes[-1] self.assertEquals(file_content, last_line) def test_bound_content_served_from_arbitary_path(self): with NamedTemporaryFile() as io: file_data = b"some stuff\n" io.write(file_data) io.flush() request = self._make_request("/read/pants") settings = self._make_settings(read=[('pants', io.name)]) self._make_handler(request, settings) last_line = request.files[-1].writes[-1] self.assertEquals(file_data, last_line) def test_bound_is_404_for_non_existing_path(self): request = self._make_request("/read/pants") settings = self._make_settings(read=[('pants', "/tmp.asdhasdas")]) self._make_handler(request, settings) message = "404: '/read/pants' (maps to '/tmp.asdhasdas'): does not exist\n" last_line = request.files[-1].writes[-1] self.assertEquals(message, last_line) def test_bound_is_404_for_non_existing_name(self): request = self._make_request("/read/pants") settings = self._make_settings() self._make_handler(request, settings) message = "404: '/read/pants': no file bound for 'pants'\n" last_line = request.files[-1].writes[-1] self.assertEquals(message, last_line) def test_favicon_respons_with_404(self): settings = self._make_settings() request = self._make_request("/favicon.ico") self._make_handler(request, settings) message = "No favicon." last_line = request.files[-1].writes[-1] self.assertEquals(message, last_line)
mit
nprimmer/rubik
rubik.py
1
3059
#!/usr/bin/env python from colorama import init init() from colorama import Fore, Back, Style face_size = 5 indent = " " * face_size separator = Back.RESET + " " line_sep = " " * ((face_size * 2) + 2) current_face = 'front' base_cube = {'top':Back.WHITE,'bottom':Back.GREEN,'left':Back.CYAN,'right':Back.MAGENTA,'front':Back.BLUE,'back':Back.RED} def generate_cube(): cube = {} for face in ['top','bottom','left','right','front','back']: color = base_cube[face] cube[face] = {} for square in ['one','two','three','four','five','six','seven','eight','nine']: cube[face][square] = color return cube def output_first_row(cube): for i in range(1,face_size): print(indent + cube[current_face]['one'] + indent + separator + cube[current_face]['two'] + indent + separator + cube[current_face]['three'] + indent + Back.RESET) print line_sep def output_second_row(cube): for i in range(1,face_size): print(indent + cube[current_face]['four'] + indent + separator + cube[current_face]['five'] + indent + separator + cube[current_face]['six'] + indent + Back.RESET) print line_sep def output_third_row(cube): for i in range(1,face_size): print(indent + cube[current_face]['seven'] + indent + separator + cube[current_face]['eight'] + indent + separator + cube[current_face]['nine'] + indent + Back.RESET) print line_sep def output_cube(cube): output_first_row(cube) output_second_row(cube) output_third_row(cube) def top(dir, cube): assoc ={ 'three':'one', 'six':'two', 'nine':'three', 'eight':'six', 'seven':'nine', 'four':'eight', 'one':'seven', 'two':'four'} newtop = {} newleft = {} newright = {} newback = {} newfront = {} newbottom = cube['bottom'] if dir == 'left': for key,value in assoc.iteritems(): newtop[key] = cube['top'][assoc[value]] for i in ['one','two','three']: newleft[i] = cube['back'][i] newback[i] = cube['right'][i] newfront[i] = cube['left'][i] newright[i] = cube['front'][i] for i in ['four','five','six','seven','eight','nine']: newleft[i] = cube['left'][i] newright[i] = cube['right'][i] newback[i] = cube['back'][i] newfront[i] = cube['front'][i] if dir == 'right': for key,value in assoc.iteritems(): newtop[value] = cube['top'][assoc[key]] for i in ['one','two','three']: newleft[i] = cube['front'][i] newright[i] = cube['back'][i] newback[i] = cube['left'][i] newfront[i] = cube['right'][i] for i in ['four','five','six','seven','eight','nine']: newleft[i] = cube['left'][i] newright[i] = cube['right'][i] newfront[i] = cube['front'][i] newback[i] = cube['back'][i] cube = {'top':newtop, 'left': newleft, 'right': newright, 'back': newback, 'front': newfront, 'bottom': newbottom } return cube def bottom(dir,cube): assoc = { cube = generate_cube() output_cube(cube) cube = top('left',cube) output_cube(cube) cube = top('left',cube) output_cube(cube)
gpl-2.0
consbio/seedsource-core
seedsource_core/django/seedsource/utils.py
1
1315
import os from django.conf import settings from ncdjango.models import Service from netCDF4 import Dataset from .models import Region def get_elevation_at_point(point): try: region = get_regions_for_point(point)[0] except IndexError: return None service = Service.objects.get(name='{}_dem'.format(region.name)) variable = service.variable_set.all().get() with Dataset(os.path.join(settings.NC_SERVICE_DATA_ROOT, service.data_path)) as ds: data = ds.variables[variable.variable] cell_size = ( float(variable.full_extent.width) / data.shape[1], float(variable.full_extent.height) / data.shape[0] ) cell_index = [ int(float(point.x - variable.full_extent.xmin) / cell_size[0]), int(float(point.y - variable.full_extent.ymin) / cell_size[1]) ] y_increasing = data[0][1] > data[0][0] if not y_increasing: cell_index[1] = data.shape[0] - cell_index[1] - 1 try: return data[cell_index[1]][cell_index[0]] except IndexError: return None def get_regions_for_point(point): regions = Region.objects.filter(polygons__intersects=point) return sorted(list(regions), key=lambda r: point.distance(r.polygons.centroid))
bsd-3-clause
bowang/tensorflow
tensorflow/python/keras/_impl/keras/engine/training_test.py
13
52417
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for training routines.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.keras._impl import keras from tensorflow.python.keras._impl.keras import testing_utils from tensorflow.python.keras._impl.keras.engine.training import _weighted_masked_objective from tensorflow.python.platform import test class TrainingTest(test.TestCase): def test_fit_on_arrays(self): with self.test_session(): a = keras.layers.Input(shape=(3,), name='input_a') b = keras.layers.Input(shape=(3,), name='input_b') dense = keras.layers.Dense(4, name='dense') c = dense(a) d = dense(b) e = keras.layers.Dropout(0.5, name='dropout')(c) model = keras.models.Model([a, b], [d, e]) optimizer = 'rmsprop' loss = 'mse' loss_weights = [1., 0.5] metrics = ['mae'] model.compile(optimizer, loss, metrics=metrics, loss_weights=loss_weights) input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) output_d_np = np.random.random((10, 4)) output_e_np = np.random.random((10, 4)) # Test fit at different verbosity model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], epochs=1, batch_size=5, verbose=0) model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], epochs=1, batch_size=5, verbose=1) model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], epochs=2, batch_size=5, verbose=2) model.train_on_batch([input_a_np, input_b_np], [output_d_np, output_e_np]) # Test with validation data model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], validation_data=([input_a_np, input_b_np], [output_d_np, output_e_np]), epochs=1, batch_size=5, verbose=0) model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], validation_data=([input_a_np, input_b_np], [output_d_np, output_e_np]), epochs=2, batch_size=5, verbose=1) model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], validation_data=([input_a_np, input_b_np], [output_d_np, output_e_np]), epochs=2, batch_size=5, verbose=2) # Test with validation split model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], epochs=2, batch_size=5, verbose=0, validation_split=0.2) # Test with dictionary inputs model.fit( { 'input_a': input_a_np, 'input_b': input_b_np }, {'dense': output_d_np, 'dropout': output_e_np}, epochs=1, batch_size=5, verbose=0) model.fit( { 'input_a': input_a_np, 'input_b': input_b_np }, {'dense': output_d_np, 'dropout': output_e_np}, epochs=1, batch_size=5, verbose=1) model.fit( { 'input_a': input_a_np, 'input_b': input_b_np }, {'dense': output_d_np, 'dropout': output_e_np}, validation_data=({ 'input_a': input_a_np, 'input_b': input_b_np }, { 'dense': output_d_np, 'dropout': output_e_np }), epochs=1, batch_size=5, verbose=0) model.train_on_batch({ 'input_a': input_a_np, 'input_b': input_b_np }, {'dense': output_d_np, 'dropout': output_e_np}) # Test with lists for loss, metrics loss = ['mae', 'mse'] metrics = ['acc', 'mae'] model.compile(optimizer, loss, metrics=metrics) model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], epochs=1, batch_size=5, verbose=0) # Test with dictionaries for loss, metrics, loss weights loss = {'dense': 'mse', 'dropout': 'mae'} loss_weights = {'dense': 1., 'dropout': 0.5} metrics = {'dense': 'mse', 'dropout': 'mae'} model.compile(optimizer, loss, metrics=metrics, loss_weights=loss_weights) model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], epochs=1, batch_size=5, verbose=0) # Invalid use cases with self.assertRaises(ValueError): model.train_on_batch({'input_a': input_a_np}, [output_d_np, output_e_np]) with self.assertRaises(TypeError): model.fit( [input_a_np, input_b_np], [output_d_np, output_e_np], epochs=1, validation_data=([input_a_np, input_b_np], 0, 0), verbose=0) with self.assertRaises(ValueError): model.train_on_batch([input_a_np], [output_d_np, output_e_np]) with self.assertRaises(TypeError): model.train_on_batch(1, [output_d_np, output_e_np]) with self.assertRaises(ValueError): model.train_on_batch(input_a_np, [output_d_np, output_e_np]) with self.assertRaises(ValueError): bad_input = np.random.random((11, 3)) model.train_on_batch([bad_input, input_b_np], [output_d_np, output_e_np]) with self.assertRaises(ValueError): bad_target = np.random.random((11, 4)) model.train_on_batch([input_a_np, input_b_np], [bad_target, output_e_np]) # Build single-input model x = keras.layers.Input(shape=(3,), name='input_a') y = keras.layers.Dense(4)(x) model = keras.models.Model(x, y) model.compile(optimizer='rmsprop', loss='mse') # This will work model.fit([input_a_np], output_d_np, epochs=1) with self.assertRaises(ValueError): model.fit([input_a_np, input_a_np], output_d_np, epochs=1) def test_evaluate_predict_on_arrays(self): with self.test_session(): a = keras.layers.Input(shape=(3,), name='input_a') b = keras.layers.Input(shape=(3,), name='input_b') dense = keras.layers.Dense(4, name='dense') c = dense(a) d = dense(b) e = keras.layers.Dropout(0.5, name='dropout')(c) model = keras.models.Model([a, b], [d, e]) optimizer = 'rmsprop' loss = 'mse' loss_weights = [1., 0.5] metrics = ['mae'] model.compile( optimizer, loss, metrics=metrics, loss_weights=loss_weights, sample_weight_mode=None) input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) output_d_np = np.random.random((10, 4)) output_e_np = np.random.random((10, 4)) # Test evaluate at different verbosity out = model.evaluate( [input_a_np, input_b_np], [output_d_np, output_e_np], batch_size=5, verbose=0) self.assertEqual(len(out), 5) out = model.evaluate( [input_a_np, input_b_np], [output_d_np, output_e_np], batch_size=5, verbose=1) self.assertEqual(len(out), 5) out = model.evaluate( [input_a_np, input_b_np], [output_d_np, output_e_np], batch_size=5, verbose=2) self.assertEqual(len(out), 5) out = model.test_on_batch([input_a_np, input_b_np], [output_d_np, output_e_np]) self.assertEqual(len(out), 5) # Test evaluate with dictionary inputs model.evaluate( { 'input_a': input_a_np, 'input_b': input_b_np }, {'dense': output_d_np, 'dropout': output_e_np}, batch_size=5, verbose=0) model.evaluate( { 'input_a': input_a_np, 'input_b': input_b_np }, {'dense': output_d_np, 'dropout': output_e_np}, batch_size=5, verbose=1) # Test predict out = model.predict([input_a_np, input_b_np], batch_size=5) self.assertEqual(len(out), 2) out = model.predict({'input_a': input_a_np, 'input_b': input_b_np}) self.assertEqual(len(out), 2) out = model.predict_on_batch({ 'input_a': input_a_np, 'input_b': input_b_np }) self.assertEqual(len(out), 2) def test_invalid_loss_or_metrics(self): num_classes = 5 train_samples = 1000 test_samples = 1000 input_dim = 5 with self.test_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(10, input_shape=(input_dim,))) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Dense(num_classes)) model.add(keras.layers.Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') np.random.seed(1337) (x_train, y_train), (_, _) = testing_utils.get_test_data( train_samples=train_samples, test_samples=test_samples, input_shape=(input_dim,), num_classes=num_classes) with self.assertRaises(ValueError): model.fit(x_train, y_train) with self.assertRaises(ValueError): model.fit(x_train, np.concatenate([y_train, y_train], axis=-1)) with self.assertRaises(TypeError): model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=set(0)) with self.assertRaises(ValueError): model.compile(loss=None, optimizer='rmsprop') class LossWeightingTest(test.TestCase): def test_class_weights(self): num_classes = 5 batch_size = 5 epochs = 5 weighted_class = 3 train_samples = 1000 test_samples = 1000 input_dim = 5 with self.test_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(10, input_shape=(input_dim,))) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Dense(num_classes)) model.add(keras.layers.Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=train_samples, test_samples=test_samples, input_shape=(input_dim,), num_classes=num_classes) int_y_test = y_test.copy() int_y_train = y_train.copy() # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) test_ids = np.where(int_y_test == np.array(weighted_class))[0] class_weight = dict([(i, 1.) for i in range(num_classes)]) class_weight[weighted_class] = 2. sample_weight = np.ones((y_train.shape[0])) sample_weight[int_y_train == weighted_class] = 2. model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs // 3, verbose=0, class_weight=class_weight, validation_data=(x_train, y_train, sample_weight)) model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs // 2, verbose=0, class_weight=class_weight) model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs // 2, verbose=0, class_weight=class_weight, validation_split=0.1) model.train_on_batch( x_train[:batch_size], y_train[:batch_size], class_weight=class_weight) ref_score = model.evaluate(x_test, y_test, verbose=0) score = model.evaluate( x_test[test_ids, :], y_test[test_ids, :], verbose=0) self.assertLess(score, ref_score) def test_sample_weights(self): num_classes = 5 batch_size = 5 epochs = 5 weighted_class = 3 train_samples = 1000 test_samples = 1000 input_dim = 5 with self.test_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(10, input_shape=(input_dim,))) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Dense(num_classes)) model.add(keras.layers.Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=train_samples, test_samples=test_samples, input_shape=(input_dim,), num_classes=num_classes) int_y_test = y_test.copy() int_y_train = y_train.copy() # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) test_ids = np.where(int_y_test == np.array(weighted_class))[0] class_weight = dict([(i, 1.) for i in range(num_classes)]) class_weight[weighted_class] = 2. sample_weight = np.ones((y_train.shape[0])) sample_weight[int_y_train == weighted_class] = 2. model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs // 3, verbose=0, sample_weight=sample_weight) model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs // 3, verbose=0, sample_weight=sample_weight, validation_split=0.1) model.train_on_batch( x_train[:batch_size], y_train[:batch_size], sample_weight=sample_weight[:batch_size]) model.test_on_batch( x_train[:batch_size], y_train[:batch_size], sample_weight=sample_weight[:batch_size]) ref_score = model.evaluate(x_test, y_test, verbose=0) score = model.evaluate( x_test[test_ids, :], y_test[test_ids, :], verbose=0) self.assertLess(score, ref_score) def test_temporal_sample_weights(self): num_classes = 5 batch_size = 5 epochs = 5 weighted_class = 3 train_samples = 1000 test_samples = 1000 input_dim = 5 timesteps = 3 with self.test_session(): model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.Dense(num_classes), input_shape=(timesteps, input_dim))) model.add(keras.layers.Activation('softmax')) np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=train_samples, test_samples=test_samples, input_shape=(input_dim,), num_classes=num_classes) int_y_test = y_test.copy() int_y_train = y_train.copy() # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) test_ids = np.where(int_y_test == np.array(weighted_class))[0] class_weight = dict([(i, 1.) for i in range(num_classes)]) class_weight[weighted_class] = 2. sample_weight = np.ones((y_train.shape[0])) sample_weight[int_y_train == weighted_class] = 2. temporal_x_train = np.reshape(x_train, (len(x_train), 1, x_train.shape[1])) temporal_x_train = np.repeat(temporal_x_train, timesteps, axis=1) temporal_x_test = np.reshape(x_test, (len(x_test), 1, x_test.shape[1])) temporal_x_test = np.repeat(temporal_x_test, timesteps, axis=1) temporal_y_train = np.reshape(y_train, (len(y_train), 1, y_train.shape[1])) temporal_y_train = np.repeat(temporal_y_train, timesteps, axis=1) temporal_y_test = np.reshape(y_test, (len(y_test), 1, y_test.shape[1])) temporal_y_test = np.repeat(temporal_y_test, timesteps, axis=1) temporal_sample_weight = np.reshape(sample_weight, (len(sample_weight), 1)) temporal_sample_weight = np.repeat( temporal_sample_weight, timesteps, axis=1) model.compile( loss='binary_crossentropy', optimizer='rmsprop', sample_weight_mode='temporal') model.fit( temporal_x_train, temporal_y_train, batch_size=batch_size, epochs=epochs // 3, verbose=0, sample_weight=temporal_sample_weight) model.fit( temporal_x_train, temporal_y_train, batch_size=batch_size, epochs=epochs // 3, verbose=0, sample_weight=temporal_sample_weight, validation_split=0.1) model.train_on_batch( temporal_x_train[:batch_size], temporal_y_train[:batch_size], sample_weight=temporal_sample_weight[:batch_size]) model.test_on_batch( temporal_x_train[:batch_size], temporal_y_train[:batch_size], sample_weight=temporal_sample_weight[:batch_size]) ref_score = model.evaluate(temporal_x_test, temporal_y_test, verbose=0) score = model.evaluate( temporal_x_test[test_ids], temporal_y_test[test_ids], verbose=0) self.assertLess(score, ref_score) def test_class_weight_invalid_use_case(self): num_classes = 5 train_samples = 1000 test_samples = 1000 input_dim = 5 timesteps = 3 with self.test_session(): model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.Dense(num_classes), input_shape=(timesteps, input_dim))) model.add(keras.layers.Activation('softmax')) model.compile( loss='binary_crossentropy', optimizer='rmsprop') (x_train, y_train), _ = testing_utils.get_test_data( train_samples=train_samples, test_samples=test_samples, input_shape=(input_dim,), num_classes=num_classes) # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) class_weight = dict([(i, 1.) for i in range(num_classes)]) del class_weight[1] with self.assertRaises(ValueError): model.fit(x_train, y_train, epochs=0, verbose=0, class_weight=class_weight) with self.assertRaises(ValueError): model.compile( loss='binary_crossentropy', optimizer='rmsprop', sample_weight_mode=[]) # Build multi-output model x = keras.Input((3,)) y1 = keras.layers.Dense(4, name='1')(x) y2 = keras.layers.Dense(4, name='2')(x) model = keras.models.Model(x, [y1, y2]) model.compile(optimizer='rmsprop', loss='mse') x_np = np.random.random((10, 3)) y_np = np.random.random((10, 4)) w_np = np.random.random((10,)) # This will work model.fit(x_np, [y_np, y_np], epochs=1, sample_weight={'1': w_np}) # These will not with self.assertRaises(ValueError): model.fit(x_np, [y_np, y_np], epochs=1, sample_weight=[w_np]) with self.assertRaises(TypeError): model.fit(x_np, [y_np, y_np], epochs=1, sample_weight=w_np) with self.assertRaises(ValueError): bad_w_np = np.random.random((11,)) model.fit(x_np, [y_np, y_np], epochs=1, sample_weight={'1': bad_w_np}) with self.assertRaises(ValueError): bad_w_np = np.random.random((10, 2)) model.fit(x_np, [y_np, y_np], epochs=1, sample_weight={'1': bad_w_np}) with self.assertRaises(ValueError): bad_w_np = np.random.random((10, 2, 2)) model.fit(x_np, [y_np, y_np], epochs=1, sample_weight={'1': bad_w_np}) class LossMaskingTest(test.TestCase): def test_masking(self): with self.test_session(): np.random.seed(1337) x = np.array([[[1], [1]], [[0], [0]]]) model = keras.models.Sequential() model.add(keras.layers.Masking(mask_value=0, input_shape=(2, 1))) model.add( keras.layers.TimeDistributed( keras.layers.Dense(1, kernel_initializer='one'))) model.compile(loss='mse', optimizer='sgd') y = np.array([[[1], [1]], [[1], [1]]]) loss = model.train_on_batch(x, y) self.assertEqual(loss, 0) def test_loss_masking(self): with self.test_session(): weighted_loss = _weighted_masked_objective(keras.losses.get('mae')) shape = (3, 4, 2) x = np.arange(24).reshape(shape) y = 2 * x # Normally the trailing 1 is added by standardize_weights weights = np.ones((3,)) mask = np.ones((3, 4)) mask[1, 0] = 0 keras.backend.eval( weighted_loss( keras.backend.variable(x), keras.backend.variable(y), keras.backend.variable(weights), keras.backend.variable(mask))) class TestDynamicTrainability(test.TestCase): def test_trainable_argument(self): with self.test_session(): x = np.random.random((5, 3)) y = np.random.random((5, 2)) model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_dim=3, trainable=False)) model.compile('rmsprop', 'mse') out = model.predict(x) model.train_on_batch(x, y) out_2 = model.predict(x) self.assertAllClose(out, out_2) # test with nesting inputs = keras.layers.Input(shape=(3,)) output = model(inputs) model = keras.models.Model(inputs, output) model.compile('rmsprop', 'mse') out = model.predict(x) model.train_on_batch(x, y) out_2 = model.predict(x) self.assertAllClose(out, out_2) def test_layer_trainability_switch(self): with self.test_session(): # with constructor argument, in Sequential model = keras.models.Sequential() model.add(keras.layers.Dense(2, trainable=False, input_dim=1)) self.assertListEqual(model.trainable_weights, []) # by setting the `trainable` argument, in Sequential model = keras.models.Sequential() layer = keras.layers.Dense(2, input_dim=1) model.add(layer) self.assertListEqual(model.trainable_weights, layer.trainable_weights) layer.trainable = False self.assertListEqual(model.trainable_weights, []) # with constructor argument, in Model x = keras.layers.Input(shape=(1,)) y = keras.layers.Dense(2, trainable=False)(x) model = keras.models.Model(x, y) self.assertListEqual(model.trainable_weights, []) # by setting the `trainable` argument, in Model x = keras.layers.Input(shape=(1,)) layer = keras.layers.Dense(2) y = layer(x) model = keras.models.Model(x, y) self.assertListEqual(model.trainable_weights, layer.trainable_weights) layer.trainable = False self.assertListEqual(model.trainable_weights, []) def test_model_trainability_switch(self): with self.test_session(): # a non-trainable model has no trainable weights x = keras.layers.Input(shape=(1,)) y = keras.layers.Dense(2)(x) model = keras.models.Model(x, y) model.trainable = False self.assertListEqual(model.trainable_weights, []) # same for Sequential model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_dim=1)) model.trainable = False self.assertListEqual(model.trainable_weights, []) def test_nested_model_trainability(self): with self.test_session(): # a Sequential inside a Model inner_model = keras.models.Sequential() inner_model.add(keras.layers.Dense(2, input_dim=1)) x = keras.layers.Input(shape=(1,)) y = inner_model(x) outer_model = keras.models.Model(x, y) self.assertListEqual(outer_model.trainable_weights, inner_model.trainable_weights) inner_model.trainable = False self.assertListEqual(outer_model.trainable_weights, []) inner_model.trainable = True inner_model.layers[-1].trainable = False self.assertListEqual(outer_model.trainable_weights, []) # a Sequential inside a Sequential inner_model = keras.models.Sequential() inner_model.add(keras.layers.Dense(2, input_dim=1)) outer_model = keras.models.Sequential() outer_model.add(inner_model) self.assertListEqual(outer_model.trainable_weights, inner_model.trainable_weights) inner_model.trainable = False self.assertListEqual(outer_model.trainable_weights, []) inner_model.trainable = True inner_model.layers[-1].trainable = False self.assertListEqual(outer_model.trainable_weights, []) # a Model inside a Model x = keras.layers.Input(shape=(1,)) y = keras.layers.Dense(2)(x) inner_model = keras.models.Model(x, y) x = keras.layers.Input(shape=(1,)) y = inner_model(x) outer_model = keras.models.Model(x, y) self.assertListEqual(outer_model.trainable_weights, inner_model.trainable_weights) inner_model.trainable = False self.assertListEqual(outer_model.trainable_weights, []) inner_model.trainable = True inner_model.layers[-1].trainable = False self.assertListEqual(outer_model.trainable_weights, []) # a Model inside a Sequential x = keras.layers.Input(shape=(1,)) y = keras.layers.Dense(2)(x) inner_model = keras.models.Model(x, y) outer_model = keras.models.Sequential() outer_model.add(inner_model) self.assertListEqual(outer_model.trainable_weights, inner_model.trainable_weights) inner_model.trainable = False self.assertListEqual(outer_model.trainable_weights, []) inner_model.trainable = True inner_model.layers[-1].trainable = False self.assertListEqual(outer_model.trainable_weights, []) class TestGeneratorMethods(test.TestCase): def test_generator_methods(self): arr_data = np.random.random((50, 2)) arr_labels = np.random.random((50,)) def custom_generator(): batch_size = 10 n_samples = 50 while True: batch_index = np.random.randint(0, n_samples - batch_size) start = batch_index end = start + batch_size x = arr_data[start: end] y = arr_labels[start: end] yield x, y with self.test_session(): x = keras.Input((2,)) y = keras.layers.Dense(1)(x) fn_model = keras.models.Model(x, y) fn_model.compile(loss='mse', optimizer='sgd') seq_model = keras.models.Sequential() seq_model.add(keras.layers.Dense(1, input_shape=(2,))) seq_model.compile(loss='mse', optimizer='sgd') for model in [fn_model, seq_model]: model.fit_generator(custom_generator(), steps_per_epoch=5, epochs=1, verbose=1, max_queue_size=10, workers=4, use_multiprocessing=True) model.fit_generator(custom_generator(), steps_per_epoch=5, epochs=1, verbose=1, max_queue_size=10, use_multiprocessing=False) model.fit_generator(custom_generator(), steps_per_epoch=5, epochs=1, verbose=1, max_queue_size=10, use_multiprocessing=False, validation_data=custom_generator(), validation_steps=10) model.predict_generator(custom_generator(), steps=5, max_queue_size=10, workers=2, use_multiprocessing=True) model.predict_generator(custom_generator(), steps=5, max_queue_size=10, use_multiprocessing=False) model.evaluate_generator(custom_generator(), steps=5, max_queue_size=10, workers=2, use_multiprocessing=True) model.evaluate_generator(custom_generator(), steps=5, max_queue_size=10, use_multiprocessing=False) # Test legacy API model.fit_generator(custom_generator(), steps_per_epoch=5, epochs=1, verbose=1, max_q_size=10, workers=4, pickle_safe=True) model.predict_generator(custom_generator(), steps=5, max_q_size=10, workers=2, pickle_safe=True) model.evaluate_generator(custom_generator(), steps=5, max_q_size=10, workers=2, pickle_safe=True) def test_generator_methods_with_sample_weights(self): arr_data = np.random.random((50, 2)) arr_labels = np.random.random((50,)) arr_sample_weights = np.random.random((50,)) def custom_generator(): batch_size = 10 n_samples = 50 while True: batch_index = np.random.randint(0, n_samples - batch_size) start = batch_index end = start + batch_size x = arr_data[start: end] y = arr_labels[start: end] w = arr_sample_weights[start: end] yield x, y, w with self.test_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(1, input_shape=(2,))) model.compile(loss='mse', optimizer='sgd') model.fit_generator(custom_generator(), steps_per_epoch=5, epochs=1, verbose=1, max_queue_size=10, use_multiprocessing=False) model.fit_generator(custom_generator(), steps_per_epoch=5, epochs=1, verbose=1, max_queue_size=10, use_multiprocessing=False, validation_data=custom_generator(), validation_steps=10) model.predict_generator(custom_generator(), steps=5, max_queue_size=10, use_multiprocessing=False) model.evaluate_generator(custom_generator(), steps=5, max_queue_size=10, use_multiprocessing=False) def test_generator_methods_invalid_use_case(self): def custom_generator(): while 1: yield 0 with self.test_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(1, input_shape=(2,))) model.compile(loss='mse', optimizer='sgd') with self.assertRaises(ValueError): model.fit_generator(custom_generator(), steps_per_epoch=5, epochs=1, verbose=1, max_queue_size=10, use_multiprocessing=False) with self.assertRaises(ValueError): model.fit_generator(custom_generator(), steps_per_epoch=5, epochs=1, verbose=1, max_queue_size=10, use_multiprocessing=False, validation_data=custom_generator(), validation_steps=10) with self.assertRaises(TypeError): model.predict_generator(custom_generator(), steps=5, max_queue_size=10, use_multiprocessing=False) with self.assertRaises(ValueError): model.evaluate_generator(custom_generator(), steps=5, max_queue_size=10, use_multiprocessing=False) class TestTrainingUtils(test.TestCase): def test_check_array_lengths(self): keras.engine.training._check_array_lengths(None, None, None) a_np = np.random.random((4, 3, 3)) keras.engine.training._check_array_lengths(a_np, a_np, a_np) keras.engine.training._check_array_lengths( [a_np, a_np], [a_np, a_np], [a_np, a_np]) keras.engine.training._check_array_lengths([None], [None], [None]) b_np = np.random.random((3, 4)) with self.assertRaises(ValueError): keras.engine.training._check_array_lengths(a_np, None, None) with self.assertRaises(ValueError): keras.engine.training._check_array_lengths(a_np, a_np, None) with self.assertRaises(ValueError): keras.engine.training._check_array_lengths([a_np], [None], None) with self.assertRaises(ValueError): keras.engine.training._check_array_lengths([a_np], [b_np], None) with self.assertRaises(ValueError): keras.engine.training._check_array_lengths([a_np], None, [b_np]) def test_slice_arrays(self): input_a = np.random.random((10, 3)) keras.engine.training._slice_arrays(None) keras.engine.training._slice_arrays(input_a, 0) keras.engine.training._slice_arrays(input_a, 0, 1) keras.engine.training._slice_arrays(input_a, stop=2) input_a = [None, [1, 1], None, [1, 1]] keras.engine.training._slice_arrays(input_a, 0) keras.engine.training._slice_arrays(input_a, 0, 1) keras.engine.training._slice_arrays(input_a, stop=2) input_a = [None] keras.engine.training._slice_arrays(input_a, 0) keras.engine.training._slice_arrays(input_a, 0, 1) keras.engine.training._slice_arrays(input_a, stop=2) input_a = None keras.engine.training._slice_arrays(input_a, 0) keras.engine.training._slice_arrays(input_a, 0, 1) keras.engine.training._slice_arrays(input_a, stop=2) class TestTrainingWithDataTensors(test.TestCase): def test_model_with_input_feed_tensor(self): """We test building a model with a TF variable as input. We should be able to call fit, evaluate, predict, by only passing them data for the placeholder inputs in the model. """ with self.test_session(): input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) output_a_np = np.random.random((10, 4)) output_b_np = np.random.random((10, 3)) a = keras.Input( tensor=keras.backend.variables_module.Variable(input_a_np, dtype='float32')) b = keras.Input(shape=(3,), name='input_b') a_2 = keras.layers.Dense(4, name='dense_1')(a) dp = keras.layers.Dropout(0.5, name='dropout') b_2 = dp(b) model = keras.models.Model([a, b], [a_2, b_2]) model.summary() optimizer = 'rmsprop' loss = 'mse' loss_weights = [1., 0.5] model.compile(optimizer, loss, metrics=['mean_squared_error'], loss_weights=loss_weights, sample_weight_mode=None) # test train_on_batch out = model.train_on_batch(input_b_np, [output_a_np, output_b_np]) out = model.train_on_batch({'input_b': input_b_np}, [output_a_np, output_b_np]) out = model.test_on_batch({'input_b': input_b_np}, [output_a_np, output_b_np]) out = model.predict_on_batch({'input_b': input_b_np}) # test fit out = model.fit({'input_b': input_b_np}, [output_a_np, output_b_np], epochs=1, batch_size=10) out = model.fit(input_b_np, [output_a_np, output_b_np], epochs=1, batch_size=10) # test evaluate out = model.evaluate({'input_b': input_b_np}, [output_a_np, output_b_np], batch_size=10) out = model.evaluate(input_b_np, [output_a_np, output_b_np], batch_size=10) # test predict out = model.predict({'input_b': input_b_np}, batch_size=10) out = model.predict(input_b_np, batch_size=10) self.assertEqual(len(out), 2) # Now test a model with a single input # i.e. we don't pass any data to fit the model. a = keras.Input( tensor=keras.backend.variables_module.Variable(input_a_np, dtype='float32')) a_2 = keras.layers.Dense(4, name='dense_1')(a) a_2 = keras.layers.Dropout(0.5, name='dropout')(a_2) model = keras.models.Model(a, a_2) model.summary() optimizer = 'rmsprop' loss = 'mse' model.compile(optimizer, loss, metrics=['mean_squared_error']) # test train_on_batch out = model.train_on_batch(None, output_a_np) out = model.train_on_batch(None, output_a_np) out = model.test_on_batch(None, output_a_np) out = model.predict_on_batch(None) out = model.train_on_batch([], output_a_np) out = model.train_on_batch({}, output_a_np) # test fit out = model.fit(None, output_a_np, epochs=1, batch_size=10) out = model.fit(None, output_a_np, epochs=1, batch_size=10) # test evaluate out = model.evaluate(None, output_a_np, batch_size=10) out = model.evaluate(None, output_a_np, batch_size=10) # test predict out = model.predict(None, steps=3) out = model.predict(None, steps=3) self.assertEqual(out.shape, (10 * 3, 4)) # Same, without learning phase # i.e. we don't pass any data to fit the model. a = keras.Input( tensor=keras.backend.variables_module.Variable(input_a_np, dtype='float32')) a_2 = keras.layers.Dense(4, name='dense_1')(a) model = keras.models.Model(a, a_2) model.summary() optimizer = 'rmsprop' loss = 'mse' model.compile(optimizer, loss, metrics=['mean_squared_error']) # test train_on_batch out = model.train_on_batch(None, output_a_np) out = model.train_on_batch(None, output_a_np) out = model.test_on_batch(None, output_a_np) out = model.predict_on_batch(None) out = model.train_on_batch([], output_a_np) out = model.train_on_batch({}, output_a_np) # test fit out = model.fit(None, output_a_np, epochs=1, batch_size=10) out = model.fit(None, output_a_np, epochs=1, batch_size=10) # test evaluate out = model.evaluate(None, output_a_np, batch_size=10) out = model.evaluate(None, output_a_np, batch_size=10) # test predict out = model.predict(None, steps=3) out = model.predict(None, steps=3) self.assertEqual(out.shape, (10 * 3, 4)) def test_model_with_partial_loss(self): with self.test_session(): a = keras.Input(shape=(3,), name='input_a') a_2 = keras.layers.Dense(4, name='dense_1')(a) dp = keras.layers.Dropout(0.5, name='dropout') a_3 = dp(a_2) model = keras.models.Model(a, [a_2, a_3]) optimizer = 'rmsprop' loss = {'dropout': 'mse'} model.compile(optimizer, loss, metrics=['mae']) input_a_np = np.random.random((10, 3)) output_a_np = np.random.random((10, 4)) # test train_on_batch _ = model.train_on_batch(input_a_np, output_a_np) _ = model.test_on_batch(input_a_np, output_a_np) # fit _ = model.fit(input_a_np, [output_a_np]) # evaluate _ = model.evaluate(input_a_np, [output_a_np]) # Same without dropout. a = keras.Input(shape=(3,), name='input_a') a_2 = keras.layers.Dense(4, name='dense_1')(a) a_3 = keras.layers.Dense(4, name='dense_2')(a_2) model = keras.models.Model(a, [a_2, a_3]) optimizer = 'rmsprop' loss = {'dense_2': 'mse'} model.compile(optimizer, loss, metrics={'dense_1': 'mae'}) # test train_on_batch _ = model.train_on_batch(input_a_np, output_a_np) _ = model.test_on_batch(input_a_np, output_a_np) # fit _ = model.fit(input_a_np, [output_a_np]) # evaluate _ = model.evaluate(input_a_np, [output_a_np]) def test_model_with_external_loss(self): with self.test_session(): # None loss, only regularization loss. a = keras.Input(shape=(3,), name='input_a') a_2 = keras.layers.Dense(4, name='dense_1', kernel_regularizer='l1', bias_regularizer='l2')(a) dp = keras.layers.Dropout(0.5, name='dropout') a_3 = dp(a_2) model = keras.models.Model(a, [a_2, a_3]) optimizer = 'rmsprop' loss = None model.compile(optimizer, loss, metrics=['mae']) input_a_np = np.random.random((10, 3)) # test train_on_batch out = model.train_on_batch(input_a_np, None) out = model.test_on_batch(input_a_np, None) # fit out = model.fit(input_a_np, None) # evaluate out = model.evaluate(input_a_np, None) # No dropout, external loss. a = keras.Input(shape=(3,), name='input_a') a_2 = keras.layers.Dense(4, name='dense_1')(a) a_3 = keras.layers.Dense(4, name='dense_2')(a) model = keras.models.Model(a, [a_2, a_3]) model.add_loss(keras.backend.mean(a_3 + a_2)) optimizer = 'rmsprop' loss = None model.compile(optimizer, loss, metrics=['mae']) # test train_on_batch out = model.train_on_batch(input_a_np, None) out = model.test_on_batch(input_a_np, None) # fit out = model.fit(input_a_np, None) # evaluate out = model.evaluate(input_a_np, None) # Test model with no external data at all. a = keras.Input( tensor=keras.backend.variables_module.Variable(input_a_np, dtype='float32')) a_2 = keras.layers.Dense(4, name='dense_1')(a) a_2 = keras.layers.Dropout(0.5, name='dropout')(a_2) model = keras.models.Model(a, a_2) model.add_loss(keras.backend.mean(a_2)) model.compile(optimizer='rmsprop', loss=None, metrics=['mean_squared_error']) # test train_on_batch out = model.train_on_batch(None, None) out = model.test_on_batch(None, None) out = model.predict_on_batch(None) # test fit with self.assertRaises(ValueError): out = model.fit(None, None, epochs=1, batch_size=10) out = model.fit(None, None, epochs=1, steps_per_epoch=1) # test fit with validation data with self.assertRaises(ValueError): out = model.fit(None, None, epochs=1, steps_per_epoch=None, validation_steps=2) out = model.fit(None, None, epochs=1, steps_per_epoch=2, validation_steps=2) # test evaluate with self.assertRaises(ValueError): out = model.evaluate(None, None, batch_size=10) out = model.evaluate(None, None, steps=3) # test predict with self.assertRaises(ValueError): out = model.predict(None, batch_size=10) out = model.predict(None, steps=3) self.assertEqual(out.shape, (10 * 3, 4)) # Test multi-output model with no external data at all. a = keras.Input( tensor=keras.backend.variables_module.Variable(input_a_np, dtype='float32')) a_1 = keras.layers.Dense(4, name='dense_1')(a) a_2 = keras.layers.Dropout(0.5, name='dropout')(a_1) model = keras.models.Model(a, [a_1, a_2]) model.add_loss(keras.backend.mean(a_2)) model.compile(optimizer='rmsprop', loss=None, metrics=['mean_squared_error']) # test train_on_batch out = model.train_on_batch(None, None) out = model.test_on_batch(None, None) out = model.predict_on_batch(None) # test fit with self.assertRaises(ValueError): out = model.fit(None, None, epochs=1, batch_size=10) out = model.fit(None, None, epochs=1, steps_per_epoch=1) # test fit with validation data out = model.fit(None, None, epochs=1, steps_per_epoch=2, validation_steps=2) # test evaluate with self.assertRaises(ValueError): out = model.evaluate(None, None, batch_size=10) out = model.evaluate(None, None, steps=3) # test predict with self.assertRaises(ValueError): out = model.predict(None, batch_size=10, verbose=1) out = model.predict(None, steps=3) self.assertEqual(len(out), 2) self.assertEqual(out[0].shape, (10 * 3, 4)) self.assertEqual(out[1].shape, (10 * 3, 4)) def test_target_tensors(self): with self.test_session(): # single-output, as list model = keras.models.Sequential() model.add(keras.layers.Dense(4, input_shape=(4,), name='dense')) input_val = np.random.random((10, 4)) target_val = np.random.random((10, 4)) target = keras.backend.variable(target_val) model.compile(optimizer='rmsprop', loss='mse', target_tensors=[target]) model.train_on_batch(input_val, None) # single-output, as dict model.compile(optimizer='rmsprop', loss='mse', target_tensors={'dense': target}) model.train_on_batch(input_val, None) # test invalid arguments with self.assertRaises(TypeError): model.compile(optimizer='rmsprop', loss='mse', target_tensors=set()) with self.assertRaises(ValueError): model.compile(optimizer='rmsprop', loss='mse', target_tensors=[target, target]) with self.assertRaises(ValueError): model.compile(optimizer='rmsprop', loss='mse', target_tensors={'dense2': None}) with self.assertRaises(ValueError): model.compile(optimizer='rmsprop', loss='mse', target_tensors=[target]) model.train_on_batch(input_val, target_val) # multi-output, as list input_val = np.random.random((10, 4)) target_val_a = np.random.random((10, 4)) target_val_b = np.random.random((10, 4)) target_a = keras.backend.variable(target_val_a) target_b = keras.backend.variable(target_val_b) inputs = keras.layers.Input(shape=(4,)) output_a = keras.layers.Dense(4, name='dense_a')(inputs) output_b = keras.layers.Dense(4, name='dense_b')(inputs) model = keras.models.Model(inputs, [output_a, output_b]) model.compile(optimizer='rmsprop', loss='mse', target_tensors=[target_a, target_b]) model.train_on_batch(input_val, None) # multi-output, as dict model.compile(optimizer='rmsprop', loss='mse', target_tensors={'dense_a': target_a, 'dense_b': target_b}) model.train_on_batch(input_val, None) # test with sample weights model.compile(optimizer='rmsprop', loss='mse', target_tensors=[target_a, target_b]) model.train_on_batch(input_val, None, sample_weight={'dense_a': np.random.random((10,))}) def test_model_custom_target_tensors(self): with self.test_session(): a = keras.Input(shape=(3,), name='input_a') b = keras.Input(shape=(3,), name='input_b') a_2 = keras.layers.Dense(4, name='dense_1')(a) dp = keras.layers.Dropout(0.5, name='dropout') b_2 = dp(b) y = keras.backend.placeholder([10, 4], name='y') y1 = keras.backend.placeholder([10, 3], name='y1') y2 = keras.backend.placeholder([7, 5], name='y2') model = keras.models.Model([a, b], [a_2, b_2]) optimizer = 'rmsprop' loss = 'mse' loss_weights = [1., 0.5] # test list of target tensors with self.assertRaises(ValueError): model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None, target_tensors=[y, y1, y2]) model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None, target_tensors=[y, y1]) input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) output_a_np = np.random.random((10, 4)) output_b_np = np.random.random((10, 3)) _ = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np], {y: np.random.random((10, 4)), y1: np.random.random((10, 3))}) # test dictionary of target_tensors with self.assertRaises(ValueError): model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None, target_tensors={'does_not_exist': y2}) # test dictionary of target_tensors model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None, target_tensors={'dense_1': y, 'dropout': y1}) _ = model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np], {y: np.random.random((10, 4)), y1: np.random.random((10, 3))}) # test with custom TF placeholder as target pl_target_a = keras.backend.array_ops.placeholder('float32', shape=(None, 4)) model.compile(optimizer='rmsprop', loss='mse', target_tensors={'dense_1': pl_target_a}) model.train_on_batch([input_a_np, input_b_np], [output_a_np, output_b_np]) if __name__ == '__main__': test.main()
apache-2.0
hurricup/intellij-community
python/lib/Lib/site-packages/django/contrib/localflavor/ar/forms.py
309
3903
# -*- coding: utf-8 -*- """ AR-specific Form helpers. """ from django.forms import ValidationError from django.core.validators import EMPTY_VALUES from django.forms.fields import RegexField, CharField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ class ARProvinceSelect(Select): """ A Select widget that uses a list of Argentinean provinces/autonomous cities as its choices. """ def __init__(self, attrs=None): from ar_provinces import PROVINCE_CHOICES super(ARProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) class ARPostalCodeField(RegexField): """ A field that accepts a 'classic' NNNN Postal Code or a CPA. See http://www.correoargentino.com.ar/consulta_cpa/home.php """ default_error_messages = { 'invalid': _("Enter a postal code in the format NNNN or ANNNNAAA."), } def __init__(self, *args, **kwargs): super(ARPostalCodeField, self).__init__(r'^\d{4}$|^[A-HJ-NP-Za-hj-np-z]\d{4}\D{3}$', min_length=4, max_length=8, *args, **kwargs) def clean(self, value): value = super(ARPostalCodeField, self).clean(value) if value in EMPTY_VALUES: return u'' if len(value) not in (4, 8): raise ValidationError(self.error_messages['invalid']) if len(value) == 8: return u'%s%s%s' % (value[0].upper(), value[1:5], value[5:].upper()) return value class ARDNIField(CharField): """ A field that validates 'Documento Nacional de Identidad' (DNI) numbers. """ default_error_messages = { 'invalid': _("This field requires only numbers."), 'max_digits': _("This field requires 7 or 8 digits."), } def __init__(self, *args, **kwargs): super(ARDNIField, self).__init__(max_length=10, min_length=7, *args, **kwargs) def clean(self, value): """ Value can be a string either in the [X]X.XXX.XXX or [X]XXXXXXX formats. """ value = super(ARDNIField, self).clean(value) if value in EMPTY_VALUES: return u'' if not value.isdigit(): value = value.replace('.', '') if not value.isdigit(): raise ValidationError(self.error_messages['invalid']) if len(value) not in (7, 8): raise ValidationError(self.error_messages['max_digits']) return value class ARCUITField(RegexField): """ This field validates a CUIT (Código Único de Identificación Tributaria). A CUIT is of the form XX-XXXXXXXX-V. The last digit is a check digit. """ default_error_messages = { 'invalid': _('Enter a valid CUIT in XX-XXXXXXXX-X or XXXXXXXXXXXX format.'), 'checksum': _("Invalid CUIT."), } def __init__(self, *args, **kwargs): super(ARCUITField, self).__init__(r'^\d{2}-?\d{8}-?\d$', *args, **kwargs) def clean(self, value): """ Value can be either a string in the format XX-XXXXXXXX-X or an 11-digit number. """ value = super(ARCUITField, self).clean(value) if value in EMPTY_VALUES: return u'' value, cd = self._canon(value) if self._calc_cd(value) != cd: raise ValidationError(self.error_messages['checksum']) return self._format(value, cd) def _canon(self, cuit): cuit = cuit.replace('-', '') return cuit[:-1], cuit[-1] def _calc_cd(self, cuit): mults = (5, 4, 3, 2, 7, 6, 5, 4, 3, 2) tmp = sum([m * int(cuit[idx]) for idx, m in enumerate(mults)]) return str(11 - tmp % 11) def _format(self, cuit, check_digit=None): if check_digit == None: check_digit = cuit[-1] cuit = cuit[:-1] return u'%s-%s-%s' % (cuit[:2], cuit[2:], check_digit)
apache-2.0
atsolakid/edx-platform
common/lib/xmodule/xmodule/tests/test_bulk_assertions.py
173
5627
import ddt import itertools from xmodule.tests import BulkAssertionTest, BulkAssertionError STATIC_PASSING_ASSERTIONS = ( ('assertTrue', True), ('assertFalse', False), ('assertIs', 1, 1), ('assertEqual', 1, 1), ('assertEquals', 1, 1), ('assertIsNot', 1, 2), ('assertIsNone', None), ('assertIsNotNone', 1), ('assertIn', 1, (1, 2, 3)), ('assertNotIn', 5, (1, 2, 3)), ('assertIsInstance', 1, int), ('assertNotIsInstance', '1', int), ('assertItemsEqual', [1, 2, 3], [3, 2, 1]) ) STATIC_FAILING_ASSERTIONS = ( ('assertTrue', False), ('assertFalse', True), ('assertIs', 1, 2), ('assertEqual', 1, 2), ('assertEquals', 1, 2), ('assertIsNot', 1, 1), ('assertIsNone', 1), ('assertIsNotNone', None), ('assertIn', 5, (1, 2, 3)), ('assertNotIn', 1, (1, 2, 3)), ('assertIsInstance', '1', int), ('assertNotIsInstance', 1, int), ('assertItemsEqual', [1, 1, 1], [1, 1]) ) CONTEXT_PASSING_ASSERTIONS = ( ('assertRaises', KeyError, {}.__getitem__, '1'), ('assertRaisesRegexp', KeyError, "1", {}.__getitem__, '1'), ) CONTEXT_FAILING_ASSERTIONS = ( ('assertRaises', ValueError, lambda: None), ('assertRaisesRegexp', KeyError, "2", {}.__getitem__, '1'), ) @ddt.ddt class TestBulkAssertionTestCase(BulkAssertionTest): # We have to use assertion methods from the base UnitTest class, # so we make a number of super calls that skip BulkAssertionTest. # pylint: disable=bad-super-call def _run_assertion(self, assertion_tuple): """ Run the supplied tuple of (assertion, *args) as a method on this class. """ assertion, args = assertion_tuple[0], assertion_tuple[1:] getattr(self, assertion)(*args) def _raw_assert(self, assertion_name, *args, **kwargs): """ Run an un-modified assertion. """ # Use super(BulkAssertionTest) to make sure we get un-adulturated assertions return getattr(super(BulkAssertionTest, self), 'assert' + assertion_name)(*args, **kwargs) @ddt.data(*(STATIC_PASSING_ASSERTIONS + CONTEXT_PASSING_ASSERTIONS)) def test_passing_asserts_passthrough(self, assertion_tuple): self._run_assertion(assertion_tuple) @ddt.data(*(STATIC_FAILING_ASSERTIONS + CONTEXT_FAILING_ASSERTIONS)) def test_failing_asserts_passthrough(self, assertion_tuple): with self._raw_assert('Raises', AssertionError) as context: self._run_assertion(assertion_tuple) self._raw_assert('NotIsInstance', context.exception, BulkAssertionError) @ddt.data(*CONTEXT_PASSING_ASSERTIONS) @ddt.unpack def test_passing_context_assertion_passthrough(self, assertion, *args): assertion_args = [] args = list(args) exception = args.pop(0) while not callable(args[0]): assertion_args.append(args.pop(0)) function = args.pop(0) with getattr(self, assertion)(exception, *assertion_args): function(*args) @ddt.data(*CONTEXT_FAILING_ASSERTIONS) @ddt.unpack def test_failing_context_assertion_passthrough(self, assertion, *args): assertion_args = [] args = list(args) exception = args.pop(0) while not callable(args[0]): assertion_args.append(args.pop(0)) function = args.pop(0) with self._raw_assert('Raises', AssertionError) as context: with getattr(self, assertion)(exception, *assertion_args): function(*args) self._raw_assert('NotIsInstance', context.exception, BulkAssertionError) @ddt.data(*list(itertools.product( CONTEXT_PASSING_ASSERTIONS, CONTEXT_FAILING_ASSERTIONS, CONTEXT_FAILING_ASSERTIONS ))) @ddt.unpack def test_bulk_assert(self, passing_assertion, failing_assertion1, failing_assertion2): contextmanager = self.bulk_assertions() contextmanager.__enter__() self._run_assertion(passing_assertion) self._run_assertion(failing_assertion1) self._run_assertion(failing_assertion2) with self._raw_assert('Raises', BulkAssertionError) as context: contextmanager.__exit__(None, None, None) self._raw_assert('Equals', len(context.exception.errors), 2) @ddt.data(*list(itertools.product( CONTEXT_FAILING_ASSERTIONS ))) @ddt.unpack def test_nested_bulk_asserts(self, failing_assertion): with self._raw_assert('Raises', BulkAssertionError) as context: with self.bulk_assertions(): self._run_assertion(failing_assertion) with self.bulk_assertions(): self._run_assertion(failing_assertion) self._run_assertion(failing_assertion) self._raw_assert('Equal', len(context.exception.errors), 3) @ddt.data(*list(itertools.product( CONTEXT_PASSING_ASSERTIONS, CONTEXT_FAILING_ASSERTIONS, CONTEXT_FAILING_ASSERTIONS ))) @ddt.unpack def test_bulk_assert_closed(self, passing_assertion, failing_assertion1, failing_assertion2): with self._raw_assert('Raises', BulkAssertionError) as context: with self.bulk_assertions(): self._run_assertion(passing_assertion) self._run_assertion(failing_assertion1) self._raw_assert('Equals', len(context.exception.errors), 1) with self._raw_assert('Raises', AssertionError) as context: self._run_assertion(failing_assertion2) self._raw_assert('NotIsInstance', context.exception, BulkAssertionError)
agpl-3.0
s20121035/rk3288_android5.1_repo
external/chromium_org/native_client_sdk/src/build_tools/tests/easy_template_test.py
53
3559
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import cStringIO import difflib import os import sys import unittest SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD_TOOLS_DIR = os.path.dirname(SCRIPT_DIR) sys.path.append(BUILD_TOOLS_DIR) import easy_template class EasyTemplateTestCase(unittest.TestCase): def _RunTest(self, template, expected, template_dict): src = cStringIO.StringIO(template) dst = cStringIO.StringIO() easy_template.RunTemplate(src, dst, template_dict) if dst.getvalue() != expected: expected_lines = expected.splitlines(1) actual_lines = dst.getvalue().splitlines(1) diff = ''.join(difflib.unified_diff( expected_lines, actual_lines, fromfile='expected', tofile='actual')) self.fail('Unexpected output:\n' + diff) def testEmpty(self): self._RunTest('', '', {}) def testNewlines(self): self._RunTest('\n\n', '\n\n', {}) def testNoInterpolation(self): template = """I love paris in the the springtime [don't you?] {this is not interpolation}. """ self._RunTest(template, template, {}) def testSimpleInterpolation(self): self._RunTest( '{{foo}} is my favorite number', '42 is my favorite number', {'foo': 42}) def testLineContinuations(self): template = "Line 1 \\\nLine 2\n""" self._RunTest(template, template, {}) def testIfStatement(self): template = r""" [[if foo:]] foo [[else:]] not foo [[]]""" self._RunTest(template, "\n foo\n", {'foo': True}) self._RunTest(template, "\n not foo\n", {'foo': False}) def testForStatement(self): template = r"""[[for beers in [99, 98, 1]:]] {{beers}} bottle{{(beers != 1) and 's' or ''}} of beer on the wall... [[]]""" expected = r"""99 bottles of beer on the wall... 98 bottles of beer on the wall... 1 bottle of beer on the wall... """ self._RunTest(template, expected, {}) def testListVariables(self): template = r""" [[for i, item in enumerate(my_list):]] {{i+1}}: {{item}} [[]] """ self._RunTest(template, "\n1: Banana\n2: Grapes\n3: Kumquat\n", {'my_list': ['Banana', 'Grapes', 'Kumquat']}) def testListInterpolation(self): template = "{{', '.join(growing[0:-1]) + ' and ' + growing[-1]}} grow..." self._RunTest(template, "Oats, peas, beans and barley grow...", {'growing': ['Oats', 'peas', 'beans', 'barley']}) self._RunTest(template, "Love and laughter grow...", {'growing': ['Love', 'laughter']}) def testComplex(self): template = r""" struct {{name}} { [[for field in fields:]] [[ if field['type'] == 'array':]] {{field['basetype']}} {{field['name']}}[{{field['size']}}]; [[ else:]] {{field['type']}} {{field['name']}}; [[ ]] [[]] };""" expected = r""" struct Foo { std::string name; int problems[99]; };""" self._RunTest(template, expected, { 'name': 'Foo', 'fields': [ {'name': 'name', 'type': 'std::string'}, {'name': 'problems', 'type': 'array', 'basetype': 'int', 'size': 99}]}) def testModulo(self): self._RunTest('No expression %', 'No expression %', {}) self._RunTest('% before {{3 + 4}}', '% before 7', {}) self._RunTest('{{2**8}} % after', '256 % after', {}) self._RunTest('inside {{8 % 3}}', 'inside 2', {}) self._RunTest('Everywhere % {{8 % 3}} %', 'Everywhere % 2 %', {}) if __name__ == '__main__': unittest.main()
gpl-3.0
theuni/bitcoin
contrib/testgen/base58.py
2139
2818
''' Bitcoin base58 encoding and decoding. Based on https://bitcointalk.org/index.php?topic=1026.0 (public domain) ''' import hashlib # for compatibility with following code... class SHA256: new = hashlib.sha256 if str != bytes: # Python 3.x def ord(c): return c def chr(n): return bytes( (n,) ) __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' __b58base = len(__b58chars) b58chars = __b58chars def b58encode(v): """ encode v, which is a string of bytes, to base58. """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += (256**i) * ord(c) result = '' while long_value >= __b58base: div, mod = divmod(long_value, __b58base) result = __b58chars[mod] + result long_value = div result = __b58chars[long_value] + result # Bitcoin does a little leading-zero-compression: # leading 0-bytes in the input become leading-1s nPad = 0 for c in v: if c == '\0': nPad += 1 else: break return (__b58chars[0]*nPad) + result def b58decode(v, length = None): """ decode v into a string of len bytes """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base**i) result = bytes() while long_value >= 256: div, mod = divmod(long_value, 256) result = chr(mod) + result long_value = div result = chr(long_value) + result nPad = 0 for c in v: if c == __b58chars[0]: nPad += 1 else: break result = chr(0)*nPad + result if length is not None and len(result) != length: return None return result def checksum(v): """Return 32-bit checksum based on SHA256""" return SHA256.new(SHA256.new(v).digest()).digest()[0:4] def b58encode_chk(v): """b58encode a string, with 32-bit checksum""" return b58encode(v + checksum(v)) def b58decode_chk(v): """decode a base58 string, check and remove checksum""" result = b58decode(v) if result is None: return None h3 = checksum(result[:-4]) if result[-4:] == checksum(result[:-4]): return result[:-4] else: return None def get_bcaddress_version(strAddress): """ Returns None if strAddress is invalid. Otherwise returns integer version of address. """ addr = b58decode_chk(strAddress) if addr is None or len(addr)!=21: return None version = addr[0] return ord(version) if __name__ == '__main__': # Test case (from http://gitorious.org/bitcoin/python-base58.git) assert get_bcaddress_version('15VjRaDX9zpbA8LVnbrCAFzrVzN7ixHNsC') is 0 _ohai = 'o hai'.encode('ascii') _tmp = b58encode(_ohai) assert _tmp == 'DYB3oMS' assert b58decode(_tmp, 5) == _ohai print("Tests passed")
mit
drufat/sympy
sympy/utilities/randtest.py
32
5449
""" Helpers for randomized testing """ from __future__ import print_function, division from random import uniform import random from sympy.core.numbers import I from sympy.simplify.simplify import nsimplify from sympy.core.containers import Tuple from sympy.core.numbers import comp from sympy.core.symbol import Symbol from sympy.core.compatibility import is_sequence, as_int def random_complex_number(a=2, b=-1, c=3, d=1, rational=False): """ Return a random complex number. To reduce chance of hitting branch cuts or anything, we guarantee b <= Im z <= d, a <= Re z <= c """ A, B = uniform(a, c), uniform(b, d) if not rational: return A + I*B return nsimplify(A, rational=True) + I*nsimplify(B, rational=True) def verify_numerically(f, g, z=None, tol=1.0e-6, a=2, b=-1, c=3, d=1): """ Test numerically that f and g agree when evaluated in the argument z. If z is None, all symbols will be tested. This routine does not test whether there are Floats present with precision higher than 15 digits so if there are, your results may not be what you expect due to round- off errors. Examples ======== >>> from sympy import sin, cos >>> from sympy.abc import x >>> from sympy.utilities.randtest import verify_numerically as tn >>> tn(sin(x)**2 + cos(x)**2, 1, x) True """ f, g, z = Tuple(f, g, z) z = [z] if isinstance(z, Symbol) else (f.free_symbols | g.free_symbols) reps = list(zip(z, [random_complex_number(a, b, c, d) for zi in z])) z1 = f.subs(reps).n() z2 = g.subs(reps).n() return comp(z1, z2, tol) def test_derivative_numerically(f, z, tol=1.0e-6, a=2, b=-1, c=3, d=1): """ Test numerically that the symbolically computed derivative of f with respect to z is correct. This routine does not test whether there are Floats present with precision higher than 15 digits so if there are, your results may not be what you expect due to round-off errors. Examples ======== >>> from sympy import sin >>> from sympy.abc import x >>> from sympy.utilities.randtest import test_derivative_numerically as td >>> td(sin(x), x) True """ from sympy.core.function import Derivative z0 = random_complex_number(a, b, c, d) f1 = f.diff(z).subs(z, z0) f2 = Derivative(f, z).doit_numerically(z0) return comp(f1.n(), f2.n(), tol) def _randrange(seed=None): """Return a randrange generator. ``seed`` can be o None - return randomly seeded generator o int - return a generator seeded with the int o list - the values to be returned will be taken from the list in the order given; the provided list is not modified. Examples ======== >>> from sympy.utilities.randtest import _randrange >>> rr = _randrange() >>> rr(1000) # doctest: +SKIP 999 >>> rr = _randrange(3) >>> rr(1000) # doctest: +SKIP 238 >>> rr = _randrange([0, 5, 1, 3, 4]) >>> rr(3), rr(3) (0, 1) """ if seed is None: return random.randrange elif isinstance(seed, int): return random.Random(seed).randrange elif is_sequence(seed): seed = list(seed) # make a copy seed.reverse() def give(a, b=None, seq=seed): if b is None: a, b = 0, a a, b = as_int(a), as_int(b) w = b - a if w < 1: raise ValueError('_randrange got empty range') try: x = seq.pop() except AttributeError: raise ValueError('_randrange expects a list-like sequence') except IndexError: raise ValueError('_randrange sequence was too short') if a <= x < b: return x else: return give(a, b, seq) return give else: raise ValueError('_randrange got an unexpected seed') def _randint(seed=None): """Return a randint generator. ``seed`` can be o None - return randomly seeded generator o int - return a generator seeded with the int o list - the values to be returned will be taken from the list in the order given; the provided list is not modified. Examples ======== >>> from sympy.utilities.randtest import _randint >>> ri = _randint() >>> ri(1, 1000) # doctest: +SKIP 999 >>> ri = _randint(3) >>> ri(1, 1000) # doctest: +SKIP 238 >>> ri = _randint([0, 5, 1, 2, 4]) >>> ri(1, 3), ri(1, 3) (1, 2) """ if seed is None: return random.randint elif isinstance(seed, int): return random.Random(seed).randint elif is_sequence(seed): seed = list(seed) # make a copy seed.reverse() def give(a, b, seq=seed): a, b = as_int(a), as_int(b) w = b - a if w < 0: raise ValueError('_randint got empty range') try: x = seq.pop() except AttributeError: raise ValueError('_randint expects a list-like sequence') except IndexError: raise ValueError('_randint sequence was too short') if a <= x <= b: return x else: return give(a, b, seq) return give else: raise ValueError('_randint got an unexpected seed')
bsd-3-clause
MikeC84/mac_kernel_lge_hammerhead
tools/perf/util/setup.py
4998
1330
#!/usr/bin/python2 from distutils.core import setup, Extension from os import getenv from distutils.command.build_ext import build_ext as _build_ext from distutils.command.install_lib import install_lib as _install_lib class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) self.build_lib = build_lib self.build_temp = build_tmp class install_lib(_install_lib): def finalize_options(self): _install_lib.finalize_options(self) self.build_dir = build_lib cflags = ['-fno-strict-aliasing', '-Wno-write-strings'] cflags += getenv('CFLAGS', '').split() build_lib = getenv('PYTHON_EXTBUILD_LIB') build_tmp = getenv('PYTHON_EXTBUILD_TMP') ext_sources = [f.strip() for f in file('util/python-ext-sources') if len(f.strip()) > 0 and f[0] != '#'] perf = Extension('perf', sources = ext_sources, include_dirs = ['util/include'], extra_compile_args = cflags, ) setup(name='perf', version='0.1', description='Interface with the Linux profiling infrastructure', author='Arnaldo Carvalho de Melo', author_email='[email protected]', license='GPLv2', url='http://perf.wiki.kernel.org', ext_modules=[perf], cmdclass={'build_ext': build_ext, 'install_lib': install_lib})
gpl-2.0
zadgroup/edx-platform
cms/djangoapps/contentstore/management/commands/fix_not_found.py
108
1110
""" Script for fixing the item not found errors in a course """ from django.core.management.base import BaseCommand, CommandError from opaque_keys.edx.keys import CourseKey from xmodule.modulestore.django import modulestore from xmodule.modulestore import ModuleStoreEnum # To run from command line: ./manage.py cms fix_not_found course-v1:org+course+run class Command(BaseCommand): """Fix a course's item not found errors""" help = "Fix a course's ItemNotFound errors" def handle(self, *args, **options): "Execute the command" if len(args) != 1: raise CommandError("requires 1 argument: <course_id>") course_key = CourseKey.from_string(args[0]) # for now only support on split mongo # pylint: disable=protected-access owning_store = modulestore()._get_modulestore_for_courselike(course_key) if hasattr(owning_store, 'fix_not_found'): owning_store.fix_not_found(course_key, ModuleStoreEnum.UserID.mgmt_command) else: raise CommandError("The owning modulestore does not support this command.")
agpl-3.0
ricorx7/rti_python
ADCP/Predictor/MaxVelocity.py
2
6635
import json import os import math import pytest def calculate_max_velocity(**kwargs): """ Calculate the maximum velocity the ADCP can measure including the boat speed in m/s. This speed is the speed the ADCP is capable of measuring, if the speed exceeds this value, then the data will be incorrect due to rollovers. :param _CWPBB_ Broadband or Narrowband. :param CWPBB_LagLength=: WP lag length in meters. :param CWPBS=: Bin Size. :param BeamAngle=: Beam angle in degrees. :param SystemFrequency=: System frequency in hz. :param SpeedOfSound=: Speed of Sound in m/s. :param CyclesPerElement=: Cycles per element. :return: Maximum velocity the ADCP can read in m/s. """ # Get the configuration from the json file script_dir = os.path.dirname(__file__) json_file_path = os.path.join(script_dir, 'predictor.json') try: config = json.loads(open(json_file_path).read()) except Exception as e: print("Error getting the configuration file. MaxVelocity", e) return 0.0 # _CWPBB_LagLength_, _BeamAngle_, _SystemFrequency_, _SpeedOfSound_, _CyclesPerElement_ return _calculate_max_velocity(kwargs.pop('CWPBB', config['DEFAULT']['CWPBB']), kwargs.pop('CWPBB_LagLength', config['DEFAULT']['CWPBB_LagLength']), kwargs.pop('CWPBS', config['DEFAULT']['CWPBS']), kwargs.pop('BeamAngle', config['BeamAngle']), kwargs.pop('SystemFrequency', config['DEFAULT']['SystemFrequency']), kwargs.pop('SpeedOfSound', config['SpeedOfSound']), kwargs.pop('CyclesPerElement', config['CyclesPerElement'])) def _calculate_max_velocity(_CWPBB_, _CWPBB_LagLength_, _CWPBS_, _BeamAngle_, _SystemFrequency_, _SpeedOfSound_, _CyclesPerElement_): """ Calculate the maximum velocity the ADCP can measure including the boat speed in m/s. This speed is the speed the ADCP is capable of measuring, if the speed exceeds this value, then the data will be incorrect due to rollovers. :param _CWPBB_ Broadband or Narrowband. :param _CWPBB_LagLength_: WP lag length in meters. :param _BeamAngle_: Beam angle in degrees. :param _SystemFrequency_: System frequency in hz. :param _SpeedOfSound_: Speed of Sound in m/s. :param _CyclesPerElement_: Cycles per element. :return: Maximum velocity the ADCP can read in m/s. """ # Get the configuration from the json file script_dir = os.path.dirname(__file__) json_file_path = os.path.join(script_dir, 'predictor.json') try: config = json.loads(open(json_file_path).read()) except Exception as e: print("Error getting the configuration file. MaxVelocity", e) return 0.0 # Prevent divide by 0 if _CyclesPerElement_ == 0: _CyclesPerElement_ = 1 if _SpeedOfSound_ == 0: _SpeedOfSound_ = 1490 if _SystemFrequency_ == 0: _SystemFrequency_ = config["DEFAULT"]["1200000"]["FREQ"] # Sample Rate sumSampling = 0.0; if _SystemFrequency_ > config["DEFAULT"]["1200000"]["FREQ"]: # 1200 khz sumSampling += config["DEFAULT"]["1200000"]["SAMPLING"] * config["DEFAULT"]["1200000"]["CPE"] / _CyclesPerElement_ elif (_SystemFrequency_ > config["DEFAULT"]["600000"]["FREQ"]) and (_SystemFrequency_ < config["DEFAULT"]["1200000"]["FREQ"]): # 600 khz sumSampling += config["DEFAULT"]["600000"]["SAMPLING"] * config["DEFAULT"]["600000"]["CPE"] / _CyclesPerElement_ elif (_SystemFrequency_ > config["DEFAULT"]["300000"]["FREQ"]) and (_SystemFrequency_ < config["DEFAULT"]["600000"]["FREQ"]): # 300 khz sumSampling += config["DEFAULT"]["300000"]["SAMPLING"] * config["DEFAULT"]["300000"]["CPE"] / _CyclesPerElement_ elif (_SystemFrequency_ > config["DEFAULT"]["150000"]["FREQ"]) and (_SystemFrequency_ < config["DEFAULT"]["300000"]["FREQ"]): # 150 khz sumSampling += config["DEFAULT"]["150000"]["SAMPLING"] * config["DEFAULT"]["150000"]["CPE"] / _CyclesPerElement_ elif (_SystemFrequency_ > config["DEFAULT"]["75000"]["FREQ"]) and (_SystemFrequency_ < config["DEFAULT"]["150000"]["FREQ"]): # 75 khz sumSampling += config["DEFAULT"]["75000"]["SAMPLING"] * config["DEFAULT"]["75000"]["CPE"] / _CyclesPerElement_ elif (_SystemFrequency_ > config["DEFAULT"]["38000"]["FREQ"]) and (_SystemFrequency_ < config["DEFAULT"]["75000"]["FREQ"]): # 38 khz sumSampling += config["DEFAULT"]["38000"]["SAMPLING"] * config["DEFAULT"]["38000"]["CPE"] / _CyclesPerElement_ sampleRate = _SystemFrequency_ * (sumSampling) # Meters Per Sample metersPerSample = 0 if sampleRate == 0: metersPerSample = 0.0 else: metersPerSample = math.cos(_BeamAngle_ / 180.0 * math.pi) * _SpeedOfSound_ / 2.0 / sampleRate # Lag Samples lagSamples = 0 if metersPerSample == 0: lagSamples = 0 else: lagSamples = 2 * math.trunc((math.trunc(_CWPBB_LagLength_ / metersPerSample) + 1.0) / 2.0) # Ua Hz uaHz = 0.0 if lagSamples == 0: uaHz = 0.0 else: uaHz = sampleRate / (2.0 * lagSamples) # Ua Radial uaRadial = 0.0 if _SystemFrequency_ == 0: uaRadial = 0.0 else: uaRadial = uaHz * _SpeedOfSound_ / (2.0 * _SystemFrequency_) #### NARROWBAND #### # Beam Angle Radian beamAngleRad = _BeamAngle_ / 180.0 * math.pi # Ta Ta = 2.0 * _CWPBS_ / _SpeedOfSound_ / math.cos(beamAngleRad) # L L = 0.5 * _SpeedOfSound_ * Ta # Check for vertical beam.No Beam angle if _BeamAngle_ == 0: return uaRadial # Narrowband lag length if _CWPBB_ == 0: return L / math.sin(_BeamAngle_ / 180.0 * math.pi) return uaRadial / math.sin(_BeamAngle_ / 180.0 * math.pi) # UNIT TEST # Run with pytext MaxVelocity.py def test_narrowband(): assert pytest.approx(calculate_max_velocity(CWPBB=0, CWPBB_LagLength=1.0, CWPBS=0.60, BeamAngle=20, SystemFrequency=1152000, SpeedOfSound=1467), 0.001) == 1.867 def test_broadband(): assert pytest.approx(calculate_max_velocity(CWPBB=1, CWPBB_LagLength=1.0, CWPBS=0.60, BeamAngle=20, SystemFrequency=1152000, SpeedOfSound=1490), 0.001) == 0.658 def test_broadband300(): assert pytest.approx(calculate_max_velocity(CWPBB=1, CWPBB_LagLength=1.0, CWPBS=4.0, BeamAngle=20, SystemFrequency=288000.0, SpeedOfSound=1490), 0.001) == 2.669
bsd-3-clause
thfield/sf-base-election-data
pyelect/utils.py
2
4805
"""Project-wide helper functions.""" import logging import os import yaml _log = logging.getLogger() FILE_MANUAL = 'manual' FILE_AUTO_GENERATED = 'auto_generated' FILE_AUTO_UPDATED = 'auto_updated' FILE_TYPES = (FILE_MANUAL, FILE_AUTO_UPDATED, FILE_AUTO_GENERATED) DIR_PRE_DATA = 'pre_data' KEY_META_COMMENTS = 'comments' KEY_META = '_meta' KEY_META_COMMENTS = 'comments' KEY_FILE_TYPE = '_type' KEY_FILE_TYPE_COMMENT = '_type_comment' FILE_TYPE_COMMENTS = { FILE_AUTO_UPDATED: "WARNING: this file is auto-updated. Any YAML comments will be deleted.", FILE_AUTO_GENERATED: "WARNING: this file is auto-generated. Do not edit this file!", } # The idea for this comes from here: # http://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data def _yaml_str_representer(dumper, data): """A PyYAML representer that uses literal blocks for multi-line strings. For example-- long: | This is a multi-line string. short: This is a one-line string. """ style = '|' if '\n' in data else None return dumper.represent_scalar('tag:yaml.org,2002:str', data, style=style) yaml.add_representer(str, _yaml_str_representer) def filter_dict_by_keys(data, keys): return {k: v for k, v in data.items() if k in keys} def get_required(dict_, key, message=None): try: value = dict_[key] except: raise Exception("error getting key {0!r} from: {1!r} message={2}" .format(key, dict_, message)) return value def get_repo_dir(): repo_dir = os.path.join(os.path.dirname(__file__), os.pardir) return os.path.abspath(repo_dir) def get_pre_data_dir(): repo_dir = get_repo_dir() dir_path = os.path.join(repo_dir, DIR_PRE_DATA) return dir_path def write(path, text): _log.info("writing to: {0}".format(path)) with open(path, mode='w') as f: f.write(text) def read_yaml(path): with open(path) as f: data = yaml.load(f) return data def read_yaml_rel(rel_path, file_base=None, key=None): """Return the data in a YAML file as a Python dict. Arguments: rel_path: the path to the file relative to the repo root. key: optionally, the key-value to return. """ if file_base is not None: file_name = "{0}.yaml".format(file_base) rel_path = os.path.join(rel_path, file_name) repo_dir = get_repo_dir() path = os.path.join(repo_dir, rel_path) data = read_yaml(path) if key is not None: data = data[key] return data def yaml_dump(*args): return yaml.dump(*args, default_flow_style=False, allow_unicode=True, default_style=None) def _write_yaml(data, path, stdout=None): if stdout is None: stdout = False with open(path, "w") as f: yaml_dump(data, f) if stdout: print(yaml_dump(data)) def get_yaml_meta(data): return get_required(data, KEY_META) def _get_yaml_file_type_from_meta(meta): file_type = get_required(meta, KEY_FILE_TYPE) if file_type not in FILE_TYPES: raise Exception('bad file type: {0}'.format(file_type)) return file_type def _get_yaml_file_type(data): meta = get_yaml_meta(data) file_type = _get_yaml_file_type_from_meta(meta) return file_type def _set_header(data, file_type, comments=None): meta = data.setdefault(KEY_META, {}) if file_type is None: # Then we require that the file type already be specified. file_type = _get_yaml_file_type_from_meta(meta) else: meta[KEY_FILE_TYPE] = file_type comment = FILE_TYPE_COMMENTS.get(file_type) if comment: meta[KEY_FILE_TYPE_COMMENT] = comment if comments is not None: meta[KEY_META_COMMENTS] = comments def write_yaml_with_header(data, rel_path, file_type=None, comments=None, stdout=None): repo_dir = get_repo_dir() path = os.path.join(repo_dir, rel_path) _set_header(data, file_type=file_type, comments=comments) _write_yaml(data, path, stdout=stdout) def _is_yaml_normalizable(data, path_hint): try: file_type = _get_yaml_file_type(data) except: raise Exception("for file: {0}".format(path_hint)) # Use a white list instead of a black list to be safe. return file_type in (FILE_AUTO_UPDATED, FILE_AUTO_GENERATED) def is_yaml_file_normalizable(path): data = read_yaml(path) return _is_yaml_normalizable(data, path_hint=path) def normalize_yaml(path, stdout=None): data = read_yaml(path) normalizable = _is_yaml_normalizable(data, path_hint=path) if not normalizable: _log.info("skipping normalization: {0}".format(path)) return write_yaml_with_header(data, path, stdout=stdout)
bsd-3-clause
fitoria/askbot-devel
askbot/templatetags/extra_tags.py
5
4049
import math from django import template from django.template import RequestContext from django.template.loader import get_template from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from askbot.utils import functions from askbot.utils.slug import slugify from askbot.conf import settings as askbot_settings register = template.Library() GRAVATAR_TEMPLATE = ( '<a style="text-decoration:none" ' 'href="%(user_profile_url)s"><img class="gravatar" ' 'width="%(size)s" height="%(size)s" ' 'src="//www.gravatar.com/avatar/%(gravatar_hash)s' '?s=%(size)s&amp;d=%(gravatar_type)s&amp;r=PG" ' 'title="%(username)s" ' 'alt="%(alt_text)s" /></a>') @register.simple_tag def gravatar(user, size): """ Creates an ``<img>`` for a user's Gravatar with a given size. This tag can accept a User object, or a dict containing the appropriate values. """ #todo: rewrite using get_from_dict_or_object user_id = functions.get_from_dict_or_object(user, 'id') slug = slugify(user.username) user_profile_url = reverse( 'user_profile', kwargs={'id':user_id, 'slug':slug} ) #safe_username = template.defaultfilters.urlencode(username) return mark_safe(GRAVATAR_TEMPLATE % { 'user_profile_url': user_profile_url, 'size': size, 'gravatar_hash': functions.get_from_dict_or_object(user, 'gravatar'), 'gravatar_type': askbot_settings.GRAVATAR_TYPE, 'alt_text': _('%(username)s gravatar image') % {'username': user.username}, 'username': functions.get_from_dict_or_object(user, 'username'), }) @register.simple_tag def get_tag_font_size(tags): max_tag = 0 for tag in tags: if tag.used_count > max_tag: max_tag = tag.used_count min_tag = max_tag for tag in tags: if tag.used_count < min_tag: min_tag = tag.used_count font_size = {} for tag in tags: font_size[tag.name] = tag_font_size(max_tag,min_tag,tag.used_count) return font_size @register.simple_tag def tag_font_size(max_size, min_size, current_size): """ do a logarithmic mapping calcuation for a proper size for tagging cloud Algorithm from http://blogs.dekoh.com/dev/2007/10/29/choosing-a-good- font-size-variation-algorithm-for-your-tag-cloud/ """ MAX_FONTSIZE = 10 MIN_FONTSIZE = 1 #avoid invalid calculation if current_size == 0: current_size = 1 try: weight = (math.log10(current_size) - math.log10(min_size)) / (math.log10(max_size) - math.log10(min_size)) except Exception: weight = 0 return int(MIN_FONTSIZE + round((MAX_FONTSIZE - MIN_FONTSIZE) * weight)) class IncludeJinja(template.Node): """http://www.mellowmorning.com/2010/08/24/""" def __init__(self, filename, request_var): self.filename = filename self.request_var = template.Variable(request_var) def render(self, context): request = self.request_var.resolve(context) jinja_template = get_template(self.filename) return jinja_template.render(RequestContext(request, context)) @register.tag def include_jinja(parser, token): bits = token.contents.split() #Check if a filename was given if len(bits) != 3: error_message = '%r tag requires the name of the ' + \ 'template and the request variable' raise template.TemplateSyntaxError(error_message % bits[0]) filename = bits[1] request_var = bits[2] #Remove quotes or raise error if filename[0] in ('"', "'") and filename[-1] == filename[0]: filename = filename[1:-1] else: raise template.TemplateSyntaxError('file name must be quoted') return IncludeJinja(filename, request_var)
gpl-3.0
mhoffman/catmap
catmap/scalers/generalized_linear_scaler.py
1
21573
from .scaler_base import * from catmap.data import regular_expressions from catmap.functions import parse_constraint from math import isnan import pylab as plt class GeneralizedLinearScaler(ScalerBase): """ :TODO: """ def __init__(self,reaction_model = None): ScalerBase.__init__(self,reaction_model) defaults = dict(default_constraints=['+','+',None], parameter_mode = 'formation_energy', transition_state_scaling_parameters={}, transition_state_scaling_mode = 'initial_state', transition_state_cross_interaction_mode = 'transition_state_scaling', max_self_interaction = 'Pd', default_interaction_constraints = None, avoid_scaling = False, #if the descriptors are equal to a metal, #use the real values for that metal rather #than scaled values ) self._rxm.update(defaults,override=False) self._required = {'default_constraints':list, 'parameter_mode':str, 'avoid_scaling':None} def parameterize(self): """ :TODO: """ #Check that descriptors are in reaction network all_ads = list(self.adsorbate_names) + list(self.transition_state_names) for d in self.descriptor_names: #REMOVE THIS REQUIREMENT LATER? if d not in all_ads: raise AttributeError('Descriptor '+d+' does not appear in reaction'+\ ' network. Add descriptor to network via "dummy" site, or '+\ 'use an adsorbate from the network as a descriptor.') if not self.parameter_dict or not self.descriptor_dict: parameter_dict = {} descriptor_dict = {} for species in self.species_definitions: Ef = self.species_definitions[species].get('formation_energy',None) if isinstance(Ef, list) and len(Ef) == len(self.surface_names): parameter_dict[species] = Ef for s_id, surf in enumerate(self.surface_names): desc_list = [] for desc in self.descriptor_names: try: desc_val = self.species_definitions[desc] desc_val = desc_val['formation_energy'][s_id] desc_val = float(desc_val) desc_list.append(desc_val) except: raise ValueError( 'All surfaces must have numeric descriptor values: '+surf) descriptor_dict[surf] = desc_list self.descriptor_dict = descriptor_dict self.parameter_dict = parameter_dict self.parameter_names = self.adsorbate_names + self.transition_state_names def get_coefficient_matrix(self): """ :TODO: """ self.parameterize() if not self.scaling_constraint_dict: self.scaling_constraint_dict = {} for ads in self.adsorbate_names: self.scaling_constraint_dict[ads] = self.default_constraints self.parse_constraints( self.scaling_constraint_dict) all_coeffs = [] all_coeffs += list(self.get_adsorbate_coefficient_matrix()) all_coeffs += list(self.get_transition_state_coefficient_matrix()) # populate all TS rows using direct scaling with the correct coefficients for i, TS in enumerate(self.transition_state_names): if TS in self.scaling_constraint_dict and isinstance( self.scaling_constraint_dict[TS], list): TS_row = i + len(self.adsorbate_names) all_coeffs[TS_row] = self.total_coefficient_dict[TS] if self.adsorbate_interaction_model not in [None,'ideal']: self.thermodynamics.adsorbate_interactions.parameterize_interactions() all_coeffs += list( self.thermodynamics.adsorbate_interactions.get_interaction_scaling_matrix()) all_coeffs = np.array(all_coeffs) self.coefficient_matrix = all_coeffs return all_coeffs def get_adsorbate_coefficient_matrix(self): """Calculate coefficients for scaling all adsorbates and transition states using constrained optimization. Store results in self.total_coefficient_dict and return the coefficient matrix for the adsorbates only. """ n_ads = len(self.parameter_names) C = catmap.functions.scaling_coefficient_matrix( self.parameter_dict, self.descriptor_dict, self.surface_names, self.parameter_names, self.coefficient_mins,self.coefficient_maxs) self.adsorbate_coefficient_matrix = C.T[:len(self.adsorbate_names),:] self.total_coefficient_dict = dict(zip(self.parameter_names, C.T)) return self.adsorbate_coefficient_matrix def get_transition_state_coefficient_matrix(self): """ :TODO: """ self.get_transition_state_scaling_matrix() if self.transition_state_scaling_matrix is not None: if self.adsorbate_coefficient_matrix is None: self.get_adsorbate_coefficient_matrix() coeffs = np.dot(self.transition_state_scaling_matrix[:,:-1], self.adsorbate_coefficient_matrix) coeffs[:,-1] += self.transition_state_scaling_matrix[:,-1] self.transition_state_coefficient_matrix = coeffs else: coeffs = np.array([]) return coeffs def get_transition_state_scaling_matrix(self): """ :TODO: """ #This function is godawful and needs to be cleaned up considerably... #156 lines is unacceptable for something so simple. #HACK def state_scaling(TS,params,mode): coeffs = [0]*len(self.adsorbate_names) rxn_def = None for rxn in self.elementary_rxns: if len(rxn) == 3: if TS in rxn[1]: if rxn_def is None: rxn_def = rxn else: rxn_def = rxn print('Warning: ambiguous IS for '+TS+\ '; Using'+self.print_rxn(rxn,mode='text')) if rxn_def is None: raise ValueError(TS+' does not appear in any reactions!') if mode == 'final_state': FS = rxn_def[-1] IS = [] elif mode == 'initial_state': FS = rxn_def[0] IS = [] elif mode == 'BEP': IS = rxn_def[0] FS = rxn_def[-1] elif mode == 'explicit': IS = [] FS = params[0] params = params[1] else: raise ValueError('Invalid Mode') def get_energy_list(state,coeff_sign): energies = [] for ads in state: if ads in self.adsorbate_names: idx = self.adsorbate_names.index(ads) coeffs[idx] += coeff_sign Ef = self.species_definitions[ads]['formation_energy'] if isinstance(Ef, list): energies.append(Ef) else: energies.append([0]*len(self.surface_names)) return energies IS_energies = get_energy_list(IS,-1) FS_energies = get_energy_list(FS,+1) if params and len(params) == 2: m,b = [float(pi) for pi in params] else: FS_totals = [] for Evec in zip(*FS_energies): if None not in Evec: FS_totals.append(sum(Evec)) else: FS_totals.append(None) IS_totals = [] for Evec in zip(*IS_energies): if None not in Evec: IS_totals.append(sum(Evec)) else: IS_totals.append(None) TS_energies = self.parameter_dict[TS] valid_xy = [] if mode in ['initial_state','final_state','explicit']: for xy in zip(FS_totals,TS_energies): if None not in xy: valid_xy.append(xy) elif mode in ['BEP']: for I,F,T in zip(IS_totals,FS_totals,TS_energies): if None not in [I,F,T]: valid_xy.append([F-I,T-I]) x,y = zip(*valid_xy) if params and len(params) == 1: m,b = catmap.functions.linear_regression(x,y,params[0]) elif params is None: m,b = catmap.functions.linear_regression(x,y) else: raise UserWarning('Invalid params') if isnan(m) or isnan(b): raise UserWarning('Transition-state scaling failed for: '+TS+\ '. Ensure that the scaling mode is set properly.') if mode == 'BEP': coeff_vals = [] for k,ck in enumerate(coeffs): ads = self.adsorbate_names[k] if ads in IS: coeff_vals.append((1.-m)*abs(ck)) elif ads in FS: coeff_vals.append(m*abs(ck)) else: coeff_vals.append(ck) offset = 0. if params and len(params) == 2: for gas in self.gas_names: if gas in IS: offset += (1.-m)*self.species_definitions[gas]['formation_energy'] elif gas in FS: offset += m*self.species_definitions[gas]['formation_energy'] else: continue coeff_vals.append(b+offset) else: coeff_vals = [m*ci for ci in coeffs] + [b] return [m,b],coeff_vals def initial_state_scaling(TS,params): return state_scaling(TS,params,'initial_state') def final_state_scaling(TS,params): return state_scaling(TS,params,'final_state') def BEP_scaling(TS,params): return state_scaling(TS,params,'BEP') def explicit_state_scaling(TS,params): return state_scaling(TS,params,'explicit') def echem_state_scaling(TS,params): #ugly workaround for ambiguous echem TS names in rxn definitions return [0,0], [0]*len(self.adsorbate_names) + [0] def direct_scaling(TS,params): # dummy scaling parameters for direct scaling return [0,0], [0]*len(self.adsorbate_names) + [0] TS_scaling_functions = { 'initial_state':initial_state_scaling, 'final_state':final_state_scaling, 'BEP':BEP_scaling, 'TS':explicit_state_scaling, 'echem':echem_state_scaling, 'direct':direct_scaling, } TS_matrix = [] TS_coeffs = [] for TS in self.transition_state_names: if TS in self.echem_transition_state_names: mode = 'echem' params = None elif TS in self.scaling_constraint_dict and isinstance( self.scaling_constraint_dict[TS], list): mode = 'direct' params = None elif TS in self.scaling_constraint_dict: constring = self.scaling_constraint_dict[TS] if not isinstance(constring, str): raise ValueError('Constraints must be strings: '\ +repr(constring)) match_dict = self.match_regex(constring, *regular_expressions[ 'transition_state_scaling_constraint']) if match_dict is None: raise ValueError('Invalid constraint: '+constring) mode = match_dict['mode'] species_list = match_dict['species_list'] state_list = [] if species_list: species_list = species_list.split('+') for sp in species_list: sp = sp.strip() if '_' not in sp: sp = sp+'_'+self._default_site state_list.append(sp) if match_dict['parameter_key']: key = match_dict['parameter_key'] if key in self.transition_state_scaling_parameters: parameter_list = \ self.transition_state_scaling_parameters[key] else: raise KeyError('The key '+key+' must be defined '+\ 'in transition_state_scaling_parameters') elif match_dict['parameter_list']: parameter_list = eval(match_dict['parameter_list']) else: parameter_list = None if state_list: params = [state_list,parameter_list] else: params = parameter_list else: mode = self.transition_state_scaling_mode params = None try: mb,coeffs=TS_scaling_functions[mode](TS,params) TS_matrix.append(coeffs) TS_coeffs.append(mb) except KeyError: raise NotImplementedError( 'Invalid transition-state scaling mode specified') TS_matrix = np.array(TS_matrix) self.transition_state_scaling_matrix = TS_matrix self.transition_state_scaling_coefficients = TS_coeffs return TS_matrix def get_electronic_energies(self,descriptors): """ :TODO: """ E_dict = {} full_descriptors = list(descriptors) + [1] if self.coefficient_matrix is None: self.coefficient_matrix = self.get_coefficient_matrix() adsorption_energies = np.dot(self.coefficient_matrix,full_descriptors) n_ads = len(self.adsorbate_names) for sp in self.species_definitions: if sp in self.adsorbate_names: idx = self.adsorbate_names.index(sp) E_dict[sp] = adsorption_energies[idx] elif sp in self.transition_state_names: idx = self.transition_state_names.index(sp) E_dict[sp] = adsorption_energies[idx+n_ads] elif self.species_definitions[sp].get('type',None) in ['site','gas']: E_dict[sp] = self.species_definitions[sp]['formation_energy'] if self.avoid_scaling == True: #Check to see if the descriptors #corrsepond to a surface. If so, return all possible energies #for that surface instead of using scaling. n = self.descriptor_decimal_precision if not n: n = 2 roundvals = [] for ds in self.descriptor_dict.values(): roundvals.append([round(di,n) for di in ds]) if [round(di,n) for di in descriptors] in roundvals: for surf in self.descriptor_dict: if ([round(di,n) for di in self.descriptor_dict[surf]] == [round(di,n) for di in descriptors]): surf_id = self.surface_names.index(surf) for ads in self.adsorbate_names+self.transition_state_names: E = self.parameter_dict[ads][surf_id] if E != None: E_dict[ads] = E else: pass #do nothing if the descriptors do not correspond to a surf for dname in self.descriptor_names: if dname in E_dict: E_dict[dname] = descriptors[self.descriptor_names.index(dname)] return E_dict def get_rxn_parameters(self,descriptors, *args, **kwargs): """ :TODO: """ if self.adsorbate_interaction_model not in ['ideal',None]: params = self.get_formation_energy_interaction_parameters(descriptors) return params else: params = self.get_formation_energy_parameters(descriptors) return params def get_formation_energy_parameters(self,descriptors): """ :TODO: """ free_energy_dict = self.get_free_energies(descriptors) params = [] for ads in self.adsorbate_names + self.transition_state_names: params.append(free_energy_dict[ads]) return params def get_formation_energy_interaction_parameters(self,descriptors): """ :TODO: """ E_f = self.get_formation_energy_parameters(descriptors) epsilon = self.thermodynamics.adsorbate_interactions.get_interaction_matrix(descriptors) epsilon = list(epsilon.ravel()) return E_f + epsilon def parse_constraints(self,constraint_dict): """This function converts constraints which are input as a dictionary to lists compatible with the function to obtain scaling coefficients.""" coefficient_mins = [] coefficient_maxs = [] if constraint_dict: for key in constraint_dict.keys(): if '_' not in key: constraint_dict[key+'_'+self._default_site] = \ constraint_dict[key] del constraint_dict[key] for ads in self.parameter_names: if ads not in constraint_dict: constr = self.default_constraints elif not isinstance(constraint_dict[ads], list): constr = self.default_constraints else: constr = constraint_dict[ads] minvs,maxvs = parse_constraint(constr,ads) coefficient_mins.append(minvs) coefficient_maxs.append(maxvs) self.coefficient_mins = coefficient_mins self.coefficient_maxs = coefficient_maxs return coefficient_mins, coefficient_maxs def summary_text(self): """ :TODO: """ str_dict = {} labs = ['E_{'+self.texify(l)+'}' for l in self.descriptor_names] + [''] for coeffs,ads in zip(self.get_coefficient_matrix(), self.adsorbate_names+self.transition_state_names): if ads not in self.descriptor_names: scaling_txt = 'E_{'+self.texify(ads)+'} = ' for c,lab in zip(coeffs,labs): if c: scaling_txt += str(float(round(c,3)))+lab+' + ' if scaling_txt.endswith(' + '): scaling_txt = scaling_txt[:-3] scaling_txt = scaling_txt.replace(' + -',' - ') str_dict[ads] = scaling_txt out_txt = '\n'+r'Adsorption Scaling Parameters\\' i = 0 for ads in self.adsorbate_names: if ads in str_dict: i+=1 out_txt += '\n'+r'\begin{equation}' out_txt += '\n'+r'\label{ads_scaling_'+str(i)+'}' out_txt += '\n' + str_dict[ads] out_txt += '\n'+r'\end{equation}' out_txt += '\n'+r'Transition-state Scaling Parameters\\' i = 0 for ads in self.transition_state_names: i += 1 out_txt += '\n'+r'\begin{equation}' out_txt += '\n'+r'\label{TS_scaling_'+str(i)+'}' if ads in self.scaling_constraint_dict: constr = self.scaling_constraint_dict[ads] if 'TS' in constr: x,par = constr.split(':') x = x.replace('TS','').replace('(','').replace(')','') x_str = [] for adsx in x.split('+'): adsx = adsx.strip() adsx_str = 'E_{'+self.texify(adsx)+'}' x_str.append(adsx_str) x_str = ' + '.join(x_str) x_str = '('+x_str+')' if par in self.transition_state_scaling_parameters: ab = self.transition_state_scaling_parameters[par][0:2] alpha,beta = ab else: alpha,beta = eval(par)[0:2] out_txt += '\n'+ 'E_{'+self.texify(ads)+'} = ' + \ str(round(alpha,3))+x_str+' + ' + str(round(beta,3)) else: out_txt += '\n' + str_dict[ads] else: out_txt += '\n' + str_dict[ads] out_txt += '\n'+r'\end{equation}' return out_txt
gpl-3.0
vrsys/avango
attic/examples/display/test_app_3.py
6
2049
# -*- Mode:Python -*- ########################################################################## # # # This file is part of AVANGO. # # # # Copyright 1997 - 2010 Fraunhofer-Gesellschaft zur Foerderung der # # angewandten Forschung (FhG), Munich, Germany. # # # # AVANGO 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, version 3. # # # # AVANGO 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 Lesser General Public # # License along with AVANGO. If not, see <http://www.gnu.org/licenses/>. # # # ########################################################################## import avango import avango.osg import avango.display import sys argv = avango.display.init(sys.argv) wiimote = avango.display.make_dominant_user_device() sphere_transform = avango.osg.nodes.MatrixTransform() sphere_transform.Matrix.connect_from(wiimote.Matrix) sphere = avango.osg.nodes.Sphere(Radius=0.3, Matrix=avango.osg.make_trans_mat(0, 1.2, -3)) sphere_transform.Children.value = [sphere] view = avango.display.make_view() view.EnableTrackball.value = True view.Root.value = sphere_transform avango.display.run()
lgpl-3.0
django-nonrel/django
django/dispatch/dispatcher.py
102
11075
import weakref import threading from django.dispatch import saferef from django.utils.six.moves import xrange WEAKREF_TYPES = (weakref.ReferenceType, saferef.BoundMethodWeakref) def _make_id(target): if hasattr(target, '__func__'): return (id(target.__self__), id(target.__func__)) return id(target) NONE_ID = _make_id(None) # A marker for caching NO_RECEIVERS = object() class Signal(object): """ Base class for all signals Internal attributes: receivers { receriverkey (id) : weakref(receiver) } """ def __init__(self, providing_args=None, use_caching=False): """ Create a new signal. providing_args A list of the arguments this signal can pass along in a send() call. """ self.receivers = [] if providing_args is None: providing_args = [] self.providing_args = set(providing_args) self.lock = threading.Lock() self.use_caching = use_caching # For convenience we create empty caches even if they are not used. # A note about caching: if use_caching is defined, then for each # distinct sender we cache the receivers that sender has in # 'sender_receivers_cache'. The cache is cleaned when .connect() or # .disconnect() is called and populated on send(). self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {} def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): """ Connect receiver to sender for signal. Arguments: receiver A function or an instance method which is to receive signals. Receivers must be hashable objects. If weak is True, then receiver must be weak-referencable (more precisely saferef.safeRef() must be able to create a reference to the receiver). Receivers must be able to accept keyword arguments. If receivers have a dispatch_uid attribute, the receiver will not be added if another receiver already exists with that dispatch_uid. sender The sender to which the receiver should respond. Must either be of type Signal, or None to receive events from any sender. weak Whether to use weak references to the receiver. By default, the module will attempt to use weak references to the receiver objects. If this parameter is false, then strong references will be used. dispatch_uid An identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. """ from django.conf import settings # If DEBUG is on, check that we got a good receiver if settings.configured and settings.DEBUG: import inspect assert callable(receiver), "Signal receivers must be callable." # Check for **kwargs # Not all callables are inspectable with getargspec, so we'll # try a couple different ways but in the end fall back on assuming # it is -- we don't want to prevent registration of valid but weird # callables. try: argspec = inspect.getargspec(receiver) except TypeError: try: argspec = inspect.getargspec(receiver.__call__) except (TypeError, AttributeError): argspec = None if argspec: assert argspec[2] is not None, \ "Signal receivers must accept keyword arguments (**kwargs)." if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) if weak: receiver = saferef.safeRef(receiver, onDelete=self._remove_receiver) with self.lock: for r_key, _ in self.receivers: if r_key == lookup_key: break else: self.receivers.append((lookup_key, receiver)) self.sender_receivers_cache.clear() def disconnect(self, receiver=None, sender=None, weak=True, dispatch_uid=None): """ Disconnect receiver from sender for signal. If weak references are used, disconnect need not be called. The receiver will be remove from dispatch automatically. Arguments: receiver The registered receiver to disconnect. May be none if dispatch_uid is specified. sender The registered sender to disconnect weak The weakref state to disconnect dispatch_uid the unique identifier of the receiver to disconnect """ if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) with self.lock: for index in xrange(len(self.receivers)): (r_key, _) = self.receivers[index] if r_key == lookup_key: del self.receivers[index] break self.sender_receivers_cache.clear() def has_listeners(self, sender=None): return bool(self._live_receivers(sender)) def send(self, sender, **named): """ Send signal from sender to all connected receivers. If any receiver raises an error, the error propagates back through send, terminating the dispatch loop, so it is quite possible to not have all receivers called if a raises an error. Arguments: sender The sender of the signal Either a specific object or None. named Named arguments which will be passed to receivers. Returns a list of tuple pairs [(receiver, response), ... ]. """ responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses for receiver in self._live_receivers(sender): response = receiver(signal=self, sender=sender, **named) responses.append((receiver, response)) return responses def send_robust(self, sender, **named): """ Send signal from sender to all connected receivers catching errors. Arguments: sender The sender of the signal. Can be any python object (normally one registered with a connect if you actually want something to occur). named Named arguments which will be passed to receivers. These arguments must be a subset of the argument names defined in providing_args. Return a list of tuple pairs [(receiver, response), ... ]. May raise DispatcherKeyError. If any receiver raises an error (specifically any subclass of Exception), the error instance is returned as the result for that receiver. """ responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. for receiver in self._live_receivers(sender): try: response = receiver(signal=self, sender=sender, **named) except Exception as err: responses.append((receiver, err)) else: responses.append((receiver, response)) return responses def _live_receivers(self, sender): """ Filter sequence of receivers to get resolved, live receivers. This checks for weak references and resolves them, then returning only live receivers. """ receivers = None if self.use_caching: receivers = self.sender_receivers_cache.get(sender) # We could end up here with NO_RECEIVERS even if we do check this case in # .send() prior to calling _live_receivers() due to concurrent .send() call. if receivers is NO_RECEIVERS: return [] if receivers is None: with self.lock: senderkey = _make_id(sender) receivers = [] for (receiverkey, r_senderkey), receiver in self.receivers: if r_senderkey == NONE_ID or r_senderkey == senderkey: receivers.append(receiver) if self.use_caching: if not receivers: self.sender_receivers_cache[sender] = NO_RECEIVERS else: # Note, we must cache the weakref versions. self.sender_receivers_cache[sender] = receivers non_weak_receivers = [] for receiver in receivers: if isinstance(receiver, WEAKREF_TYPES): # Dereference the weak reference. receiver = receiver() if receiver is not None: non_weak_receivers.append(receiver) else: non_weak_receivers.append(receiver) return non_weak_receivers def _remove_receiver(self, receiver): """ Remove dead receivers from connections. """ with self.lock: to_remove = [] for key, connected_receiver in self.receivers: if connected_receiver == receiver: to_remove.append(key) for key in to_remove: last_idx = len(self.receivers) - 1 # enumerate in reverse order so that indexes are valid even # after we delete some items for idx, (r_key, _) in enumerate(reversed(self.receivers)): if r_key == key: del self.receivers[last_idx - idx] self.sender_receivers_cache.clear() def receiver(signal, **kwargs): """ A decorator for connecting receivers to signals. Used by passing in the signal (or list of signals) and keyword arguments to connect:: @receiver(post_save, sender=MyModel) def signal_receiver(sender, **kwargs): ... @receiver([post_save, post_delete], sender=MyModel) def signals_receiver(sender, **kwargs): ... """ def _decorator(func): if isinstance(signal, (list, tuple)): for s in signal: s.connect(func, **kwargs) else: signal.connect(func, **kwargs) return func return _decorator
bsd-3-clause
r3tard/BartusBot
lib/google/protobuf/internal/message_listener.py
264
3367
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Defines a listener interface for observing certain state transitions on Message objects. Also defines a null implementation of this interface. """ __author__ = '[email protected] (Will Robinson)' class MessageListener(object): """Listens for modifications made to a message. Meant to be registered via Message._SetListener(). Attributes: dirty: If True, then calling Modified() would be a no-op. This can be used to avoid these calls entirely in the common case. """ def Modified(self): """Called every time the message is modified in such a way that the parent message may need to be updated. This currently means either: (a) The message was modified for the first time, so the parent message should henceforth mark the message as present. (b) The message's cached byte size became dirty -- i.e. the message was modified for the first time after a previous call to ByteSize(). Therefore the parent should also mark its byte size as dirty. Note that (a) implies (b), since new objects start out with a client cached size (zero). However, we document (a) explicitly because it is important. Modified() will *only* be called in response to one of these two events -- not every time the sub-message is modified. Note that if the listener's |dirty| attribute is true, then calling Modified at the moment would be a no-op, so it can be skipped. Performance- sensitive callers should check this attribute directly before calling since it will be true most of the time. """ raise NotImplementedError class NullMessageListener(object): """No-op MessageListener implementation.""" def Modified(self): pass
apache-2.0
ebar0n/django
tests/template_backends/test_jinja2.py
94
3451
from unittest import skipIf from django.template import TemplateSyntaxError from django.test import RequestFactory from .test_dummy import TemplateStringsTests try: import jinja2 except ImportError: jinja2 = None Jinja2 = None else: from django.template.backends.jinja2 import Jinja2 @skipIf(jinja2 is None, "this test requires jinja2") class Jinja2Tests(TemplateStringsTests): engine_class = Jinja2 backend_name = 'jinja2' options = { 'keep_trailing_newline': True, 'context_processors': [ 'django.template.context_processors.static', ], } def test_origin(self): template = self.engine.get_template('template_backends/hello.html') self.assertTrue(template.origin.name.endswith('hello.html')) self.assertEqual(template.origin.template_name, 'template_backends/hello.html') def test_origin_from_string(self): template = self.engine.from_string('Hello!\n') self.assertEqual(template.origin.name, '<template>') self.assertIsNone(template.origin.template_name) def test_self_context(self): """ Using 'self' in the context should not throw errors (#24538). """ # self will be overridden to be a TemplateReference, so the self # variable will not come through. Attempting to use one though should # not throw an error. template = self.engine.from_string('hello {{ foo }}!') content = template.render(context={'self': 'self', 'foo': 'world'}) self.assertEqual(content, 'hello world!') def test_exception_debug_info_min_context(self): with self.assertRaises(TemplateSyntaxError) as e: self.engine.get_template('template_backends/syntax_error.html') debug = e.exception.template_debug self.assertEqual(debug['after'], '') self.assertEqual(debug['before'], '') self.assertEqual(debug['during'], '{% block %}') self.assertEqual(debug['bottom'], 1) self.assertEqual(debug['top'], 0) self.assertEqual(debug['line'], 1) self.assertEqual(debug['total'], 1) self.assertEqual(len(debug['source_lines']), 1) self.assertTrue(debug['name'].endswith('syntax_error.html')) self.assertIn('message', debug) def test_exception_debug_info_max_context(self): with self.assertRaises(TemplateSyntaxError) as e: self.engine.get_template('template_backends/syntax_error2.html') debug = e.exception.template_debug self.assertEqual(debug['after'], '') self.assertEqual(debug['before'], '') self.assertEqual(debug['during'], '{% block %}') self.assertEqual(debug['bottom'], 26) self.assertEqual(debug['top'], 5) self.assertEqual(debug['line'], 16) self.assertEqual(debug['total'], 31) self.assertEqual(len(debug['source_lines']), 21) self.assertTrue(debug['name'].endswith('syntax_error2.html')) self.assertIn('message', debug) def test_context_processors(self): request = RequestFactory().get('/') template = self.engine.from_string('Static URL: {{ STATIC_URL }}') content = template.render(request=request) self.assertEqual(content, 'Static URL: /static/') with self.settings(STATIC_URL='/s/'): content = template.render(request=request) self.assertEqual(content, 'Static URL: /s/')
bsd-3-clause
polyval/CNC
flask/Lib/site-packages/sqlalchemy/orm/descriptor_props.py
38
25141
# orm/descriptor_props.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Descriptor properties are more "auxiliary" properties that exist as configurational elements, but don't participate as actively in the load/persist ORM loop. """ from .interfaces import MapperProperty, PropComparator from .util import _none_set from . import attributes from .. import util, sql, exc as sa_exc, event, schema from ..sql import expression from . import properties from . import query class DescriptorProperty(MapperProperty): """:class:`.MapperProperty` which proxies access to a user-defined descriptor.""" doc = None def instrument_class(self, mapper): prop = self class _ProxyImpl(object): accepts_scalar_loader = False expire_missing = True collection = False def __init__(self, key): self.key = key if hasattr(prop, 'get_history'): def get_history(self, state, dict_, passive=attributes.PASSIVE_OFF): return prop.get_history(state, dict_, passive) if self.descriptor is None: desc = getattr(mapper.class_, self.key, None) if mapper._is_userland_descriptor(desc): self.descriptor = desc if self.descriptor is None: def fset(obj, value): setattr(obj, self.name, value) def fdel(obj): delattr(obj, self.name) def fget(obj): return getattr(obj, self.name) self.descriptor = property( fget=fget, fset=fset, fdel=fdel, ) proxy_attr = attributes.create_proxied_attribute( self.descriptor)( self.parent.class_, self.key, self.descriptor, lambda: self._comparator_factory(mapper), doc=self.doc, original_property=self ) proxy_attr.impl = _ProxyImpl(self.key) mapper.class_manager.instrument_attribute(self.key, proxy_attr) @util.langhelpers.dependency_for("sqlalchemy.orm.properties") class CompositeProperty(DescriptorProperty): """Defines a "composite" mapped attribute, representing a collection of columns as one attribute. :class:`.CompositeProperty` is constructed using the :func:`.composite` function. .. seealso:: :ref:`mapper_composite` """ def __init__(self, class_, *attrs, **kwargs): """Return a composite column-based property for use with a Mapper. See the mapping documentation section :ref:`mapper_composite` for a full usage example. The :class:`.MapperProperty` returned by :func:`.composite` is the :class:`.CompositeProperty`. :param class\_: The "composite type" class. :param \*cols: List of Column objects to be mapped. :param active_history=False: When ``True``, indicates that the "previous" value for a scalar attribute should be loaded when replaced, if not already loaded. See the same flag on :func:`.column_property`. .. versionchanged:: 0.7 This flag specifically becomes meaningful - previously it was a placeholder. :param group: A group name for this property when marked as deferred. :param deferred: When True, the column property is "deferred", meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also :func:`~sqlalchemy.orm.deferred`. :param comparator_factory: a class which extends :class:`.CompositeProperty.Comparator` which provides custom SQL clause generation for comparison operations. :param doc: optional string that will be applied as the doc on the class-bound descriptor. :param info: Optional data dictionary which will be populated into the :attr:`.MapperProperty.info` attribute of this object. .. versionadded:: 0.8 :param extension: an :class:`.AttributeExtension` instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. **Deprecated.** Please see :class:`.AttributeEvents`. """ super(CompositeProperty, self).__init__() self.attrs = attrs self.composite_class = class_ self.active_history = kwargs.get('active_history', False) self.deferred = kwargs.get('deferred', False) self.group = kwargs.get('group', None) self.comparator_factory = kwargs.pop('comparator_factory', self.__class__.Comparator) if 'info' in kwargs: self.info = kwargs.pop('info') util.set_creation_order(self) self._create_descriptor() def instrument_class(self, mapper): super(CompositeProperty, self).instrument_class(mapper) self._setup_event_handlers() def do_init(self): """Initialization which occurs after the :class:`.CompositeProperty` has been associated with its parent mapper. """ self._setup_arguments_on_columns() def _create_descriptor(self): """Create the Python descriptor that will serve as the access point on instances of the mapped class. """ def fget(instance): dict_ = attributes.instance_dict(instance) state = attributes.instance_state(instance) if self.key not in dict_: # key not present. Iterate through related # attributes, retrieve their values. This # ensures they all load. values = [ getattr(instance, key) for key in self._attribute_keys ] # current expected behavior here is that the composite is # created on access if the object is persistent or if # col attributes have non-None. This would be better # if the composite were created unconditionally, # but that would be a behavioral change. if self.key not in dict_ and ( state.key is not None or not _none_set.issuperset(values) ): dict_[self.key] = self.composite_class(*values) state.manager.dispatch.refresh(state, None, [self.key]) return dict_.get(self.key, None) def fset(instance, value): dict_ = attributes.instance_dict(instance) state = attributes.instance_state(instance) attr = state.manager[self.key] previous = dict_.get(self.key, attributes.NO_VALUE) for fn in attr.dispatch.set: value = fn(state, value, previous, attr.impl) dict_[self.key] = value if value is None: for key in self._attribute_keys: setattr(instance, key, None) else: for key, value in zip( self._attribute_keys, value.__composite_values__()): setattr(instance, key, value) def fdel(instance): state = attributes.instance_state(instance) dict_ = attributes.instance_dict(instance) previous = dict_.pop(self.key, attributes.NO_VALUE) attr = state.manager[self.key] attr.dispatch.remove(state, previous, attr.impl) for key in self._attribute_keys: setattr(instance, key, None) self.descriptor = property(fget, fset, fdel) @util.memoized_property def _comparable_elements(self): return [ getattr(self.parent.class_, prop.key) for prop in self.props ] @util.memoized_property def props(self): props = [] for attr in self.attrs: if isinstance(attr, str): prop = self.parent.get_property( attr, _configure_mappers=False) elif isinstance(attr, schema.Column): prop = self.parent._columntoproperty[attr] elif isinstance(attr, attributes.InstrumentedAttribute): prop = attr.property else: raise sa_exc.ArgumentError( "Composite expects Column objects or mapped " "attributes/attribute names as arguments, got: %r" % (attr,)) props.append(prop) return props @property def columns(self): return [a for a in self.attrs if isinstance(a, schema.Column)] def _setup_arguments_on_columns(self): """Propagate configuration arguments made on this composite to the target columns, for those that apply. """ for prop in self.props: prop.active_history = self.active_history if self.deferred: prop.deferred = self.deferred prop.strategy_class = prop._strategy_lookup( ("deferred", True), ("instrument", True)) prop.group = self.group def _setup_event_handlers(self): """Establish events that populate/expire the composite attribute.""" def load_handler(state, *args): dict_ = state.dict if self.key in dict_: return # if column elements aren't loaded, skip. # __get__() will initiate a load for those # columns for k in self._attribute_keys: if k not in dict_: return # assert self.key not in dict_ dict_[self.key] = self.composite_class( *[state.dict[key] for key in self._attribute_keys] ) def expire_handler(state, keys): if keys is None or set(self._attribute_keys).intersection(keys): state.dict.pop(self.key, None) def insert_update_handler(mapper, connection, state): """After an insert or update, some columns may be expired due to server side defaults, or re-populated due to client side defaults. Pop out the composite value here so that it recreates. """ state.dict.pop(self.key, None) event.listen(self.parent, 'after_insert', insert_update_handler, raw=True) event.listen(self.parent, 'after_update', insert_update_handler, raw=True) event.listen(self.parent, 'load', load_handler, raw=True, propagate=True) event.listen(self.parent, 'refresh', load_handler, raw=True, propagate=True) event.listen(self.parent, 'expire', expire_handler, raw=True, propagate=True) # TODO: need a deserialize hook here @util.memoized_property def _attribute_keys(self): return [ prop.key for prop in self.props ] def get_history(self, state, dict_, passive=attributes.PASSIVE_OFF): """Provided for userland code that uses attributes.get_history().""" added = [] deleted = [] has_history = False for prop in self.props: key = prop.key hist = state.manager[key].impl.get_history(state, dict_) if hist.has_changes(): has_history = True non_deleted = hist.non_deleted() if non_deleted: added.extend(non_deleted) else: added.append(None) if hist.deleted: deleted.extend(hist.deleted) else: deleted.append(None) if has_history: return attributes.History( [self.composite_class(*added)], (), [self.composite_class(*deleted)] ) else: return attributes.History( (), [self.composite_class(*added)], () ) def _comparator_factory(self, mapper): return self.comparator_factory(self, mapper) class CompositeBundle(query.Bundle): def __init__(self, property, expr): self.property = property super(CompositeProperty.CompositeBundle, self).__init__( property.key, *expr) def create_row_processor(self, query, procs, labels): def proc(row): return self.property.composite_class( *[proc(row) for proc in procs]) return proc class Comparator(PropComparator): """Produce boolean, comparison, and other operators for :class:`.CompositeProperty` attributes. See the example in :ref:`composite_operations` for an overview of usage , as well as the documentation for :class:`.PropComparator`. See also: :class:`.PropComparator` :class:`.ColumnOperators` :ref:`types_operators` :attr:`.TypeEngine.comparator_factory` """ __hash__ = None @property def clauses(self): return self.__clause_element__() def __clause_element__(self): return expression.ClauseList( group=False, *self._comparable_elements) def _query_clause_element(self): return CompositeProperty.CompositeBundle( self.prop, self.__clause_element__()) @util.memoized_property def _comparable_elements(self): if self._adapt_to_entity: return [ getattr( self._adapt_to_entity.entity, prop.key ) for prop in self.prop._comparable_elements ] else: return self.prop._comparable_elements def __eq__(self, other): if other is None: values = [None] * len(self.prop._comparable_elements) else: values = other.__composite_values__() comparisons = [ a == b for a, b in zip(self.prop._comparable_elements, values) ] if self._adapt_to_entity: comparisons = [self.adapter(x) for x in comparisons] return sql.and_(*comparisons) def __ne__(self, other): return sql.not_(self.__eq__(other)) def __str__(self): return str(self.parent.class_.__name__) + "." + self.key @util.langhelpers.dependency_for("sqlalchemy.orm.properties") class ConcreteInheritedProperty(DescriptorProperty): """A 'do nothing' :class:`.MapperProperty` that disables an attribute on a concrete subclass that is only present on the inherited mapper, not the concrete classes' mapper. Cases where this occurs include: * When the superclass mapper is mapped against a "polymorphic union", which includes all attributes from all subclasses. * When a relationship() is configured on an inherited mapper, but not on the subclass mapper. Concrete mappers require that relationship() is configured explicitly on each subclass. """ def _comparator_factory(self, mapper): comparator_callable = None for m in self.parent.iterate_to_root(): p = m._props[self.key] if not isinstance(p, ConcreteInheritedProperty): comparator_callable = p.comparator_factory break return comparator_callable def __init__(self): super(ConcreteInheritedProperty, self).__init__() def warn(): raise AttributeError("Concrete %s does not implement " "attribute %r at the instance level. Add " "this property explicitly to %s." % (self.parent, self.key, self.parent)) class NoninheritedConcreteProp(object): def __set__(s, obj, value): warn() def __delete__(s, obj): warn() def __get__(s, obj, owner): if obj is None: return self.descriptor warn() self.descriptor = NoninheritedConcreteProp() @util.langhelpers.dependency_for("sqlalchemy.orm.properties") class SynonymProperty(DescriptorProperty): def __init__(self, name, map_column=None, descriptor=None, comparator_factory=None, doc=None, info=None): """Denote an attribute name as a synonym to a mapped property, in that the attribute will mirror the value and expression behavior of another attribute. :param name: the name of the existing mapped property. This can refer to the string name of any :class:`.MapperProperty` configured on the class, including column-bound attributes and relationships. :param descriptor: a Python :term:`descriptor` that will be used as a getter (and potentially a setter) when this attribute is accessed at the instance level. :param map_column: if ``True``, the :func:`.synonym` construct will locate the existing named :class:`.MapperProperty` based on the attribute name of this :func:`.synonym`, and assign it to a new attribute linked to the name of this :func:`.synonym`. That is, given a mapping like:: class MyClass(Base): __tablename__ = 'my_table' id = Column(Integer, primary_key=True) job_status = Column(String(50)) job_status = synonym("_job_status", map_column=True) The above class ``MyClass`` will now have the ``job_status`` :class:`.Column` object mapped to the attribute named ``_job_status``, and the attribute named ``job_status`` will refer to the synonym itself. This feature is typically used in conjunction with the ``descriptor`` argument in order to link a user-defined descriptor as a "wrapper" for an existing column. :param info: Optional data dictionary which will be populated into the :attr:`.InspectionAttr.info` attribute of this object. .. versionadded:: 1.0.0 :param comparator_factory: A subclass of :class:`.PropComparator` that will provide custom comparison behavior at the SQL expression level. .. note:: For the use case of providing an attribute which redefines both Python-level and SQL-expression level behavior of an attribute, please refer to the Hybrid attribute introduced at :ref:`mapper_hybrids` for a more effective technique. .. seealso:: :ref:`synonyms` - examples of functionality. :ref:`mapper_hybrids` - Hybrids provide a better approach for more complicated attribute-wrapping schemes than synonyms. """ super(SynonymProperty, self).__init__() self.name = name self.map_column = map_column self.descriptor = descriptor self.comparator_factory = comparator_factory self.doc = doc or (descriptor and descriptor.__doc__) or None if info: self.info = info util.set_creation_order(self) # TODO: when initialized, check _proxied_property, # emit a warning if its not a column-based property @util.memoized_property def _proxied_property(self): return getattr(self.parent.class_, self.name).property def _comparator_factory(self, mapper): prop = self._proxied_property if self.comparator_factory: comp = self.comparator_factory(prop, mapper) else: comp = prop.comparator_factory(prop, mapper) return comp def set_parent(self, parent, init): if self.map_column: # implement the 'map_column' option. if self.key not in parent.mapped_table.c: raise sa_exc.ArgumentError( "Can't compile synonym '%s': no column on table " "'%s' named '%s'" % (self.name, parent.mapped_table.description, self.key)) elif parent.mapped_table.c[self.key] in \ parent._columntoproperty and \ parent._columntoproperty[ parent.mapped_table.c[self.key] ].key == self.name: raise sa_exc.ArgumentError( "Can't call map_column=True for synonym %r=%r, " "a ColumnProperty already exists keyed to the name " "%r for column %r" % (self.key, self.name, self.name, self.key) ) p = properties.ColumnProperty(parent.mapped_table.c[self.key]) parent._configure_property( self.name, p, init=init, setparent=True) p._mapped_by_synonym = self.key self.parent = parent @util.langhelpers.dependency_for("sqlalchemy.orm.properties") class ComparableProperty(DescriptorProperty): """Instruments a Python property for use in query expressions.""" def __init__( self, comparator_factory, descriptor=None, doc=None, info=None): """Provides a method of applying a :class:`.PropComparator` to any Python descriptor attribute. .. versionchanged:: 0.7 :func:`.comparable_property` is superseded by the :mod:`~sqlalchemy.ext.hybrid` extension. See the example at :ref:`hybrid_custom_comparators`. Allows any Python descriptor to behave like a SQL-enabled attribute when used at the class level in queries, allowing redefinition of expression operator behavior. In the example below we redefine :meth:`.PropComparator.operate` to wrap both sides of an expression in ``func.lower()`` to produce case-insensitive comparison:: from sqlalchemy.orm import comparable_property from sqlalchemy.orm.interfaces import PropComparator from sqlalchemy.sql import func from sqlalchemy import Integer, String, Column from sqlalchemy.ext.declarative import declarative_base class CaseInsensitiveComparator(PropComparator): def __clause_element__(self): return self.prop def operate(self, op, other): return op( func.lower(self.__clause_element__()), func.lower(other) ) Base = declarative_base() class SearchWord(Base): __tablename__ = 'search_word' id = Column(Integer, primary_key=True) word = Column(String) word_insensitive = comparable_property(lambda prop, mapper: CaseInsensitiveComparator( mapper.c.word, mapper) ) A mapping like the above allows the ``word_insensitive`` attribute to render an expression like:: >>> print SearchWord.word_insensitive == "Trucks" lower(search_word.word) = lower(:lower_1) :param comparator_factory: A PropComparator subclass or factory that defines operator behavior for this property. :param descriptor: Optional when used in a ``properties={}`` declaration. The Python descriptor or property to layer comparison behavior on top of. The like-named descriptor will be automatically retrieved from the mapped class if left blank in a ``properties`` declaration. :param info: Optional data dictionary which will be populated into the :attr:`.InspectionAttr.info` attribute of this object. .. versionadded:: 1.0.0 """ super(ComparableProperty, self).__init__() self.descriptor = descriptor self.comparator_factory = comparator_factory self.doc = doc or (descriptor and descriptor.__doc__) or None if info: self.info = info util.set_creation_order(self) def _comparator_factory(self, mapper): return self.comparator_factory(self, mapper)
apache-2.0
jmehnle/ansible
lib/ansible/modules/network/nxos/nxos_vrf.py
23
8238
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = { 'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: nxos_vrf extends_documentation_fragment: nxos version_added: "2.1" short_description: Manages global VRF configuration. description: - Manages global VRF configuration. author: - Jason Edelman (@jedelman8) - Gabriele Gerbino (@GGabriele) notes: - Cisco NX-OS creates the default VRF by itself. Therefore, you're not allowed to use default as I(vrf) name in this module. - C(vrf) name must be shorter than 32 chars. - VRF names are not case sensible in NX-OS. Anyway, the name is stored just like it's inserted by the user and it'll not be changed again unless the VRF is removed and re-created. i.e. C(vrf=NTC) will create a VRF named NTC, but running it again with C(vrf=ntc) will not cause a configuration change. options: vrf: description: - Name of VRF to be managed. required: true admin_state: description: - Administrative state of the VRF. required: false default: up choices: ['up','down'] vni: description: - Specify virtual network identifier. Valid values are Integer or keyword 'default'. required: false default: null version_added: "2.2" route_distinguisher: description: - VPN Route Distinguisher (RD). Valid values are a string in one of the route-distinguisher formats (ASN2:NN, ASN4:NN, or IPV4:NN); the keyword 'auto', or the keyword 'default'. required: false default: null version_added: "2.2" state: description: - Manages desired state of the resource. required: false default: present choices: ['present','absent'] description: description: - Description of the VRF. required: false default: null ''' EXAMPLES = ''' - name: Ensure ntc VRF exists on switch nxos_vrf: vrf: ntc state: present ''' RETURN = ''' commands: description: commands sent to the device returned: always type: list sample: ["vrf context ntc", "shutdown"] ''' import re from ansible.module_utils.nxos import get_config, load_config, run_commands from ansible.module_utils.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleModule def execute_show_command(command, module): transport = module.params['transport'] if transport == 'cli': if 'show run' not in command: command += ' | json' cmds = [command] body = run_commands(module, cmds) return body def apply_key_map(key_map, table): new_dict = {} for key in table: new_key = key_map.get(key) if new_key: new_dict[new_key] = str(table.get(key)) return new_dict def get_commands_to_config_vrf(delta, vrf): commands = [] for param, value in delta.items(): command = '' if param == 'description': command = 'description {0}'.format(value) elif param == 'admin_state': if value.lower() == 'up': command = 'no shutdown' elif value.lower() == 'down': command = 'shutdown' elif param == 'rd': command = 'rd {0}'.format(value) elif param == 'vni': command = 'vni {0}'.format(value) if command: commands.append(command) if commands: commands.insert(0, 'vrf context {0}'.format(vrf)) return commands def get_vrf_description(vrf, module): command = (r'show run section vrf | begin ^vrf\scontext\s{0} | end ^vrf.*'.format(vrf)) description = '' descr_regex = r".*description\s(?P<descr>[\S+\s]+).*" try: body = execute_show_command(command, module)[0] except IndexError: return description if body: splitted_body = body.split('\n') for element in splitted_body: if 'description' in element: match_description = re.match(descr_regex, element, re.DOTALL) group_description = match_description.groupdict() description = group_description["descr"] return description def get_value(arg, config, module): extra_arg_regex = re.compile(r'(?:{0}\s)(?P<value>.*)$'.format(arg), re.M) value = '' if arg in config: value = extra_arg_regex.search(config).group('value') return value def get_vrf(vrf, module): command = 'show vrf {0}'.format(vrf) vrf_key = { 'vrf_name': 'vrf', 'vrf_state': 'admin_state' } try: body = execute_show_command(command, module)[0] vrf_table = body['TABLE_vrf']['ROW_vrf'] except (TypeError, IndexError): return {} parsed_vrf = apply_key_map(vrf_key, vrf_table) command = 'show run all | section vrf.context.{0}'.format(vrf) body = execute_show_command(command, module)[0] extra_params = ['vni', 'rd', 'description'] for param in extra_params: parsed_vrf[param] = get_value(param, body, module) return parsed_vrf def main(): argument_spec = dict( vrf=dict(required=True), description=dict(default=None, required=False), vni=dict(required=False, type='str'), rd=dict(required=False, type='str'), admin_state=dict(default='up', choices=['up', 'down'], required=False), state=dict(default='present', choices=['present', 'absent'], required=False), include_defaults=dict(default=False), config=dict(), save=dict(type='bool', default=False) ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) results = dict(changed=False, warnings=warnings) vrf = module.params['vrf'] admin_state = module.params['admin_state'].lower() description = module.params['description'] rd = module.params['rd'] vni = module.params['vni'] state = module.params['state'] if vrf == 'default': module.fail_json(msg='cannot use default as name of a VRF') elif len(vrf) > 32: module.fail_json(msg='VRF name exceeded max length of 32', vrf=vrf) existing = get_vrf(vrf, module) args = dict(vrf=vrf, description=description, vni=vni, admin_state=admin_state, rd=rd) proposed = dict((k, v) for k, v in args.items() if v is not None) delta = dict(set(proposed.items()).difference(existing.items())) commands = [] if state == 'absent': if existing: command = ['no vrf context {0}'.format(vrf)] commands.extend(command) elif state == 'present': if not existing: command = get_commands_to_config_vrf(delta, vrf) commands.extend(command) elif delta: command = get_commands_to_config_vrf(delta, vrf) commands.extend(command) if commands: if proposed.get('vni'): if existing.get('vni') and existing.get('vni') != '': commands.insert(1, 'no vni {0}'.format(existing['vni'])) if module.check_mode: module.exit_json(changed=True, commands=commands) else: load_config(module, commands) results['changed'] = True if 'configure' in commands: commands.pop(0) results['commands'] = commands module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
harvard-vpal/bridge-adaptivity
bridge_adaptivity/module/models.py
1
21212
import hashlib import importlib import inspect import logging import math import os import uuid from django.conf import settings from django.contrib.postgres.fields import JSONField from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models import fields from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from multiselectfield import MultiSelectField from ordered_model.models import OrderedModel import shortuuid from slugger import AutoSlugField from bridge_lti.models import BridgeUser, LtiContentSource, LtiUser, OutcomeService from common.mixins.models import HasLinkedSequenceMixin, ModelFieldIsDefaultMixin from module import tasks log = logging.getLogger(__name__) def _discover_applicable_modules(folder_name='engines', file_startswith='engine_'): modules = [] for name in os.listdir(os.path.join( os.path.dirname(os.path.abspath(__file__)), folder_name )): if name.startswith(file_startswith) and name.endswith('.py'): modules.append((name[:-len('.py')], name[len(file_startswith):-len('.py')])) return modules def _load_cls_from_applicable_module(module_path, mod_name, class_startswith=None, class_endswith=None): """ Load class from module. """ module = None try: cls_module = importlib.import_module('{}.{}'.format(module_path, mod_name)) except ImportError: log.error("Could not load module_path={}, mod_name={}".format(module_path, mod_name)) raise for attr in inspect.getmembers(cls_module): if class_endswith and attr[0].endswith(class_endswith): module = attr[1] elif class_startswith and attr[0].startswith(class_startswith): module = attr[1] return module ENGINES = _discover_applicable_modules(folder_name='engines', file_startswith='engine_') GRADING_POLICY_MODULES = _discover_applicable_modules(folder_name='policies', file_startswith='policy_') GRADING_POLICY_NAME_TO_CLS = { name: _load_cls_from_applicable_module("module.policies", file_name, class_endswith="GradingPolicy") for file_name, name in GRADING_POLICY_MODULES } """ Policy choices. Key is a policy name and value is a GradingPolicyClass. GradingPolicyClass has __str__ method and it's string representation is GradingPolicy.public_name. This hack is done to pass policy.summary_text and policy.detail_text to select policy widget's template, where these variables are used to show popover message with description about each policy (bootstrap3 JS popover function). """ GRADING_POLICY_CHOICES = ((k, v) for k, v in GRADING_POLICY_NAME_TO_CLS.items()) class Sequence(models.Model): """ Represents User's problem solving track. """ lti_user = models.ForeignKey(LtiUser, on_delete=models.CASCADE) collection_order = models.ForeignKey('CollectionOrder', null=True, on_delete=models.CASCADE) completed = fields.BooleanField(default=False) lis_result_sourcedid = models.CharField(max_length=255, null=True) outcome_service = models.ForeignKey(OutcomeService, null=True, on_delete=models.CASCADE) metadata = JSONField(default={}, blank=True) # NOTE(yura.braiko) suffix is a hash to make unique user_id for the collection repetition feature. suffix = models.CharField(max_length=15, default='') class Meta: unique_together = ('lti_user', 'collection_order', 'suffix') def __str__(self): return '<Sequence[{}]: {}>'.format(self.id, self.lti_user) def fulfil_sequence_metadata(self, lti_params, launch_params): """ Automate fulfilling sequence metadata field with launch_params equal to lti_params. :param lti_params: iterable object with the required lti parameters names :param launch_params: dict with the launch lti parameters received in launch lti request """ meta_dict = {} for param in lti_params: if param in launch_params: meta_dict[param] = launch_params[param] if meta_dict: self.metadata = meta_dict self.save() def sequence_ui_details(self): """ Create the context for the optional label on the student view. Context depends on the ModuleGroup's OPTION value. :return: str with the text for injecting into the label. """ ui_options = self.collection_order.ui_option details_list = [] for ui_option in ui_options: # NOTE(idegtiarov) conditions depend on ModuleGroup's OPTIONS if ui_option == CollectionOrder.OPTIONS[0][0]: details = ( f"{CollectionOrder.OPTIONS[0][1]}: {self.items.count()}/" f"{self.collection_order.collection.activities.count()}" ) elif ui_option == CollectionOrder.OPTIONS[1][0]: grade = self.collection_order.grading_policy.calculate_grade(self) # NOTE(andrey.lykhoman): Operations with float numbers can lead to the creation of some numbers in # higher degrees after the decimal point. grade = round(grade * 100, 1) details = f"{CollectionOrder.OPTIONS[1][1]}: {grade}%" else: details = ( f"{CollectionOrder.OPTIONS[2][1]}: " f"{self.items.filter(score__gt=0).count()}/{self.items.filter(score=0).count()}" ) details_list.append(details) return details_list class SequenceItem(models.Model): """ Represents one User's step in problem solving track. """ sequence = models.ForeignKey('Sequence', related_name='items', null=True, on_delete=models.CASCADE) activity = models.ForeignKey('Activity', null=True, on_delete=models.CASCADE) position = models.PositiveIntegerField(default=1) score = models.FloatField(null=True, blank=True, help_text="Grade policy: 'p' (problem's current score).") # NOTE(idegtiarov) suffix is a hash to make unique user_id for the Activity repetition feature. suffix = models.CharField(max_length=10, default='') is_problem = models.BooleanField(default=True) __origin_score = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__origin_score = self.score class Meta: verbose_name = "Sequence Item" verbose_name_plural = "Sequence Items" ordering = ['sequence', 'position'] def __str__(self): return '<SequenceItem: {}={}>'.format(self.sequence, self.activity.name) def _add_suffix(self): """ Add suffix to the SequenceItem if activity repetition is allowed. """ if self.suffix: return self.suffix = hashlib.sha1(shortuuid.uuid().encode('utf-8')).hexdigest()[::4] # Return 10 character uuid suffix def save(self, *args, **kwargs): """ Extension sending notification to the Adaptive engine that score is changed. """ if self.score != self.__origin_score: engine = self.sequence.collection_order.engine.engine_driver engine.submit_activity_answer(self) log.debug("Adaptive engine is updated with the grade for the {} activity in the SequenceItem {}".format( self.activity.name, self.id )) if self.activity.repetition > 1: self._add_suffix() self.is_problem = self.activity.is_problem super().save(*args, **kwargs) @property def user_id_for_consumer(self): return f'{self.sequence.lti_user.user_id}{self.sequence.suffix}{self.suffix}' class GradingPolicy(ModelFieldIsDefaultMixin, models.Model): """ Predefined set of Grading policy objects. Define how to grade collections. Field `name` if fulfilled from the correspondent choices in the form GradingPolicyForm. """ name = models.CharField(max_length=20) # Field name is not editable in admin UI. public_name = models.CharField(max_length=255) params = JSONField(default={}, blank=True, help_text="Policy parameters in json format.") engine = models.ForeignKey('Engine', blank=True, null=True, on_delete=models.CASCADE) is_default = models.BooleanField(default=False) @property def policy_cls(self): return GRADING_POLICY_NAME_TO_CLS[self.name] def policy_instance(self, **kwargs): return self.policy_cls(policy=self, **kwargs) def calculate_grade(self, sequence): policy = self.policy_cls(policy=self, sequence=sequence) return math.floor(policy.grade * 1000) / 1000 def __str__(self): return "{}, public_name: {} params: {}{}".format( self.name, self.public_name, self.params, ", IS DEFAULT POLICY" if self.is_default else "" ) class Collection(models.Model): """Set of Activities (problems) for a module.""" name = fields.CharField(max_length=255) slug = AutoSlugField( populate_from='name', unique=True, db_index=True, help_text="Add the slug for the collection. If field empty slug will be created automatically.", verbose_name='slug id' ) owner = models.ForeignKey(BridgeUser, on_delete=models.CASCADE) metadata = fields.CharField(max_length=255, blank=True, null=True) updated_at = fields.DateTimeField(auto_now=True) class Meta: unique_together = ('owner', 'name') def __str__(self): return '<Collection: {}>'.format(self.name) def save(self, *args, **kwargs): """Extension cover method with logging.""" initial_id = self.id super().save(*args, **kwargs) tasks.sync_collection_engines.apply_async( kwargs={'collection_slug': self.slug, 'created_at': self.updated_at}, countdown=settings.CELERY_DELAY_SYNC_TASK, ) if initial_id: Log.objects.create( log_type=Log.ADMIN, action=Log.COLLECTION_UPDATED, data={'collection_slug': self.slug} ) else: Log.objects.create( log_type=Log.ADMIN, action=Log.COLLECTION_CREATED, data={'collection_slug': self.slug} ) def get_absolute_url(self): return reverse('module:collection-list') class Engine(ModelFieldIsDefaultMixin, models.Model): """Defines engine settings.""" DEFAULT_ENGINE = 'engine_mock' DRIVER = None engine = models.CharField(choices=ENGINES, default=DEFAULT_ENGINE, max_length=100) engine_name = models.CharField(max_length=255, blank=True, null=True, unique=True) host = models.URLField(blank=True, null=True) token = models.CharField(max_length=255, blank=True, null=True) lti_parameters = models.TextField( default='', blank=True, help_text=_("LTI parameters to sent to the engine, use comma separated string") ) is_default = fields.BooleanField(default=False, help_text=_("If checked Engine will be used as the default!")) class Meta: unique_together = ('host', 'token') def __str__(self): return "Engine: {}".format(self.engine_name) @classmethod def create_default(cls): return cls.objects.create( engine=cls.DEFAULT_ENGINE, engine_name='Mock', is_default=True ) @property def engine_driver(self): if not self.DRIVER: driver = _load_cls_from_applicable_module('module.engines', self.engine, class_startswith='Engine') # NOTE(idegtiarov) Currently, statement coves existent engines modules. Improve in case new engine will be # added to the engines package. if self.engine.endswith('mock'): engine_driver = driver() else: engine_driver = driver(**{'HOST': self.host, 'TOKEN': self.token}) self.DRIVER = engine_driver return self.DRIVER @property def lti_params(self): return (param.strip() for param in self.lti_parameters.split(',')) class CollectionOrder(HasLinkedSequenceMixin, OrderedModel): OPTIONS = ( ('AT', _('Questions viewed/total')), ('EP', _('Earned grade')), ('RW', _('Answers right/wrong')) ) slug = models.SlugField(unique=True, default=uuid.uuid4, editable=True, db_index=True) group = models.ForeignKey('ModuleGroup', on_delete=models.CASCADE) collection = models.ForeignKey('Collection', on_delete=models.CASCADE) grading_policy = models.OneToOneField('GradingPolicy', blank=True, null=True, on_delete=models.CASCADE) engine = models.ForeignKey(Engine, blank=True, null=True, on_delete=models.CASCADE) strict_forward = fields.BooleanField(default=True) ui_option = MultiSelectField( choices=OPTIONS, blank=True, help_text="Add an optional UI block to the student view" ) ui_next = models.BooleanField( default=False, help_text="Add an optional NEXT button under the embedded unit." ) congratulation_message = fields.BooleanField(default=False) order_with_respect_to = 'group' class Meta: ordering = ('group', 'order') @property def get_selected_ui_options(self): res_list = self.get_ui_option_list() if self.ui_next: res_list.append(_('Additional NEXT Button')) return res_list def get_launch_url(self): return "{}{}".format(settings.BRIDGE_HOST, reverse("lti:launch", kwargs={'collection_order_slug': self.slug})) class ModuleGroup(models.Model): """ Represents Module Group. """ name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) atime = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(BridgeUser, on_delete=models.CASCADE) slug = models.UUIDField(unique=True, default=uuid.uuid4, editable=False, db_index=True) collections = models.ManyToManyField( Collection, related_name='collection_groups', blank=True, through='CollectionOrder' ) contributors = models.ManyToManyField( BridgeUser, related_name='module_groups', blank=True, through='ContributorPermission' ) @property def ordered_collections(self): """ Return tuple of tuples of CollectionOrder and result sequence_set.exists() method. """ return ( (col_order, col_order.sequence_set.exists()) for col_order in CollectionOrder.objects.filter(group=self).order_by('order') ) def __str__(self): return "<Group of Collections: {}>".format(self.name) def get_absolute_url(self): return reverse('module:group-detail', kwargs={'group_slug': self.slug}) def get_collection_order_by_order(self, order): """ Return CollectionOrder object filtered by order and group. """ return CollectionOrder.objects.filter(group=self, order=order).first() def has_linked_active_sequences(self): return CollectionOrder.objects.filter(group=self, sequence__completed=False).exists() def has_linked_sequences(self): return CollectionOrder.objects.filter(group=self, sequence__isnull=False).exists() class ContributorPermission(models.Model): user = models.ForeignKey(BridgeUser, on_delete=models.CASCADE) group = models.ForeignKey(ModuleGroup, on_delete=models.CASCADE) # Note(AndreyLykhoman): Change this field to field with the possibility to select more than one option for select. full_permission = models.BooleanField(default=True) class Activity(OrderedModel): """General entity which represents problem/text/video material.""" TYPES = ( ('G', _('generic')), ('A', _('pre-assessment')), ('Z', _('post-assessment')), ) order_with_respect_to = 'atype', 'collection' name = models.CharField(max_length=255) collection = models.ForeignKey('Collection', related_name='activities', null=True, on_delete=models.CASCADE) tags = fields.CharField( max_length=255, help_text="Provide your tags separated by a comma.", blank=True, null=True, ) atype = fields.CharField( verbose_name="type", choices=TYPES, default='G', max_length=1, help_text="Choose 'pre/post-assessment' activity type to pin Activity to the start or the end of " "the Collection." ) difficulty = fields.FloatField( default='0.5', help_text="Provide float number in the range 0.0 - 1.0", validators=[MinValueValidator(0.0), MaxValueValidator(1.0)], ) points = models.FloatField(blank=True, default=1) lti_content_source = models.ForeignKey(LtiContentSource, null=True, on_delete=models.CASCADE) source_launch_url = models.URLField(max_length=255, null=True) source_name = fields.CharField(max_length=255, blank=True, null=True) # NOTE(wowkalucky): extra field 'order' is available (inherited from OrderedModel) # `stype` - means source_type or string_type. stype = models.CharField( "Type of the activity", help_text="(problem, video, html, etc.)", max_length=25, blank=True, null=True ) # Number of possible repetition of the activity in the sequence repetition = models.PositiveIntegerField( default=1, help_text="The number of possible repetition of the Activity in the sequence." ) @property def is_problem(self): return self.stype in settings.PROBLEM_ACTIVITY_TYPES class Meta: verbose_name_plural = 'Activities' unique_together = ("source_launch_url", "collection") ordering = 'atype', 'order' def __str__(self): return '<Activity: {}>'.format(self.name) def get_absolute_url(self): return reverse('module:collection-detail', kwargs={'slug': self.collection.slug}) def save(self, *args, **kwargs): """Extension which sends notification to the Adaptive engine that Activity is created/updated.""" initial_id = self.id if initial_id: Log.objects.create( log_type=Log.ADMIN, action=Log.ACTIVITY_UPDATED, data=self.get_research_data() ) else: Log.objects.create( log_type=Log.ADMIN, action=Log.ACTIVITY_CREATED, data=self.get_research_data() ) super().save(*args, **kwargs) self.collection.save() def delete(self, *args, **kwargs): """Extension which sends notification to the Adaptive engine that Activity is deleted.""" Log.objects.create( log_type=Log.ADMIN, action=Log.ACTIVITY_DELETED, data=self.get_research_data() ) super().delete(*args, **kwargs) self.collection.save() @property def last_pre(self): """ Has Activity last order number position in certain type sub-collection. :return: (bool) """ last_pre = Activity.objects.filter(collection=self.collection, atype='A').last() return self.id == last_pre.id def get_research_data(self): return {'collection_id': self.collection_id, 'activity_id': self.id} class Log(models.Model): """ Student actions log. Every time student opens/submits lti problem new Log created. """ OPENED = 'O' SUBMITTED = 'S' ADMIN = 'A' LOG_TYPES = ( (OPENED, 'Opened'), (SUBMITTED, 'Submitted'), (ADMIN, 'Admin'), ) ACTIVITY_CREATED = 'AC' ACTIVITY_UPDATED = 'AU' ACTIVITY_DELETED = 'AD' COLLECTION_CREATED = 'CC' COLLECTION_UPDATED = 'CU' ACTIONS = ( (ACTIVITY_CREATED, 'Activity created'), (ACTIVITY_UPDATED, 'Activity updated'), (ACTIVITY_DELETED, 'Activity deleted'), (COLLECTION_CREATED, 'Collection created'), (COLLECTION_UPDATED, 'Collection updated'), ) sequence_item = models.ForeignKey('SequenceItem', null=True, blank=True, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, blank=True, null=True) log_type = fields.CharField(choices=LOG_TYPES, max_length=32) answer = models.BooleanField(verbose_name='Is answer correct?', default=False) attempt = models.PositiveIntegerField(default=0) action = fields.CharField(choices=ACTIONS, max_length=2, null=True, blank=True) data = JSONField(default={}, blank=True) def __str__(self): if self.log_type == self.OPENED: return '<Log[{}]: {}>'.format(self.get_log_type_display(), self.sequence_item) elif self.log_type == self.ADMIN: return '<Log[{}]: {} ({})>'.format( self.get_log_type_display(), self.get_action_display(), self.data ) else: return '<Log[{}]: {}-{}[{}]>'.format( self.get_log_type_display(), self.sequence_item, self.answer, self.attempt )
bsd-3-clause
toofar/qutebrowser
qutebrowser/keyinput/basekeyparser.py
1
9449
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2018 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser 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. # # qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Base class for vim-like key sequence parser.""" from PyQt5.QtCore import pyqtSignal, QObject from PyQt5.QtGui import QKeySequence from qutebrowser.config import config from qutebrowser.utils import usertypes, log, utils from qutebrowser.keyinput import keyutils class BaseKeyParser(QObject): """Parser for vim-like key sequences and shortcuts. Not intended to be instantiated directly. Subclasses have to override execute() to do whatever they want to. Class Attributes: Match: types of a match between a binding and the keystring. partial: No keychain matched yet, but it's still possible in the future. definitive: Keychain matches exactly. none: No more matches possible. do_log: Whether to log keypresses or not. passthrough: Whether unbound keys should be passed through with this handler. Attributes: bindings: Bound key bindings _win_id: The window ID this keyparser is associated with. _sequence: The currently entered key sequence _modename: The name of the input mode associated with this keyparser. _supports_count: Whether count is supported Signals: keystring_updated: Emitted when the keystring is updated. arg: New keystring. request_leave: Emitted to request leaving a mode. arg 0: Mode to leave. arg 1: Reason for leaving. arg 2: Ignore the request if we're not in that mode """ keystring_updated = pyqtSignal(str) request_leave = pyqtSignal(usertypes.KeyMode, str, bool) do_log = True passthrough = False def __init__(self, win_id, parent=None, supports_count=True): super().__init__(parent) self._win_id = win_id self._modename = None self._sequence = keyutils.KeySequence() self._count = '' self._supports_count = supports_count self.bindings = {} config.instance.changed.connect(self._on_config_changed) def __repr__(self): return utils.get_repr(self, supports_count=self._supports_count) def _debug_log(self, message): """Log a message to the debug log if logging is active. Args: message: The message to log. """ if self.do_log: log.keyboard.debug(message) def _match_key(self, sequence): """Try to match a given keystring with any bound keychain. Args: sequence: The command string to find. Return: A tuple (matchtype, binding). matchtype: Match.definitive, Match.partial or Match.none. binding: - None with Match.partial/Match.none. - The found binding with Match.definitive. """ assert sequence assert not isinstance(sequence, str) result = QKeySequence.NoMatch for seq, cmd in self.bindings.items(): assert not isinstance(seq, str), seq match = sequence.matches(seq) if match == QKeySequence.ExactMatch: return match, cmd elif match == QKeySequence.PartialMatch: result = QKeySequence.PartialMatch return result, None def _match_without_modifiers(self, sequence): """Try to match a key with optional modifiers stripped.""" self._debug_log("Trying match without modifiers") sequence = sequence.strip_modifiers() match, binding = self._match_key(sequence) return match, binding, sequence def _match_key_mapping(self, sequence): """Try to match a key in bindings.key_mappings.""" self._debug_log("Trying match with key_mappings") mapped = sequence.with_mappings(config.val.bindings.key_mappings) if sequence != mapped: self._debug_log("Mapped {} -> {}".format( sequence, mapped)) match, binding = self._match_key(mapped) sequence = mapped return match, binding, sequence return QKeySequence.NoMatch, None, sequence def _match_count(self, sequence, dry_run): """Try to match a key as count.""" txt = str(sequence[-1]) # To account for sequences changed above. if (txt.isdigit() and self._supports_count and not (not self._count and txt == '0')): self._debug_log("Trying match as count") assert len(txt) == 1, txt if not dry_run: self._count += txt self.keystring_updated.emit(self._count + str(self._sequence)) return True return False def handle(self, e, *, dry_run=False): """Handle a new keypress. Separate the keypress into count/command, then check if it matches any possible command, and either run the command, ignore it, or display an error. Args: e: the KeyPressEvent from Qt. dry_run: Don't actually execute anything, only check whether there would be a match. Return: A QKeySequence match. """ key = e.key() txt = str(keyutils.KeyInfo.from_event(e)) self._debug_log("Got key: 0x{:x} / modifiers: 0x{:x} / text: '{}' / " "dry_run {}".format(key, int(e.modifiers()), txt, dry_run)) if keyutils.is_modifier_key(key): self._debug_log("Ignoring, only modifier") return QKeySequence.NoMatch try: sequence = self._sequence.append_event(e) except keyutils.KeyParseError as ex: self._debug_log("{} Aborting keychain.".format(ex)) self.clear_keystring() return QKeySequence.NoMatch match, binding = self._match_key(sequence) if match == QKeySequence.NoMatch: match, binding, sequence = self._match_without_modifiers(sequence) if match == QKeySequence.NoMatch: match, binding, sequence = self._match_key_mapping(sequence) if match == QKeySequence.NoMatch: was_count = self._match_count(sequence, dry_run) if was_count: return QKeySequence.ExactMatch if dry_run: return match self._sequence = sequence if match == QKeySequence.ExactMatch: self._debug_log("Definitive match for '{}'.".format( sequence)) count = int(self._count) if self._count else None self.clear_keystring() self.execute(binding, count) elif match == QKeySequence.PartialMatch: self._debug_log("No match for '{}' (added {})".format( sequence, txt)) self.keystring_updated.emit(self._count + str(sequence)) elif match == QKeySequence.NoMatch: self._debug_log("Giving up with '{}', no matches".format( sequence)) self.clear_keystring() else: raise utils.Unreachable("Invalid match value {!r}".format(match)) return match @config.change_filter('bindings') def _on_config_changed(self): self._read_config() def _read_config(self, modename=None): """Read the configuration. Config format: key = command, e.g.: <Ctrl+Q> = quit Args: modename: Name of the mode to use. """ if modename is None: if self._modename is None: raise ValueError("read_config called with no mode given, but " "None defined so far!") modename = self._modename else: self._modename = modename self.bindings = {} for key, cmd in config.key_instance.get_bindings_for(modename).items(): assert not isinstance(key, str), key assert cmd self.bindings[key] = cmd def execute(self, cmdstr, count=None): """Handle a completed keychain. Args: cmdstr: The command to execute as a string. count: The count if given. """ raise NotImplementedError def clear_keystring(self): """Clear the currently entered key sequence.""" if self._sequence: self._debug_log("Clearing keystring (was: {}).".format( self._sequence)) self._sequence = keyutils.KeySequence() self._count = '' self.keystring_updated.emit('')
gpl-3.0
tawsifkhan/scikit-learn
examples/applications/plot_outlier_detection_housing.py
243
5577
""" ==================================== Outlier detection on a real data set ==================================== This example illustrates the need for robust covariance estimation on a real data set. It is useful both for outlier detection and for a better understanding of the data structure. We selected two sets of two variables from the Boston housing data set as an illustration of what kind of analysis can be done with several outlier detection tools. For the purpose of visualization, we are working with two-dimensional examples, but one should be aware that things are not so trivial in high-dimension, as it will be pointed out. In both examples below, the main result is that the empirical covariance estimate, as a non-robust one, is highly influenced by the heterogeneous structure of the observations. Although the robust covariance estimate is able to focus on the main mode of the data distribution, it sticks to the assumption that the data should be Gaussian distributed, yielding some biased estimation of the data structure, but yet accurate to some extent. The One-Class SVM algorithm First example ------------- The first example illustrates how robust covariance estimation can help concentrating on a relevant cluster when another one exists. Here, many observations are confounded into one and break down the empirical covariance estimation. Of course, some screening tools would have pointed out the presence of two clusters (Support Vector Machines, Gaussian Mixture Models, univariate outlier detection, ...). But had it been a high-dimensional example, none of these could be applied that easily. Second example -------------- The second example shows the ability of the Minimum Covariance Determinant robust estimator of covariance to concentrate on the main mode of the data distribution: the location seems to be well estimated, although the covariance is hard to estimate due to the banana-shaped distribution. Anyway, we can get rid of some outlying observations. The One-Class SVM is able to capture the real data structure, but the difficulty is to adjust its kernel bandwidth parameter so as to obtain a good compromise between the shape of the data scatter matrix and the risk of over-fitting the data. """ print(__doc__) # Author: Virgile Fritsch <[email protected]> # License: BSD 3 clause import numpy as np from sklearn.covariance import EllipticEnvelope from sklearn.svm import OneClassSVM import matplotlib.pyplot as plt import matplotlib.font_manager from sklearn.datasets import load_boston # Get data X1 = load_boston()['data'][:, [8, 10]] # two clusters X2 = load_boston()['data'][:, [5, 12]] # "banana"-shaped # Define "classifiers" to be used classifiers = { "Empirical Covariance": EllipticEnvelope(support_fraction=1., contamination=0.261), "Robust Covariance (Minimum Covariance Determinant)": EllipticEnvelope(contamination=0.261), "OCSVM": OneClassSVM(nu=0.261, gamma=0.05)} colors = ['m', 'g', 'b'] legend1 = {} legend2 = {} # Learn a frontier for outlier detection with several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500)) for i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) plt.figure(2) clf.fit(X2) Z2 = clf.decision_function(np.c_[xx2.ravel(), yy2.ravel()]) Z2 = Z2.reshape(xx2.shape) legend2[clf_name] = plt.contour( xx2, yy2, Z2, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list( legend1.values() ) legend1_keys_list = list( legend1.keys() ) # Plot the results (= shape of the data points cloud) plt.figure(1) # two clusters plt.title("Outlier detection on a real data set (boston housing)") plt.scatter(X1[:, 0], X1[:, 1], color='black') bbox_args = dict(boxstyle="round", fc="0.8") arrow_args = dict(arrowstyle="->") plt.annotate("several confounded points", xy=(24, 19), xycoords="data", textcoords="data", xytext=(13, 10), bbox=bbox_args, arrowprops=arrow_args) plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend((legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc="upper center", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel("accessibility to radial highways") plt.xlabel("pupil-teacher ratio by town") legend2_values_list = list( legend2.values() ) legend2_keys_list = list( legend2.keys() ) plt.figure(2) # "banana" shape plt.title("Outlier detection on a real data set (boston housing)") plt.scatter(X2[:, 0], X2[:, 1], color='black') plt.xlim((xx2.min(), xx2.max())) plt.ylim((yy2.min(), yy2.max())) plt.legend((legend2_values_list[0].collections[0], legend2_values_list[1].collections[0], legend2_values_list[2].collections[0]), (legend2_values_list[0], legend2_values_list[1], legend2_values_list[2]), loc="upper center", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel("% lower status of the population") plt.xlabel("average number of rooms per dwelling") plt.show()
bsd-3-clause
vidartf/hyperspy
hyperspy/misc/utils.py
1
28688
# -*- coding: utf-8 -*- # Copyright 2007-2016 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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. # # HyperSpy 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 HyperSpy. If not, see <http://www.gnu.org/licenses/>. from operator import attrgetter import inspect import copy import types from io import StringIO import codecs import collections import tempfile import unicodedata from contextlib import contextmanager import numpy as np def attrsetter(target, attrs, value): """ Sets attribute of the target to specified value, supports nested attributes. Only creates a new attribute if the object supports such behaviour (e.g. DictionaryTreeBrowser does) Parameters ---------- target : object attrs : string attributes, separated by periods (e.g. 'metadata.Signal.Noise_parameters.variance' ) value : object Example ------- First create a signal and model pair: >>> s = hs.signals.Signal1D(np.arange(10)) >>> m = s.create_model() >>> m.signal.data array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) Now set the data of the model with attrsetter >>> attrsetter(m, 'signal1D.data', np.arange(10)+2) >>> self.signal.data array([2, 3, 4, 5, 6, 7, 8, 9, 10, 10]) The behaviour is identical to >>> self.signal.data = np.arange(10) + 2 """ where = attrs.rfind('.') if where != -1: target = attrgetter(attrs[:where])(target) setattr(target, attrs[where + 1:], value) def generate_axis(origin, step, N, index=0): """Creates an axis given the origin, step and number of channels Alternatively, the index of the origin channel can be specified. Parameters ---------- origin : float step : float N : number of channels index : int index of origin Returns ------- Numpy array """ return np.linspace( origin - index * step, origin + step * (N - 1 - index), N) @contextmanager def stash_active_state(model): active_state = [] for component in model: if component.active_is_multidimensional: active_state.append(component._active_array) else: active_state.append(component.active) yield for component in model: active_s = active_state.pop(0) if isinstance(active_s, bool): component.active = active_s else: if not component.active_is_multidimensional: component.active_is_multidimensional = True component._active_array[:] = active_s @contextmanager def dummy_context_manager(*args, **kwargs): yield def str2num(string, **kargs): """Transform a a table in string form into a numpy array Parameters ---------- string : string Returns ------- numpy array """ stringIO = StringIO(string) return np.loadtxt(stringIO, **kargs) _slugify_strip_re_data = ''.join( c for c in map( chr, np.delete( np.arange(256), [ 95, 32])) if not c.isalnum()).encode() def slugify(value, valid_variable_name=False): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. Adapted from Django's "django/template/defaultfilters.py". """ if not isinstance(value, str): try: # Convert to unicode using the default encoding value = str(value) except: # Try latin1. If this does not work an exception is raised. value = str(value, "latin1") value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = value.translate(None, _slugify_strip_re_data).decode().strip() value = value.replace(' ', '_') if valid_variable_name is True: if value[:1].isdigit(): value = 'Number_' + value return value class DictionaryTreeBrowser(object): """A class to comfortably browse a dictionary using a CLI. In addition to accessing the values using dictionary syntax the class enables navigating a dictionary that constains nested dictionaries as attribures of nested classes. Also it is an iterator over the (key, value) items. The `__repr__` method provides pretty tree printing. Private keys, i.e. keys that starts with an underscore, are not printed, counted when calling len nor iterated. Methods ------- export : saves the dictionary in pretty tree printing format in a text file. keys : returns a list of non-private keys. as_dictionary : returns a dictionary representation of the object. set_item : easily set items, creating any necessary node on the way. add_node : adds a node. Examples -------- >>> tree = DictionaryTreeBrowser() >>> tree.set_item("Branch.Leaf1.color", "green") >>> tree.set_item("Branch.Leaf2.color", "brown") >>> tree.set_item("Branch.Leaf2.caterpillar", True) >>> tree.set_item("Branch.Leaf1.caterpillar", False) >>> tree └── Branch ├── Leaf1 │ ├── caterpillar = False │ └── color = green └── Leaf2 ├── caterpillar = True └── color = brown >>> tree.Branch ├── Leaf1 │ ├── caterpillar = False │ └── color = green └── Leaf2 ├── caterpillar = True └── color = brown >>> for label, leaf in tree.Branch: ... print("%s is %s" % (label, leaf.color)) Leaf1 is green Leaf2 is brown >>> tree.Branch.Leaf2.caterpillar True >>> "Leaf1" in tree.Branch True >>> "Leaf3" in tree.Branch False >>> """ def __init__(self, dictionary=None, double_lines=False): self._double_lines = double_lines if not dictionary: dictionary = {} super(DictionaryTreeBrowser, self).__init__() self.add_dictionary(dictionary, double_lines=double_lines) def add_dictionary(self, dictionary, double_lines=False): """Add new items from dictionary. """ for key, value in dictionary.items(): if key == '_double_lines': value = double_lines self.__setattr__(key, value) def export(self, filename, encoding='utf8'): """Export the dictionary to a text file Parameters ---------- filename : str The name of the file without the extension that is txt by default encoding : valid encoding str """ f = codecs.open(filename, 'w', encoding=encoding) f.write(self._get_print_items(max_len=None)) f.close() def _get_print_items(self, padding='', max_len=78): """Prints only the attributes that are not methods """ from hyperspy.defaults_parser import preferences def check_long_string(value, max_len): if not isinstance(value, (str, np.string_)): value = repr(value) value = ensure_unicode(value) strvalue = str(value) _long = False if max_len is not None and len(strvalue) > 2 * max_len: right_limit = min(max_len, len(strvalue) - max_len) strvalue = '%s ... %s' % ( strvalue[:max_len], strvalue[-right_limit:]) _long = True return _long, strvalue string = '' eoi = len(self) j = 0 if preferences.General.dtb_expand_structures and self._double_lines: s_end = '╚══ ' s_middle = '╠══ ' pad_middle = '║ ' else: s_end = '└── ' s_middle = '├── ' pad_middle = '│ ' for key_, value in iter(sorted(self.__dict__.items())): if key_.startswith("_"): continue if not isinstance(key_, types.MethodType): key = ensure_unicode(value['key']) value = value['_dtb_value_'] if j == eoi - 1: symbol = s_end else: symbol = s_middle if preferences.General.dtb_expand_structures: if isinstance(value, list) or isinstance(value, tuple): iflong, strvalue = check_long_string(value, max_len) if iflong: key += (" <list>" if isinstance(value, list) else " <tuple>") value = DictionaryTreeBrowser( {'[%d]' % i: v for i, v in enumerate(value)}, double_lines=True) else: string += "%s%s%s = %s\n" % ( padding, symbol, key, strvalue) j += 1 continue if isinstance(value, DictionaryTreeBrowser): string += '%s%s%s\n' % (padding, symbol, key) if j == eoi - 1: extra_padding = ' ' else: extra_padding = pad_middle string += value._get_print_items( padding + extra_padding) else: _, strvalue = check_long_string(value, max_len) string += "%s%s%s = %s\n" % ( padding, symbol, key, strvalue) j += 1 return string def __repr__(self): return self._get_print_items() def __getitem__(self, key): return self.__getattribute__(key) def __setitem__(self, key, value): self.__setattr__(key, value) def __getattribute__(self, name): if isinstance(name, bytes): name = name.decode() name = slugify(name, valid_variable_name=True) item = super(DictionaryTreeBrowser, self).__getattribute__(name) if isinstance(item, dict) and '_dtb_value_' in item and "key" in item: return item['_dtb_value_'] else: return item def __setattr__(self, key, value): if key.startswith('_sig_'): key = key[5:] from hyperspy.signal import BaseSignal value = BaseSignal(**value) slugified_key = str(slugify(key, valid_variable_name=True)) if isinstance(value, dict): if self.has_item(slugified_key): self.get_item(slugified_key).add_dictionary( value, double_lines=self._double_lines) return else: value = DictionaryTreeBrowser( value, double_lines=self._double_lines) super(DictionaryTreeBrowser, self).__setattr__( slugified_key, {'key': key, '_dtb_value_': value}) def __len__(self): return len( [key for key in self.__dict__.keys() if not key.startswith("_")]) def keys(self): """Returns a list of non-private keys. """ return sorted([key for key in self.__dict__.keys() if not key.startswith("_")]) def as_dictionary(self): """Returns its dictionary representation. """ from hyperspy.signal import BaseSignal par_dict = {} for key_, item_ in self.__dict__.items(): if not isinstance(item_, types.MethodType): key = item_['key'] if key in ["_db_index", "_double_lines"]: continue if isinstance(item_['_dtb_value_'], DictionaryTreeBrowser): item = item_['_dtb_value_'].as_dictionary() elif isinstance(item_['_dtb_value_'], BaseSignal): item = item_['_dtb_value_']._to_dictionary() key = '_sig_' + key else: item = item_['_dtb_value_'] par_dict.__setitem__(key, item) return par_dict def has_item(self, item_path): """Given a path, return True if it exists. The nodes of the path are separated using periods. Parameters ---------- item_path : Str A string describing the path with each item separated by full stops (periods) Examples -------- >>> dict = {'To' : {'be' : True}} >>> dict_browser = DictionaryTreeBrowser(dict) >>> dict_browser.has_item('To') True >>> dict_browser.has_item('To.be') True >>> dict_browser.has_item('To.be.or') False """ if isinstance(item_path, str): item_path = item_path.split('.') else: item_path = copy.copy(item_path) attrib = item_path.pop(0) if hasattr(self, attrib): if len(item_path) == 0: return True else: item = self[attrib] if isinstance(item, type(self)): return item.has_item(item_path) else: return False else: return False def get_item(self, item_path): """Given a path, return True if it exists. The nodes of the path are separated using periods. Parameters ---------- item_path : Str A string describing the path with each item separated by full stops (periods) Examples -------- >>> dict = {'To' : {'be' : True}} >>> dict_browser = DictionaryTreeBrowser(dict) >>> dict_browser.has_item('To') True >>> dict_browser.has_item('To.be') True >>> dict_browser.has_item('To.be.or') False """ if isinstance(item_path, str): item_path = item_path.split('.') else: item_path = copy.copy(item_path) attrib = item_path.pop(0) if hasattr(self, attrib): if len(item_path) == 0: return self[attrib] else: item = self[attrib] if isinstance(item, type(self)): return item.get_item(item_path) else: raise AttributeError("Item not in dictionary browser") else: raise AttributeError("Item not in dictionary browser") def __contains__(self, item): return self.has_item(item_path=item) def copy(self): return copy.copy(self) def deepcopy(self): return copy.deepcopy(self) def set_item(self, item_path, value): """Given the path and value, create the missing nodes in the path and assign to the last one the value Parameters ---------- item_path : Str A string describing the path with each item separated by a full stops (periods) Examples -------- >>> dict_browser = DictionaryTreeBrowser({}) >>> dict_browser.set_item('First.Second.Third', 3) >>> dict_browser └── First └── Second └── Third = 3 """ if not self.has_item(item_path): self.add_node(item_path) if isinstance(item_path, str): item_path = item_path.split('.') if len(item_path) > 1: self.__getattribute__(item_path.pop(0)).set_item( item_path, value) else: self.__setattr__(item_path.pop(), value) def add_node(self, node_path): """Adds all the nodes in the given path if they don't exist. Parameters ---------- node_path: str The nodes must be separated by full stops (periods). Examples -------- >>> dict_browser = DictionaryTreeBrowser({}) >>> dict_browser.add_node('First.Second') >>> dict_browser.First.Second = 3 >>> dict_browser └── First └── Second = 3 """ keys = node_path.split('.') dtb = self for key in keys: if dtb.has_item(key) is False: dtb[key] = DictionaryTreeBrowser() dtb = dtb[key] def __next__(self): """ Standard iterator method, updates the index and returns the current coordiantes Returns ------- val : tuple of ints Returns a tuple containing the coordiantes of the current iteration. """ if len(self) == 0: raise StopIteration if not hasattr(self, '_db_index'): self._db_index = 0 elif self._db_index >= len(self) - 1: del self._db_index raise StopIteration else: self._db_index += 1 key = list(self.keys())[self._db_index] return key, getattr(self, key) def __iter__(self): return self def strlist2enumeration(lst): lst = tuple(lst) if not lst: return '' elif len(lst) == 1: return lst[0] elif len(lst) == 2: return "%s and %s" % lst else: return "%s, " * (len(lst) - 2) % lst[:-2] + "%s and %s" % lst[-2:] def ensure_unicode(stuff, encoding='utf8', encoding2='latin-1'): if not isinstance(stuff, (bytes, np.string_)): return stuff else: string = stuff try: string = string.decode(encoding) except: string = string.decode(encoding2, errors='ignore') return string def swapelem(obj, i, j): """Swaps element having index i with element having index j in object obj IN PLACE. E.g. >>> L = ['a', 'b', 'c'] >>> spwapelem(L, 1, 2) >>> print(L) ['a', 'c', 'b'] """ if len(obj) > 1: buf = obj[i] obj[i] = obj[j] obj[j] = buf def rollelem(a, index, to_index=0): """Roll the specified axis backwards, until it lies in a given position. Parameters ---------- a : list Input list. index : int The index of the item to roll backwards. The positions of the items do not change relative to one another. to_index : int, optional The item is rolled until it lies before this position. The default, 0, results in a "complete" roll. Returns ------- res : list Output list. """ res = copy.copy(a) res.insert(to_index, res.pop(index)) return res def fsdict(nodes, value, dictionary): """Populates the dictionary 'dic' in a file system-like fashion creating a dictionary of dictionaries from the items present in the list 'nodes' and assigning the value 'value' to the innermost dictionary. 'dic' will be of the type: dic['node1']['node2']['node3']...['nodeN'] = value where each node is like a directory that contains other directories (nodes) or files (values) """ node = nodes.pop(0) if node not in dictionary: dictionary[node] = {} if len(nodes) != 0 and isinstance(dictionary[node], dict): fsdict(nodes, value, dictionary[node]) else: dictionary[node] = value def find_subclasses(mod, cls): """Find all the subclasses in a module. Parameters ---------- mod : module cls : class Returns ------- dictonary in which key, item = subclass name, subclass """ return dict([(name, obj) for name, obj in inspect.getmembers(mod) if inspect.isclass(obj) and issubclass(obj, cls)]) def isiterable(obj): if isinstance(obj, collections.Iterable): return True else: return False def ordinal(value): """ Converts zero or a *postive* integer (or their string representations) to an ordinal value. >>> for i in range(1,13): ... ordinal(i) ... '1st' '2nd' '3rd' '4th' '5th' '6th' '7th' '8th' '9th' '10th' '11th' '12th' >>> for i in (100, '111', '112',1011): ... ordinal(i) ... '100th' '111th' '112th' '1011th' Notes ----- Author: Serdar Tumgoren http://code.activestate.com/recipes/576888-format-a-number-as-an-ordinal/ MIT license """ try: value = int(value) except ValueError: return value if value % 100 // 10 != 1: if value % 10 == 1: ordval = "%d%s" % (value, "st") elif value % 10 == 2: ordval = "%d%s" % (value, "nd") elif value % 10 == 3: ordval = "%d%s" % (value, "rd") else: ordval = "%d%s" % (value, "th") else: ordval = "%d%s" % (value, "th") return ordval def underline(line, character="-"): """Return the line underlined. """ return line + "\n" + character * len(line) def closest_power_of_two(n): return int(2 ** np.ceil(np.log2(n))) def without_nans(data): return data[~np.isnan(data)] def stack(signal_list, axis=None, new_axis_name='stack_element', mmap=False, mmap_dir=None,): """Concatenate the signals in the list over a given axis or a new axis. The title is set to that of the first signal in the list. Parameters ---------- signal_list : list of BaseSignal instances axis : {None, int, str} If None, the signals are stacked over a new axis. The data must have the same dimensions. Otherwise the signals are stacked over the axis given by its integer index or its name. The data must have the same shape, except in the dimension corresponding to `axis`. new_axis_name : string The name of the new axis when `axis` is None. If an axis with this name already exists it automatically append '-i', where `i` are integers, until it finds a name that is not yet in use. mmap: bool If True and stack is True, then the data is stored in a memory-mapped temporary file.The memory-mapped data is stored on disk, and not directly loaded into memory. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory. mmap_dir : string If mmap_dir is not None, and stack and mmap are True, the memory mapped file will be created in the given directory, otherwise the default directory is used. Returns ------- signal : BaseSignal instance (or subclass, determined by the objects in signal list) Examples -------- >>> data = np.arange(20) >>> s = hs.stack([hs.signals.Signal1D(data[:10]), ... hs.signals.Signal1D(data[10:])]) >>> s <Signal1D, title: Stack of , dimensions: (2, 10)> >>> s.data array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]) """ axis_input = copy.deepcopy(axis) for i, obj in enumerate(signal_list): if i == 0: if axis is None: original_shape = obj.data.shape stack_shape = tuple([len(signal_list), ]) + original_shape tempf = None if mmap is False: data = np.empty(stack_shape, dtype=obj.data.dtype) else: tempf = tempfile.NamedTemporaryFile( dir=mmap_dir) data = np.memmap(tempf, dtype=obj.data.dtype, mode='w+', shape=stack_shape,) signal = type(obj)(data=data) signal.axes_manager._axes[ 1:] = copy.deepcopy( obj.axes_manager._axes) axis_name = new_axis_name axis_names = [axis_.name for axis_ in signal.axes_manager._axes[1:]] j = 1 while axis_name in axis_names: axis_name = new_axis_name + "_%i" % j j += 1 eaxis = signal.axes_manager._axes[0] eaxis.name = axis_name eaxis.navigate = True # This triggers _update_parameters signal.metadata = copy.deepcopy(obj.metadata) # Get the title from 1st object signal.metadata.General.title = ( "Stack of " + obj.metadata.General.title) signal.original_metadata = DictionaryTreeBrowser({}) else: axis = obj.axes_manager[axis] signal = obj.deepcopy() signal.original_metadata.add_node('stack_elements') # Store parameters signal.original_metadata.stack_elements.add_node( 'element%i' % i) node = signal.original_metadata.stack_elements[ 'element%i' % i] node.original_metadata = \ obj.original_metadata.as_dictionary() node.metadata = \ obj.metadata.as_dictionary() if axis is None: if obj.data.shape != original_shape: raise IOError( "Only files with data of the same shape can be stacked") signal.data[i, ...] = obj.data del obj if axis is not None: signal.data = np.concatenate([signal_.data for signal_ in signal_list], axis=axis.index_in_array) signal.get_dimensions_from_data() if axis_input is None: axis_input = signal.axes_manager[-1 + 1j].index_in_axes_manager step_sizes = 1 else: step_sizes = [obj.axes_manager[axis_input].size for obj in signal_list] signal.metadata._HyperSpy.set_item( 'Stacking_history.axis', axis_input) signal.metadata._HyperSpy.set_item( 'Stacking_history.step_sizes', step_sizes) from hyperspy.signal import BaseSignal if np.all([s.metadata.has_item('Signal.Noise_properties.variance') for s in signal_list]): if np.all([isinstance(s.metadata.Signal.Noise_properties.variance, BaseSignal) for s in signal_list]): variance = stack( [s.metadata.Signal.Noise_properties.variance for s in signal_list], axis) signal.metadata.set_item( 'Signal.Noise_properties.variance', variance) return signal def shorten_name(name, req_l): if len(name) > req_l: return name[:req_l - 2] + '..' else: return name def transpose(*args, signal_axes=None, navigation_axes=None, optimize=False): """Transposes all passed signals according to the specified options. For parameters see ``BaseSignal.transpose``. Examples -------- >>> signal_iterable = [hs.signals.BaseSignal(np.random.random((2,)*(i+1))) for i in range(3)] >>> signal_iterable [<BaseSignal, title: , dimensions: (|2)>, <BaseSignal, title: , dimensions: (|2, 2)>, <BaseSignal, title: , dimensions: (|2, 2, 2)>] >>> hs.transpose(*signal_iterable, signal_axes=1) [<BaseSignal, title: , dimensions: (|2)>, <BaseSignal, title: , dimensions: (2|2)>, <BaseSignal, title: , dimensions: (2, 2|2)>] >>> hs.transpose(signal1, signal2, signal3, signal_axes=["Energy"]) """ from hyperspy.signal import BaseSignal if not all(map(isinstance, args, (BaseSignal for _ in args))): raise ValueError("Not all pased objects are signals") return [sig.transpose(signal_axes=signal_axes, navigation_axes=navigation_axes, optimize=optimize) for sig in args]
gpl-3.0
tavaresdong/courses-notes
ucb_cs61A/projects/ants/tests/02.py
4
2267
test = { 'name': 'Problem 2', 'points': 2, 'suites': [ { 'cases': [ { 'code': r""" >>> # Simple test for Place >>> place0 = Place('place_0') >>> print(place0.exit) None >>> print(place0.entrance) None >>> place1 = Place('place_1', place0) >>> place1.exit is place0 True >>> place0.entrance is place1 True """, 'hidden': False, 'locked': False }, { 'code': r""" >>> # Testing if entrances are properly initialized >>> tunnel_len = 9 >>> for entrance in colony.bee_entrances: ... num_places = 0 ... place = entrance ... while place is not colony.queen: ... num_places += 1 ... assert place.entrance is not None,\ ... '{0} has no entrance'.format(place.name) ... place = place.exit ... assert num_places == tunnel_len,\ ... 'Found {0} places in tunnel instead of {1}'.format(num_places,tunnel_len) """, 'hidden': False, 'locked': False }, { 'code': r""" >>> # Testing if exits and entrances are different >>> for place in colony.places.values(): ... assert place is not place.exit,\ ... "{0}'s exit leads to itself".format(place.name) ... assert place is not place.entrance,\ ... "{0}'s entrance leads to itself".format(place.name) ... if place.exit and place.entrance: ... assert place.exit is not place.entrance,\ ... "{0}'s entrance and exit are the same".format(place.name) """, 'hidden': False, 'locked': False } ], 'scored': True, 'setup': r""" >>> from ants import * >>> hive, layout = Hive(make_test_assault_plan()), dry_layout >>> dimensions = (1, 9) >>> colony = AntColony(None, hive, ant_types(), layout, dimensions) """, 'teardown': '', 'type': 'doctest' } ] }
mit
lincoln-lil/flink
flink-python/pyflink/fn_execution/coders.py
1
21445
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ import os from abc import ABC, abstractmethod import pyarrow as pa import pytz from pyflink.fn_execution import flink_fn_execution_pb2 from pyflink.table.types import TinyIntType, SmallIntType, IntType, BigIntType, BooleanType, \ FloatType, DoubleType, VarCharType, VarBinaryType, DecimalType, DateType, TimeType, \ LocalZonedTimestampType, RowType, RowField, to_arrow_type, TimestampType, ArrayType try: from pyflink.fn_execution import coder_impl_fast as coder_impl except: from pyflink.fn_execution import coder_impl_slow as coder_impl __all__ = ['FlattenRowCoder', 'RowCoder', 'BigIntCoder', 'TinyIntCoder', 'BooleanCoder', 'SmallIntCoder', 'IntCoder', 'FloatCoder', 'DoubleCoder', 'BinaryCoder', 'CharCoder', 'DateCoder', 'TimeCoder', 'TimestampCoder', 'LocalZonedTimestampCoder', 'BasicArrayCoder', 'PrimitiveArrayCoder', 'MapCoder', 'DecimalCoder', 'BigDecimalCoder', 'TupleCoder', 'TimeWindowCoder', 'CountWindowCoder'] # LengthPrefixBaseCoder will be used in Operations and other coders will be the field coder # of LengthPrefixBaseCoder class LengthPrefixBaseCoder(ABC): def __init__(self, field_coder: 'FieldCoder'): self._field_coder = field_coder @abstractmethod def get_impl(self): pass @classmethod def from_coder_param_proto(cls, coder_param_proto): field_coder = cls._to_field_coder(coder_param_proto) output_mode = coder_param_proto.output_mode if output_mode == flink_fn_execution_pb2.CoderParam.SINGLE: return ValueCoder(field_coder) else: return IterableCoder(field_coder, output_mode) @classmethod def _to_field_coder(cls, coder_param_proto): data_type = coder_param_proto.data_type if data_type == flink_fn_execution_pb2.CoderParam.FLATTEN_ROW: if coder_param_proto.HasField('schema'): schema_proto = coder_param_proto.schema field_coders = [from_proto(f.type) for f in schema_proto.fields] else: type_info_proto = coder_param_proto.type_info field_coders = [from_type_info_proto(f.field_type) for f in type_info_proto.row_type_info.fields] return FlattenRowCoder(field_coders) elif data_type == flink_fn_execution_pb2.CoderParam.ROW: schema_proto = coder_param_proto.schema field_coders = [from_proto(f.type) for f in schema_proto.fields] field_names = [f.name for f in schema_proto.fields] return RowCoder(field_coders, field_names) elif data_type == flink_fn_execution_pb2.CoderParam.RAW: type_info_proto = coder_param_proto.type_info field_coder = from_type_info_proto(type_info_proto) return field_coder elif data_type == flink_fn_execution_pb2.CoderParam.ARROW: timezone = pytz.timezone(os.environ['table.exec.timezone']) schema_proto = coder_param_proto.schema row_type = cls._to_row_type(schema_proto) return ArrowCoder(cls._to_arrow_schema(row_type), row_type, timezone) elif data_type == flink_fn_execution_pb2.CoderParam.OVER_WINDOW_ARROW: timezone = pytz.timezone(os.environ['table.exec.timezone']) schema_proto = coder_param_proto.schema row_type = cls._to_row_type(schema_proto) return OverWindowArrowCoder( cls._to_arrow_schema(row_type), row_type, timezone) else: raise ValueError("Unexpected coder type %s" % data_type) @classmethod def _to_arrow_schema(cls, row_type): return pa.schema([pa.field(n, to_arrow_type(t), t._nullable) for n, t in zip(row_type.field_names(), row_type.field_types())]) @classmethod def _to_data_type(cls, field_type): if field_type.type_name == flink_fn_execution_pb2.Schema.TINYINT: return TinyIntType(field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.SMALLINT: return SmallIntType(field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.INT: return IntType(field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.BIGINT: return BigIntType(field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.BOOLEAN: return BooleanType(field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.FLOAT: return FloatType(field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.DOUBLE: return DoubleType(field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.VARCHAR: return VarCharType(0x7fffffff, field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.VARBINARY: return VarBinaryType(0x7fffffff, field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.DECIMAL: return DecimalType(field_type.decimal_info.precision, field_type.decimal_info.scale, field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.DATE: return DateType(field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.TIME: return TimeType(field_type.time_info.precision, field_type.nullable) elif field_type.type_name == \ flink_fn_execution_pb2.Schema.LOCAL_ZONED_TIMESTAMP: return LocalZonedTimestampType(field_type.local_zoned_timestamp_info.precision, field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.TIMESTAMP: return TimestampType(field_type.timestamp_info.precision, field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.BASIC_ARRAY: return ArrayType(cls._to_data_type(field_type.collection_element_type), field_type.nullable) elif field_type.type_name == flink_fn_execution_pb2.Schema.TypeName.ROW: return RowType( [RowField(f.name, cls._to_data_type(f.type), f.description) for f in field_type.row_schema.fields], field_type.nullable) else: raise ValueError("field_type %s is not supported." % field_type) @classmethod def _to_row_type(cls, row_schema): return RowType([RowField(f.name, cls._to_data_type(f.type)) for f in row_schema.fields]) class FieldCoder(ABC): def get_impl(self) -> coder_impl.FieldCoderImpl: pass class IterableCoder(LengthPrefixBaseCoder): """ Coder for iterable data. """ def __init__(self, field_coder: FieldCoder, output_mode): super(IterableCoder, self).__init__(field_coder) self._output_mode = output_mode def get_impl(self): return coder_impl.IterableCoderImpl(self._field_coder.get_impl(), self._output_mode) class ValueCoder(LengthPrefixBaseCoder): """ Coder for single data. """ def __init__(self, field_coder: FieldCoder): super(ValueCoder, self).__init__(field_coder) def get_impl(self): if isinstance(self._field_coder, (ArrowCoder, OverWindowArrowCoder)): # ArrowCoder and OverWindowArrowCoder doesn't support fast coder currently. from pyflink.fn_execution import coder_impl_slow return coder_impl_slow.ValueCoderImpl(self._field_coder.get_impl()) else: return coder_impl.ValueCoderImpl(self._field_coder.get_impl()) class FlattenRowCoder(FieldCoder): """ Coder for Row. The decoded result will be flattened as a list of column values of a row instead of a row object. """ def __init__(self, field_coders): self._field_coders = field_coders def get_impl(self): return coder_impl.FlattenRowCoderImpl([c.get_impl() for c in self._field_coders]) def __repr__(self): return 'FlattenRowCoder[%s]' % ', '.join(str(c) for c in self._field_coders) def __eq__(self, other: 'FlattenRowCoder'): return (self.__class__ == other.__class__ and len(self._field_coders) == len(other._field_coders) and [self._field_coders[i] == other._field_coders[i] for i in range(len(self._field_coders))]) def __ne__(self, other): return not self == other def __hash__(self): return hash(self._field_coders) class ArrowCoder(FieldCoder): """ Coder for Arrow. """ def __init__(self, schema, row_type, timezone): self._schema = schema self._row_type = row_type self._timezone = timezone def get_impl(self): # ArrowCoder doesn't support fast coder implementation currently. from pyflink.fn_execution import coder_impl_slow return coder_impl_slow.ArrowCoderImpl(self._schema, self._row_type, self._timezone) def __repr__(self): return 'ArrowCoder[%s]' % self._schema class OverWindowArrowCoder(FieldCoder): """ Coder for batch pandas over window aggregation. """ def __init__(self, schema, row_type, timezone): self._arrow_coder = ArrowCoder(schema, row_type, timezone) def get_impl(self): # OverWindowArrowCoder doesn't support fast coder implementation currently. from pyflink.fn_execution import coder_impl_slow return coder_impl_slow.OverWindowArrowCoderImpl(self._arrow_coder.get_impl()) def __repr__(self): return 'OverWindowArrowCoder[%s]' % self._arrow_coder class RowCoder(FieldCoder): """ Coder for Row. """ def __init__(self, field_coders, field_names): self._field_coders = field_coders self._field_names = field_names def get_impl(self): return coder_impl.RowCoderImpl([c.get_impl() for c in self._field_coders], self._field_names) def __repr__(self): return 'RowCoder[%s]' % ', '.join(str(c) for c in self._field_coders) def __eq__(self, other: 'RowCoder'): return (self.__class__ == other.__class__ and self._field_names == other._field_names and [self._field_coders[i] == other._field_coders[i] for i in range(len(self._field_coders))]) def __ne__(self, other): return not self == other def __hash__(self): return hash(self._field_coders) class CollectionCoder(FieldCoder): """ Base coder for collection. """ def __init__(self, elem_coder): self._elem_coder = elem_coder def is_deterministic(self): return self._elem_coder.is_deterministic() def __eq__(self, other: 'CollectionCoder'): return (self.__class__ == other.__class__ and self._elem_coder == other._elem_coder) def __repr__(self): return '%s[%s]' % (self.__class__.__name__, repr(self._elem_coder)) def __ne__(self, other): return not self == other def __hash__(self): return hash(self._elem_coder) class BasicArrayCoder(CollectionCoder): """ Coder for Array. """ def __init__(self, elem_coder): super(BasicArrayCoder, self).__init__(elem_coder) def get_impl(self): return coder_impl.BasicArrayCoderImpl(self._elem_coder.get_impl()) class PrimitiveArrayCoder(CollectionCoder): """ Coder for Primitive Array. """ def __init__(self, elem_coder): super(PrimitiveArrayCoder, self).__init__(elem_coder) def get_impl(self): return coder_impl.PrimitiveArrayCoderImpl(self._elem_coder.get_impl()) class MapCoder(FieldCoder): """ Coder for Map. """ def __init__(self, key_coder, value_coder): self._key_coder = key_coder self._value_coder = value_coder def get_impl(self): return coder_impl.MapCoderImpl(self._key_coder.get_impl(), self._value_coder.get_impl()) def is_deterministic(self): return self._key_coder.is_deterministic() and self._value_coder.is_deterministic() def __repr__(self): return 'MapCoder[%s]' % ','.join([repr(self._key_coder), repr(self._value_coder)]) def __eq__(self, other: 'MapCoder'): return (self.__class__ == other.__class__ and self._key_coder == other._key_coder and self._value_coder == other._value_coder) def __ne__(self, other): return not self == other def __hash__(self): return hash([self._key_coder, self._value_coder]) class BigIntCoder(FieldCoder): """ Coder for 8 bytes long. """ def get_impl(self): return coder_impl.BigIntCoderImpl() class TinyIntCoder(FieldCoder): """ Coder for Byte. """ def get_impl(self): return coder_impl.TinyIntCoderImpl() class BooleanCoder(FieldCoder): """ Coder for Boolean. """ def get_impl(self): return coder_impl.BooleanCoderImpl() class SmallIntCoder(FieldCoder): """ Coder for Short. """ def get_impl(self): return coder_impl.SmallIntCoderImpl() class IntCoder(FieldCoder): """ Coder for 4 bytes int. """ def get_impl(self): return coder_impl.IntCoderImpl() class FloatCoder(FieldCoder): """ Coder for Float. """ def get_impl(self): return coder_impl.FloatCoderImpl() class DoubleCoder(FieldCoder): """ Coder for Double. """ def get_impl(self): return coder_impl.DoubleCoderImpl() class DecimalCoder(FieldCoder): """ Coder for Decimal. """ def __init__(self, precision, scale): self.precision = precision self.scale = scale def get_impl(self): return coder_impl.DecimalCoderImpl(self.precision, self.scale) class BigDecimalCoder(FieldCoder): """ Coder for Basic Decimal that no need to have precision and scale specified. """ def get_impl(self): return coder_impl.BigDecimalCoderImpl() class BinaryCoder(FieldCoder): """ Coder for Byte Array. """ def get_impl(self): return coder_impl.BinaryCoderImpl() class CharCoder(FieldCoder): """ Coder for Character String. """ def get_impl(self): return coder_impl.CharCoderImpl() class DateCoder(FieldCoder): """ Coder for Date """ def get_impl(self): return coder_impl.DateCoderImpl() class TimeCoder(FieldCoder): """ Coder for Time. """ def get_impl(self): return coder_impl.TimeCoderImpl() class TimestampCoder(FieldCoder): """ Coder for Timestamp. """ def __init__(self, precision): self.precision = precision def get_impl(self): return coder_impl.TimestampCoderImpl(self.precision) class LocalZonedTimestampCoder(FieldCoder): """ Coder for LocalZonedTimestamp. """ def __init__(self, precision, timezone): self.precision = precision self.timezone = timezone def get_impl(self): return coder_impl.LocalZonedTimestampCoderImpl(self.precision, self.timezone) class PickledBytesCoder(FieldCoder): def get_impl(self): return coder_impl.PickledBytesCoderImpl() class TupleCoder(FieldCoder): """ Coder for Tuple. """ def __init__(self, field_coders): self._field_coders = field_coders def get_impl(self): return coder_impl.TupleCoderImpl([c.get_impl() for c in self._field_coders]) def __repr__(self): return 'TupleCoder[%s]' % ', '.join(str(c) for c in self._field_coders) class TimeWindowCoder(FieldCoder): """ Coder for TimeWindow. """ def get_impl(self): return coder_impl.TimeWindowCoderImpl() class CountWindowCoder(FieldCoder): """ Coder for CountWindow. """ def get_impl(self): return coder_impl.CountWindowCoderImpl() type_name = flink_fn_execution_pb2.Schema _type_name_mappings = { type_name.TINYINT: TinyIntCoder(), type_name.SMALLINT: SmallIntCoder(), type_name.INT: IntCoder(), type_name.BIGINT: BigIntCoder(), type_name.BOOLEAN: BooleanCoder(), type_name.FLOAT: FloatCoder(), type_name.DOUBLE: DoubleCoder(), type_name.BINARY: BinaryCoder(), type_name.VARBINARY: BinaryCoder(), type_name.CHAR: CharCoder(), type_name.VARCHAR: CharCoder(), type_name.DATE: DateCoder(), type_name.TIME: TimeCoder(), } def from_proto(field_type): """ Creates the corresponding :class:`Coder` given the protocol representation of the field type. :param field_type: the protocol representation of the field type :return: :class:`Coder` """ field_type_name = field_type.type_name coder = _type_name_mappings.get(field_type_name) if coder is not None: return coder if field_type_name == type_name.ROW: return RowCoder([from_proto(f.type) for f in field_type.row_schema.fields], [f.name for f in field_type.row_schema.fields]) if field_type_name == type_name.TIMESTAMP: return TimestampCoder(field_type.timestamp_info.precision) if field_type_name == type_name.LOCAL_ZONED_TIMESTAMP: timezone = pytz.timezone(os.environ['table.exec.timezone']) return LocalZonedTimestampCoder(field_type.local_zoned_timestamp_info.precision, timezone) elif field_type_name == type_name.BASIC_ARRAY: return BasicArrayCoder(from_proto(field_type.collection_element_type)) elif field_type_name == type_name.MAP: return MapCoder(from_proto(field_type.map_info.key_type), from_proto(field_type.map_info.value_type)) elif field_type_name == type_name.DECIMAL: return DecimalCoder(field_type.decimal_info.precision, field_type.decimal_info.scale) else: raise ValueError("field_type %s is not supported." % field_type) # for data stream type information. type_info_name = flink_fn_execution_pb2.TypeInfo _type_info_name_mappings = { type_info_name.STRING: CharCoder(), type_info_name.BYTE: TinyIntCoder(), type_info_name.BOOLEAN: BooleanCoder(), type_info_name.SHORT: SmallIntCoder(), type_info_name.INT: IntCoder(), type_info_name.LONG: BigIntCoder(), type_info_name.FLOAT: FloatCoder(), type_info_name.DOUBLE: DoubleCoder(), type_info_name.CHAR: CharCoder(), type_info_name.BIG_INT: BigIntCoder(), type_info_name.BIG_DEC: BigDecimalCoder(), type_info_name.SQL_DATE: DateCoder(), type_info_name.SQL_TIME: TimeCoder(), type_info_name.SQL_TIMESTAMP: TimestampCoder(3), type_info_name.PICKLED_BYTES: PickledBytesCoder() } def from_type_info_proto(type_info): field_type_name = type_info.type_name try: return _type_info_name_mappings[field_type_name] except KeyError: if field_type_name == type_info_name.ROW: return RowCoder( [from_type_info_proto(f.field_type) for f in type_info.row_type_info.fields], [f.field_name for f in type_info.row_type_info.fields]) elif field_type_name == type_info_name.PRIMITIVE_ARRAY: if type_info.collection_element_type.type_name == type_info_name.BYTE: return BinaryCoder() return PrimitiveArrayCoder(from_type_info_proto(type_info.collection_element_type)) elif field_type_name == type_info_name.BASIC_ARRAY: return BasicArrayCoder(from_type_info_proto(type_info.collection_element_type)) elif field_type_name == type_info_name.TUPLE: return TupleCoder([from_type_info_proto(field_type) for field_type in type_info.tuple_type_info.field_types]) elif field_type_name == type_info_name.MAP: return MapCoder(from_type_info_proto(type_info.map_type_info.key_type), from_type_info_proto(type_info.map_type_info.value_type)) elif field_type_name == type_info_name.LIST: return BasicArrayCoder(from_type_info_proto(type_info.collection_element_type)) else: raise ValueError("Unsupported type_info %s." % type_info)
apache-2.0
nichit93/Implementation-of-TRED-in-ns-3
src/mobility/bindings/modulegen__gcc_LP64.py
38
321845
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.mobility', 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') ## 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']) ## box.h (module 'mobility'): ns3::Box [class] module.add_class('Box') ## box.h (module 'mobility'): ns3::Box::Side [enumeration] module.add_enum('Side', ['RIGHT', 'LEFT', 'TOP', 'BOTTOM', 'UP', 'DOWN'], outer_class=root_module['ns3::Box']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper [class] module.add_class('ConstantVelocityHelper') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## geographic-positions.h (module 'mobility'): ns3::GeographicPositions [class] module.add_class('GeographicPositions') ## geographic-positions.h (module 'mobility'): ns3::GeographicPositions::EarthSpheroidType [enumeration] module.add_enum('EarthSpheroidType', ['SPHERE', 'GRS80', 'WGS84'], outer_class=root_module['ns3::GeographicPositions']) ## 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') ## mobility-helper.h (module 'mobility'): ns3::MobilityHelper [class] module.add_class('MobilityHelper') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## ns2-mobility-helper.h (module 'mobility'): ns3::Ns2MobilityHelper [class] module.add_class('Ns2MobilityHelper') ## 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') ## rectangle.h (module 'mobility'): ns3::Rectangle [class] module.add_class('Rectangle') ## rectangle.h (module 'mobility'): ns3::Rectangle::Side [enumeration] module.add_enum('Side', ['RIGHT', 'LEFT', 'TOP', 'BOTTOM'], outer_class=root_module['ns3::Rectangle']) ## 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')) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## 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') ## waypoint.h (module 'mobility'): ns3::Waypoint [class] module.add_class('Waypoint') ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## 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']) ## position-allocator.h (module 'mobility'): ns3::PositionAllocator [class] module.add_class('PositionAllocator', parent=root_module['ns3::Object']) ## position-allocator.h (module 'mobility'): ns3::RandomBoxPositionAllocator [class] module.add_class('RandomBoxPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## position-allocator.h (module 'mobility'): ns3::RandomDiscPositionAllocator [class] module.add_class('RandomDiscPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## position-allocator.h (module 'mobility'): ns3::RandomRectanglePositionAllocator [class] module.add_class('RandomRectanglePositionAllocator', parent=root_module['ns3::PositionAllocator']) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## position-allocator.h (module 'mobility'): ns3::UniformDiscPositionAllocator [class] module.add_class('UniformDiscPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## 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> >']) ## box.h (module 'mobility'): ns3::BoxChecker [class] module.add_class('BoxChecker', parent=root_module['ns3::AttributeChecker']) ## box.h (module 'mobility'): ns3::BoxValue [class] module.add_class('BoxValue', parent=root_module['ns3::AttributeValue']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class] module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator [class] module.add_class('GridPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator::LayoutType [enumeration] module.add_enum('LayoutType', ['ROW_FIRST', 'COLUMN_FIRST'], outer_class=root_module['ns3::GridPositionAllocator']) ## 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']) ## position-allocator.h (module 'mobility'): ns3::ListPositionAllocator [class] module.add_class('ListPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## mobility-model.h (module 'mobility'): ns3::MobilityModel [class] module.add_class('MobilityModel', parent=root_module['ns3::Object']) ## 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') ## net-device.h (module 'network'): ns3::NetDeviceQueue [class] module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface [class] module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class] module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## net-device.h (module 'network'): ns3::QueueItem [class] module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) ## net-device.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration] module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network') ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::RandomDirection2dMobilityModel [class] module.add_class('RandomDirection2dMobilityModel', parent=root_module['ns3::MobilityModel']) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::RandomWalk2dMobilityModel [class] module.add_class('RandomWalk2dMobilityModel', parent=root_module['ns3::MobilityModel']) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::RandomWalk2dMobilityModel::Mode [enumeration] module.add_enum('Mode', ['MODE_DISTANCE', 'MODE_TIME'], outer_class=root_module['ns3::RandomWalk2dMobilityModel']) ## random-waypoint-mobility-model.h (module 'mobility'): ns3::RandomWaypointMobilityModel [class] module.add_class('RandomWaypointMobilityModel', parent=root_module['ns3::MobilityModel']) ## rectangle.h (module 'mobility'): ns3::RectangleChecker [class] module.add_class('RectangleChecker', parent=root_module['ns3::AttributeChecker']) ## rectangle.h (module 'mobility'): ns3::RectangleValue [class] module.add_class('RectangleValue', parent=root_module['ns3::AttributeValue']) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::SteadyStateRandomWaypointMobilityModel [class] module.add_class('SteadyStateRandomWaypointMobilityModel', parent=root_module['ns3::MobilityModel']) ## 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']) ## waypoint.h (module 'mobility'): ns3::WaypointChecker [class] module.add_class('WaypointChecker', parent=root_module['ns3::AttributeChecker']) ## waypoint-mobility-model.h (module 'mobility'): ns3::WaypointMobilityModel [class] module.add_class('WaypointMobilityModel', parent=root_module['ns3::MobilityModel']) ## waypoint.h (module 'mobility'): ns3::WaypointValue [class] module.add_class('WaypointValue', 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']) ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::ConstantAccelerationMobilityModel [class] module.add_class('ConstantAccelerationMobilityModel', parent=root_module['ns3::MobilityModel']) ## constant-position-mobility-model.h (module 'mobility'): ns3::ConstantPositionMobilityModel [class] module.add_class('ConstantPositionMobilityModel', parent=root_module['ns3::MobilityModel']) ## constant-velocity-mobility-model.h (module 'mobility'): ns3::ConstantVelocityMobilityModel [class] module.add_class('ConstantVelocityMobilityModel', parent=root_module['ns3::MobilityModel']) ## gauss-markov-mobility-model.h (module 'mobility'): ns3::GaussMarkovMobilityModel [class] module.add_class('GaussMarkovMobilityModel', parent=root_module['ns3::MobilityModel']) ## hierarchical-mobility-model.h (module 'mobility'): ns3::HierarchicalMobilityModel [class] module.add_class('HierarchicalMobilityModel', parent=root_module['ns3::MobilityModel']) module.add_container('std::list< ns3::Vector3D >', 'ns3::Vector3D', container_type=u'list') typehandlers.add_type_alias(u'ns3::Vector3D', u'ns3::Vector') typehandlers.add_type_alias(u'ns3::Vector3D*', u'ns3::Vector*') typehandlers.add_type_alias(u'ns3::Vector3D&', u'ns3::Vector&') module.add_typedef(root_module['ns3::Vector3D'], 'Vector') typehandlers.add_type_alias(u'ns3::Vector3DValue', u'ns3::VectorValue') typehandlers.add_type_alias(u'ns3::Vector3DValue*', u'ns3::VectorValue*') typehandlers.add_type_alias(u'ns3::Vector3DValue&', u'ns3::VectorValue&') module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue') typehandlers.add_type_alias(u'ns3::Vector3DChecker', u'ns3::VectorChecker') typehandlers.add_type_alias(u'ns3::Vector3DChecker*', u'ns3::VectorChecker*') typehandlers.add_type_alias(u'ns3::Vector3DChecker&', u'ns3::VectorChecker&') module.add_typedef(root_module['ns3::Vector3DChecker'], 'VectorChecker') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&') def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Box_methods(root_module, root_module['ns3::Box']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3ConstantVelocityHelper_methods(root_module, root_module['ns3::ConstantVelocityHelper']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3GeographicPositions_methods(root_module, root_module['ns3::GeographicPositions']) 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_Ns3MobilityHelper_methods(root_module, root_module['ns3::MobilityHelper']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3Ns2MobilityHelper_methods(root_module, root_module['ns3::Ns2MobilityHelper']) 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_Ns3Rectangle_methods(root_module, root_module['ns3::Rectangle']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D']) register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D']) register_Ns3Waypoint_methods(root_module, root_module['ns3::Waypoint']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PositionAllocator_methods(root_module, root_module['ns3::PositionAllocator']) register_Ns3RandomBoxPositionAllocator_methods(root_module, root_module['ns3::RandomBoxPositionAllocator']) register_Ns3RandomDiscPositionAllocator_methods(root_module, root_module['ns3::RandomDiscPositionAllocator']) register_Ns3RandomRectanglePositionAllocator_methods(root_module, root_module['ns3::RandomRectanglePositionAllocator']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3UniformDiscPositionAllocator_methods(root_module, root_module['ns3::UniformDiscPositionAllocator']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_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_Ns3BoxChecker_methods(root_module, root_module['ns3::BoxChecker']) register_Ns3BoxValue_methods(root_module, root_module['ns3::BoxValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3GridPositionAllocator_methods(root_module, root_module['ns3::GridPositionAllocator']) 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_Ns3ListPositionAllocator_methods(root_module, root_module['ns3::ListPositionAllocator']) register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue']) register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem']) register_Ns3RandomDirection2dMobilityModel_methods(root_module, root_module['ns3::RandomDirection2dMobilityModel']) register_Ns3RandomWalk2dMobilityModel_methods(root_module, root_module['ns3::RandomWalk2dMobilityModel']) register_Ns3RandomWaypointMobilityModel_methods(root_module, root_module['ns3::RandomWaypointMobilityModel']) register_Ns3RectangleChecker_methods(root_module, root_module['ns3::RectangleChecker']) register_Ns3RectangleValue_methods(root_module, root_module['ns3::RectangleValue']) register_Ns3SteadyStateRandomWaypointMobilityModel_methods(root_module, root_module['ns3::SteadyStateRandomWaypointMobilityModel']) 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_Ns3WaypointChecker_methods(root_module, root_module['ns3::WaypointChecker']) register_Ns3WaypointMobilityModel_methods(root_module, root_module['ns3::WaypointMobilityModel']) register_Ns3WaypointValue_methods(root_module, root_module['ns3::WaypointValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3ConstantAccelerationMobilityModel_methods(root_module, root_module['ns3::ConstantAccelerationMobilityModel']) register_Ns3ConstantPositionMobilityModel_methods(root_module, root_module['ns3::ConstantPositionMobilityModel']) register_Ns3ConstantVelocityMobilityModel_methods(root_module, root_module['ns3::ConstantVelocityMobilityModel']) register_Ns3GaussMarkovMobilityModel_methods(root_module, root_module['ns3::GaussMarkovMobilityModel']) register_Ns3HierarchicalMobilityModel_methods(root_module, root_module['ns3::HierarchicalMobilityModel']) 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_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_Ns3Box_methods(root_module, cls): cls.add_output_stream_operator() ## box.h (module 'mobility'): ns3::Box::Box(ns3::Box const & arg0) [copy constructor] cls.add_constructor([param('ns3::Box const &', 'arg0')]) ## box.h (module 'mobility'): ns3::Box::Box(double _xMin, double _xMax, double _yMin, double _yMax, double _zMin, double _zMax) [constructor] cls.add_constructor([param('double', '_xMin'), param('double', '_xMax'), param('double', '_yMin'), param('double', '_yMax'), param('double', '_zMin'), param('double', '_zMax')]) ## box.h (module 'mobility'): ns3::Box::Box() [constructor] cls.add_constructor([]) ## box.h (module 'mobility'): ns3::Vector ns3::Box::CalculateIntersection(ns3::Vector const & current, ns3::Vector const & speed) const [member function] cls.add_method('CalculateIntersection', 'ns3::Vector', [param('ns3::Vector const &', 'current'), param('ns3::Vector const &', 'speed')], is_const=True) ## box.h (module 'mobility'): ns3::Box::Side ns3::Box::GetClosestSide(ns3::Vector const & position) const [member function] cls.add_method('GetClosestSide', 'ns3::Box::Side', [param('ns3::Vector const &', 'position')], is_const=True) ## box.h (module 'mobility'): bool ns3::Box::IsInside(ns3::Vector const & position) const [member function] cls.add_method('IsInside', 'bool', [param('ns3::Vector const &', 'position')], is_const=True) ## box.h (module 'mobility'): ns3::Box::xMax [variable] cls.add_instance_attribute('xMax', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::xMin [variable] cls.add_instance_attribute('xMin', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::yMax [variable] cls.add_instance_attribute('yMax', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::yMin [variable] cls.add_instance_attribute('yMin', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::zMax [variable] cls.add_instance_attribute('zMax', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::zMin [variable] cls.add_instance_attribute('zMin', 'double', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') return def register_Ns3ConstantVelocityHelper_methods(root_module, cls): ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper::ConstantVelocityHelper(ns3::ConstantVelocityHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantVelocityHelper const &', 'arg0')]) ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper::ConstantVelocityHelper() [constructor] cls.add_constructor([]) ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper::ConstantVelocityHelper(ns3::Vector const & position) [constructor] cls.add_constructor([param('ns3::Vector const &', 'position')]) ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper::ConstantVelocityHelper(ns3::Vector const & position, ns3::Vector const & vel) [constructor] cls.add_constructor([param('ns3::Vector const &', 'position'), param('ns3::Vector const &', 'vel')]) ## constant-velocity-helper.h (module 'mobility'): ns3::Vector ns3::ConstantVelocityHelper::GetCurrentPosition() const [member function] cls.add_method('GetCurrentPosition', 'ns3::Vector', [], is_const=True) ## constant-velocity-helper.h (module 'mobility'): ns3::Vector ns3::ConstantVelocityHelper::GetVelocity() const [member function] cls.add_method('GetVelocity', 'ns3::Vector', [], is_const=True) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::Pause() [member function] cls.add_method('Pause', 'void', []) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::SetPosition(ns3::Vector const & position) [member function] cls.add_method('SetPosition', 'void', [param('ns3::Vector const &', 'position')]) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::SetVelocity(ns3::Vector const & vel) [member function] cls.add_method('SetVelocity', 'void', [param('ns3::Vector const &', 'vel')]) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::Unpause() [member function] cls.add_method('Unpause', 'void', []) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::Update() const [member function] cls.add_method('Update', 'void', [], is_const=True) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::UpdateWithBounds(ns3::Rectangle const & rectangle) const [member function] cls.add_method('UpdateWithBounds', 'void', [param('ns3::Rectangle const &', 'rectangle')], is_const=True) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::UpdateWithBounds(ns3::Box const & bounds) const [member function] cls.add_method('UpdateWithBounds', 'void', [param('ns3::Box const &', 'bounds')], 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_Ns3GeographicPositions_methods(root_module, cls): ## geographic-positions.h (module 'mobility'): ns3::GeographicPositions::GeographicPositions() [constructor] cls.add_constructor([]) ## geographic-positions.h (module 'mobility'): ns3::GeographicPositions::GeographicPositions(ns3::GeographicPositions const & arg0) [copy constructor] cls.add_constructor([param('ns3::GeographicPositions const &', 'arg0')]) ## geographic-positions.h (module 'mobility'): static ns3::Vector ns3::GeographicPositions::GeographicToCartesianCoordinates(double latitude, double longitude, double altitude, ns3::GeographicPositions::EarthSpheroidType sphType) [member function] cls.add_method('GeographicToCartesianCoordinates', 'ns3::Vector', [param('double', 'latitude'), param('double', 'longitude'), param('double', 'altitude'), param('ns3::GeographicPositions::EarthSpheroidType', 'sphType')], is_static=True) ## geographic-positions.h (module 'mobility'): static std::list<ns3::Vector3D,std::allocator<ns3::Vector3D> > ns3::GeographicPositions::RandCartesianPointsAroundGeographicPoint(double originLatitude, double originLongitude, double maxAltitude, int numPoints, double maxDistFromOrigin, ns3::Ptr<ns3::UniformRandomVariable> uniRand) [member function] cls.add_method('RandCartesianPointsAroundGeographicPoint', 'std::list< ns3::Vector3D >', [param('double', 'originLatitude'), param('double', 'originLongitude'), param('double', 'maxAltitude'), param('int', 'numPoints'), param('double', 'maxDistFromOrigin'), param('ns3::Ptr< ns3::UniformRandomVariable >', 'uniRand')], is_static=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::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], deprecated=True, is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3MobilityHelper_methods(root_module, cls): ## mobility-helper.h (module 'mobility'): ns3::MobilityHelper::MobilityHelper(ns3::MobilityHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::MobilityHelper const &', 'arg0')]) ## mobility-helper.h (module 'mobility'): ns3::MobilityHelper::MobilityHelper() [constructor] cls.add_constructor([]) ## mobility-helper.h (module 'mobility'): int64_t ns3::MobilityHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')]) ## mobility-helper.h (module 'mobility'): static void ns3::MobilityHelper::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid')], is_static=True) ## mobility-helper.h (module 'mobility'): static void ns3::MobilityHelper::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')], is_static=True) ## mobility-helper.h (module 'mobility'): static void ns3::MobilityHelper::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiAll', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## mobility-helper.h (module 'mobility'): static double ns3::MobilityHelper::GetDistanceSquaredBetween(ns3::Ptr<ns3::Node> n1, ns3::Ptr<ns3::Node> n2) [member function] cls.add_method('GetDistanceSquaredBetween', 'double', [param('ns3::Ptr< ns3::Node >', 'n1'), param('ns3::Ptr< ns3::Node >', 'n2')], is_static=True) ## mobility-helper.h (module 'mobility'): std::string ns3::MobilityHelper::GetMobilityModelType() const [member function] cls.add_method('GetMobilityModelType', 'std::string', [], is_const=True) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'void', [param('std::string', 'nodeName')], is_const=True) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::Install(ns3::NodeContainer container) const [member function] cls.add_method('Install', 'void', [param('ns3::NodeContainer', 'container')], is_const=True) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::InstallAll() [member function] cls.add_method('InstallAll', 'void', []) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::PopReferenceMobilityModel() [member function] cls.add_method('PopReferenceMobilityModel', 'void', []) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::PushReferenceMobilityModel(ns3::Ptr<ns3::Object> reference) [member function] cls.add_method('PushReferenceMobilityModel', 'void', [param('ns3::Ptr< ns3::Object >', 'reference')]) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::PushReferenceMobilityModel(std::string referenceName) [member function] cls.add_method('PushReferenceMobilityModel', 'void', [param('std::string', 'referenceName')]) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::SetMobilityModel(std::string type, std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), 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(), std::string n8="", ns3::AttributeValue const & v8=ns3::EmptyAttributeValue(), std::string n9="", ns3::AttributeValue const & v9=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetMobilityModel', 'void', [param('std::string', 'type'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), 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()'), param('std::string', 'n8', default_value='""'), param('ns3::AttributeValue const &', 'v8', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n9', default_value='""'), param('ns3::AttributeValue const &', 'v9', default_value='ns3::EmptyAttributeValue()')]) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::SetPositionAllocator(ns3::Ptr<ns3::PositionAllocator> allocator) [member function] cls.add_method('SetPositionAllocator', 'void', [param('ns3::Ptr< ns3::PositionAllocator >', 'allocator')]) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::SetPositionAllocator(std::string type, std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), 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(), std::string n8="", ns3::AttributeValue const & v8=ns3::EmptyAttributeValue(), std::string n9="", ns3::AttributeValue const & v9=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetPositionAllocator', 'void', [param('std::string', 'type'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), 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()'), param('std::string', 'n8', default_value='""'), param('ns3::AttributeValue const &', 'v8', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n9', default_value='""'), param('ns3::AttributeValue const &', 'v9', default_value='ns3::EmptyAttributeValue()')]) 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_Ns3Ns2MobilityHelper_methods(root_module, cls): ## ns2-mobility-helper.h (module 'mobility'): ns3::Ns2MobilityHelper::Ns2MobilityHelper(ns3::Ns2MobilityHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ns2MobilityHelper const &', 'arg0')]) ## ns2-mobility-helper.h (module 'mobility'): ns3::Ns2MobilityHelper::Ns2MobilityHelper(std::string filename) [constructor] cls.add_constructor([param('std::string', 'filename')]) ## ns2-mobility-helper.h (module 'mobility'): void ns3::Ns2MobilityHelper::Install() const [member function] cls.add_method('Install', 'void', [], 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 & value) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3Rectangle_methods(root_module, cls): cls.add_output_stream_operator() ## rectangle.h (module 'mobility'): ns3::Rectangle::Rectangle(ns3::Rectangle const & arg0) [copy constructor] cls.add_constructor([param('ns3::Rectangle const &', 'arg0')]) ## rectangle.h (module 'mobility'): ns3::Rectangle::Rectangle(double _xMin, double _xMax, double _yMin, double _yMax) [constructor] cls.add_constructor([param('double', '_xMin'), param('double', '_xMax'), param('double', '_yMin'), param('double', '_yMax')]) ## rectangle.h (module 'mobility'): ns3::Rectangle::Rectangle() [constructor] cls.add_constructor([]) ## rectangle.h (module 'mobility'): ns3::Vector ns3::Rectangle::CalculateIntersection(ns3::Vector const & current, ns3::Vector const & speed) const [member function] cls.add_method('CalculateIntersection', 'ns3::Vector', [param('ns3::Vector const &', 'current'), param('ns3::Vector const &', 'speed')], is_const=True) ## rectangle.h (module 'mobility'): ns3::Rectangle::Side ns3::Rectangle::GetClosestSide(ns3::Vector const & position) const [member function] cls.add_method('GetClosestSide', 'ns3::Rectangle::Side', [param('ns3::Vector const &', 'position')], is_const=True) ## rectangle.h (module 'mobility'): bool ns3::Rectangle::IsInside(ns3::Vector const & position) const [member function] cls.add_method('IsInside', 'bool', [param('ns3::Vector const &', 'position')], is_const=True) ## rectangle.h (module 'mobility'): ns3::Rectangle::xMax [variable] cls.add_instance_attribute('xMax', 'double', is_const=False) ## rectangle.h (module 'mobility'): ns3::Rectangle::xMin [variable] cls.add_instance_attribute('xMin', 'double', is_const=False) ## rectangle.h (module 'mobility'): ns3::Rectangle::yMax [variable] cls.add_instance_attribute('yMax', 'double', is_const=False) ## rectangle.h (module 'mobility'): ns3::Rectangle::yMin [variable] cls.add_instance_attribute('yMin', 'double', 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_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')], deprecated=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function] cls.add_method('GetSize', 'std::size_t', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function] cls.add_method('SetSize', 'ns3::TypeId', [param('std::size_t', 'size')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t uid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'uid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable] cls.add_instance_attribute('callback', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_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_Ns3Waypoint_methods(root_module, cls): cls.add_output_stream_operator() ## waypoint.h (module 'mobility'): ns3::Waypoint::Waypoint(ns3::Waypoint const & arg0) [copy constructor] cls.add_constructor([param('ns3::Waypoint const &', 'arg0')]) ## waypoint.h (module 'mobility'): ns3::Waypoint::Waypoint(ns3::Time const & waypointTime, ns3::Vector const & waypointPosition) [constructor] cls.add_constructor([param('ns3::Time const &', 'waypointTime'), param('ns3::Vector const &', 'waypointPosition')]) ## waypoint.h (module 'mobility'): ns3::Waypoint::Waypoint() [constructor] cls.add_constructor([]) ## waypoint.h (module 'mobility'): ns3::Waypoint::position [variable] cls.add_instance_attribute('position', 'ns3::Vector', is_const=False) ## waypoint.h (module 'mobility'): ns3::Waypoint::time [variable] cls.add_instance_attribute('time', 'ns3::Time', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_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'): bool ns3::Object::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3PositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::PositionAllocator::PositionAllocator(ns3::PositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::PositionAllocator::PositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::PositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::PositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::PositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3RandomBoxPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::RandomBoxPositionAllocator::RandomBoxPositionAllocator(ns3::RandomBoxPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomBoxPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::RandomBoxPositionAllocator::RandomBoxPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::RandomBoxPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::RandomBoxPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::RandomBoxPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::RandomBoxPositionAllocator::SetX(ns3::Ptr<ns3::RandomVariableStream> x) [member function] cls.add_method('SetX', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'x')]) ## position-allocator.h (module 'mobility'): void ns3::RandomBoxPositionAllocator::SetY(ns3::Ptr<ns3::RandomVariableStream> y) [member function] cls.add_method('SetY', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'y')]) ## position-allocator.h (module 'mobility'): void ns3::RandomBoxPositionAllocator::SetZ(ns3::Ptr<ns3::RandomVariableStream> z) [member function] cls.add_method('SetZ', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'z')]) return def register_Ns3RandomDiscPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::RandomDiscPositionAllocator::RandomDiscPositionAllocator(ns3::RandomDiscPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomDiscPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::RandomDiscPositionAllocator::RandomDiscPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::RandomDiscPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::RandomDiscPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::RandomDiscPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::RandomDiscPositionAllocator::SetRho(ns3::Ptr<ns3::RandomVariableStream> rho) [member function] cls.add_method('SetRho', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'rho')]) ## position-allocator.h (module 'mobility'): void ns3::RandomDiscPositionAllocator::SetTheta(ns3::Ptr<ns3::RandomVariableStream> theta) [member function] cls.add_method('SetTheta', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'theta')]) ## position-allocator.h (module 'mobility'): void ns3::RandomDiscPositionAllocator::SetX(double x) [member function] cls.add_method('SetX', 'void', [param('double', 'x')]) ## position-allocator.h (module 'mobility'): void ns3::RandomDiscPositionAllocator::SetY(double y) [member function] cls.add_method('SetY', 'void', [param('double', 'y')]) return def register_Ns3RandomRectanglePositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::RandomRectanglePositionAllocator::RandomRectanglePositionAllocator(ns3::RandomRectanglePositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomRectanglePositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::RandomRectanglePositionAllocator::RandomRectanglePositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::RandomRectanglePositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::RandomRectanglePositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::RandomRectanglePositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::RandomRectanglePositionAllocator::SetX(ns3::Ptr<ns3::RandomVariableStream> x) [member function] cls.add_method('SetX', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'x')]) ## position-allocator.h (module 'mobility'): void ns3::RandomRectanglePositionAllocator::SetY(ns3::Ptr<ns3::RandomVariableStream> y) [member function] cls.add_method('SetY', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'y')]) return def register_Ns3RandomVariableStream_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function] cls.add_method('SetStream', 'void', [param('int64_t', 'stream')]) ## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function] cls.add_method('GetStream', 'int64_t', [], is_const=True) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function] cls.add_method('SetAntithetic', 'void', [param('bool', 'isAntithetic')]) ## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function] cls.add_method('IsAntithetic', 'bool', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function] cls.add_method('Peek', 'ns3::RngStream *', [], is_const=True, visibility='protected') return def register_Ns3SequentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function] cls.add_method('GetIncrement', 'ns3::Ptr< ns3::RandomVariableStream >', [], is_const=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function] cls.add_method('GetConsecutive', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_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_Ns3UniformDiscPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::UniformDiscPositionAllocator::UniformDiscPositionAllocator(ns3::UniformDiscPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::UniformDiscPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::UniformDiscPositionAllocator::UniformDiscPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::UniformDiscPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::UniformDiscPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::UniformDiscPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::UniformDiscPositionAllocator::SetRho(double rho) [member function] cls.add_method('SetRho', 'void', [param('double', 'rho')]) ## position-allocator.h (module 'mobility'): void ns3::UniformDiscPositionAllocator::SetX(double x) [member function] cls.add_method('SetX', 'void', [param('double', 'x')]) ## position-allocator.h (module 'mobility'): void ns3::UniformDiscPositionAllocator::SetY(double y) [member function] cls.add_method('SetY', 'void', [param('double', 'y')]) return def register_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_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_Ns3BoxChecker_methods(root_module, cls): ## box.h (module 'mobility'): ns3::BoxChecker::BoxChecker() [constructor] cls.add_constructor([]) ## box.h (module 'mobility'): ns3::BoxChecker::BoxChecker(ns3::BoxChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::BoxChecker const &', 'arg0')]) return def register_Ns3BoxValue_methods(root_module, cls): ## box.h (module 'mobility'): ns3::BoxValue::BoxValue() [constructor] cls.add_constructor([]) ## box.h (module 'mobility'): ns3::BoxValue::BoxValue(ns3::BoxValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::BoxValue const &', 'arg0')]) ## box.h (module 'mobility'): ns3::BoxValue::BoxValue(ns3::Box const & value) [constructor] cls.add_constructor([param('ns3::Box const &', 'value')]) ## box.h (module 'mobility'): ns3::Ptr<ns3::AttributeValue> ns3::BoxValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## box.h (module 'mobility'): bool ns3::BoxValue::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) ## box.h (module 'mobility'): ns3::Box ns3::BoxValue::Get() const [member function] cls.add_method('Get', 'ns3::Box', [], is_const=True) ## box.h (module 'mobility'): std::string ns3::BoxValue::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) ## box.h (module 'mobility'): void ns3::BoxValue::Set(ns3::Box const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Box const &', 'value')]) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_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_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 c1, double c2, double v1, double v2, double r) [member function] cls.add_method('Interpolate', 'double', [param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')], visibility='private', is_virtual=True) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function] cls.add_method('Validate', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EmptyAttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_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_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_Ns3GridPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator::GridPositionAllocator(ns3::GridPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::GridPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator::GridPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::GridPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): double ns3::GridPositionAllocator::GetDeltaX() const [member function] cls.add_method('GetDeltaX', 'double', [], is_const=True) ## position-allocator.h (module 'mobility'): double ns3::GridPositionAllocator::GetDeltaY() const [member function] cls.add_method('GetDeltaY', 'double', [], is_const=True) ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator::LayoutType ns3::GridPositionAllocator::GetLayoutType() const [member function] cls.add_method('GetLayoutType', 'ns3::GridPositionAllocator::LayoutType', [], is_const=True) ## position-allocator.h (module 'mobility'): double ns3::GridPositionAllocator::GetMinX() const [member function] cls.add_method('GetMinX', 'double', [], is_const=True) ## position-allocator.h (module 'mobility'): double ns3::GridPositionAllocator::GetMinY() const [member function] cls.add_method('GetMinY', 'double', [], is_const=True) ## position-allocator.h (module 'mobility'): uint32_t ns3::GridPositionAllocator::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::GridPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::GridPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetDeltaX(double deltaX) [member function] cls.add_method('SetDeltaX', 'void', [param('double', 'deltaX')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetDeltaY(double deltaY) [member function] cls.add_method('SetDeltaY', 'void', [param('double', 'deltaY')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetLayoutType(ns3::GridPositionAllocator::LayoutType layoutType) [member function] cls.add_method('SetLayoutType', 'void', [param('ns3::GridPositionAllocator::LayoutType', 'layoutType')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetMinX(double xMin) [member function] cls.add_method('SetMinX', 'void', [param('double', 'xMin')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetMinY(double yMin) [member function] cls.add_method('SetMinY', 'void', [param('double', 'yMin')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetN(uint32_t n) [member function] cls.add_method('SetN', 'void', [param('uint32_t', 'n')]) 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_Ns3ListPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::ListPositionAllocator::ListPositionAllocator(ns3::ListPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ListPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::ListPositionAllocator::ListPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): void ns3::ListPositionAllocator::Add(ns3::Vector v) [member function] cls.add_method('Add', 'void', [param('ns3::Vector', 'v')]) ## position-allocator.h (module 'mobility'): int64_t ns3::ListPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::ListPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::ListPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=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_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_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<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,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 >, short unsigned int, 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<const ns3::Packet>,short unsigned int,const ns3::Address&,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 >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NetDeviceQueue_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::Ptr<ns3::QueueLimits> ns3::NetDeviceQueue::GetQueueLimits() [member function] cls.add_method('GetQueueLimits', 'ns3::Ptr< ns3::QueueLimits >', []) ## net-device.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function] cls.add_method('IsStopped', 'bool', [], is_const=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyQueuedBytes(uint32_t bytes) [member function] cls.add_method('NotifyQueuedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyTransmittedBytes(uint32_t bytes) [member function] cls.add_method('NotifyTransmittedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::ResetQueueLimits() [member function] cls.add_method('ResetQueueLimits', 'void', []) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetQueueLimits(ns3::Ptr<ns3::QueueLimits> ql) [member function] cls.add_method('SetQueueLimits', 'void', [param('ns3::Ptr< ns3::QueueLimits >', 'ql')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetWakeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function] cls.add_method('Wake', 'void', [], is_virtual=True) return def register_Ns3NetDeviceQueueInterface_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::CreateTxQueues() [member function] cls.add_method('CreateTxQueues', 'void', []) ## net-device.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function] cls.add_method('GetNTxQueues', 'uint8_t', [], is_const=True) ## net-device.h (module 'network'): ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function] cls.add_method('GetSelectQueueCallback', 'ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(uint8_t i) const [member function] cls.add_method('GetTxQueue', 'ns3::Ptr< ns3::NetDeviceQueue >', [param('uint8_t', 'i')], is_const=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetSelectQueueCallback', 'void', [param('ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function] cls.add_method('SetTxQueuesN', 'void', [param('uint8_t', 'numTxQueues')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): ns3::Time ns3::Node::GetLocalTime() const [member function] cls.add_method('GetLocalTime', 'ns3::Time', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable] cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function] cls.add_method('GetVariance', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_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_Ns3QueueItem_methods(root_module, cls): cls.add_output_stream_operator() ## net-device.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')]) ## net-device.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## net-device.h (module 'network'): uint32_t ns3::QueueItem::GetPacketSize() const [member function] cls.add_method('GetPacketSize', 'uint32_t', [], is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function] cls.add_method('GetUint8Value', 'bool', [param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')], is_const=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) return def register_Ns3RandomDirection2dMobilityModel_methods(root_module, cls): ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::RandomDirection2dMobilityModel::RandomDirection2dMobilityModel(ns3::RandomDirection2dMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomDirection2dMobilityModel const &', 'arg0')]) ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::RandomDirection2dMobilityModel::RandomDirection2dMobilityModel() [constructor] cls.add_constructor([]) ## random-direction-2d-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::RandomDirection2dMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-direction-2d-mobility-model.h (module 'mobility'): int64_t ns3::RandomDirection2dMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): void ns3::RandomDirection2dMobilityModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomDirection2dMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomDirection2dMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): void ns3::RandomDirection2dMobilityModel::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): void ns3::RandomDirection2dMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3RandomWalk2dMobilityModel_methods(root_module, cls): ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::RandomWalk2dMobilityModel::RandomWalk2dMobilityModel() [constructor] cls.add_constructor([]) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::RandomWalk2dMobilityModel::RandomWalk2dMobilityModel(ns3::RandomWalk2dMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomWalk2dMobilityModel const &', 'arg0')]) ## random-walk-2d-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::RandomWalk2dMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-walk-2d-mobility-model.h (module 'mobility'): int64_t ns3::RandomWalk2dMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): void ns3::RandomWalk2dMobilityModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomWalk2dMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomWalk2dMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): void ns3::RandomWalk2dMobilityModel::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): void ns3::RandomWalk2dMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3RandomWaypointMobilityModel_methods(root_module, cls): ## random-waypoint-mobility-model.h (module 'mobility'): ns3::RandomWaypointMobilityModel::RandomWaypointMobilityModel() [constructor] cls.add_constructor([]) ## random-waypoint-mobility-model.h (module 'mobility'): ns3::RandomWaypointMobilityModel::RandomWaypointMobilityModel(ns3::RandomWaypointMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomWaypointMobilityModel const &', 'arg0')]) ## random-waypoint-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::RandomWaypointMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-waypoint-mobility-model.h (module 'mobility'): void ns3::RandomWaypointMobilityModel::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## random-waypoint-mobility-model.h (module 'mobility'): int64_t ns3::RandomWaypointMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## random-waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomWaypointMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomWaypointMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-waypoint-mobility-model.h (module 'mobility'): void ns3::RandomWaypointMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3RectangleChecker_methods(root_module, cls): ## rectangle.h (module 'mobility'): ns3::RectangleChecker::RectangleChecker() [constructor] cls.add_constructor([]) ## rectangle.h (module 'mobility'): ns3::RectangleChecker::RectangleChecker(ns3::RectangleChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::RectangleChecker const &', 'arg0')]) return def register_Ns3RectangleValue_methods(root_module, cls): ## rectangle.h (module 'mobility'): ns3::RectangleValue::RectangleValue() [constructor] cls.add_constructor([]) ## rectangle.h (module 'mobility'): ns3::RectangleValue::RectangleValue(ns3::RectangleValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::RectangleValue const &', 'arg0')]) ## rectangle.h (module 'mobility'): ns3::RectangleValue::RectangleValue(ns3::Rectangle const & value) [constructor] cls.add_constructor([param('ns3::Rectangle const &', 'value')]) ## rectangle.h (module 'mobility'): ns3::Ptr<ns3::AttributeValue> ns3::RectangleValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## rectangle.h (module 'mobility'): bool ns3::RectangleValue::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) ## rectangle.h (module 'mobility'): ns3::Rectangle ns3::RectangleValue::Get() const [member function] cls.add_method('Get', 'ns3::Rectangle', [], is_const=True) ## rectangle.h (module 'mobility'): std::string ns3::RectangleValue::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) ## rectangle.h (module 'mobility'): void ns3::RectangleValue::Set(ns3::Rectangle const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Rectangle const &', 'value')]) return def register_Ns3SteadyStateRandomWaypointMobilityModel_methods(root_module, cls): ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::SteadyStateRandomWaypointMobilityModel::SteadyStateRandomWaypointMobilityModel(ns3::SteadyStateRandomWaypointMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SteadyStateRandomWaypointMobilityModel const &', 'arg0')]) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::SteadyStateRandomWaypointMobilityModel::SteadyStateRandomWaypointMobilityModel() [constructor] cls.add_constructor([]) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::SteadyStateRandomWaypointMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): void ns3::SteadyStateRandomWaypointMobilityModel::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): int64_t ns3::SteadyStateRandomWaypointMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::SteadyStateRandomWaypointMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::SteadyStateRandomWaypointMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): void ns3::SteadyStateRandomWaypointMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', 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_Ns3WaypointChecker_methods(root_module, cls): ## waypoint.h (module 'mobility'): ns3::WaypointChecker::WaypointChecker() [constructor] cls.add_constructor([]) ## waypoint.h (module 'mobility'): ns3::WaypointChecker::WaypointChecker(ns3::WaypointChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::WaypointChecker const &', 'arg0')]) return def register_Ns3WaypointMobilityModel_methods(root_module, cls): ## waypoint-mobility-model.h (module 'mobility'): ns3::WaypointMobilityModel::WaypointMobilityModel(ns3::WaypointMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::WaypointMobilityModel const &', 'arg0')]) ## waypoint-mobility-model.h (module 'mobility'): ns3::WaypointMobilityModel::WaypointMobilityModel() [constructor] cls.add_constructor([]) ## waypoint-mobility-model.h (module 'mobility'): void ns3::WaypointMobilityModel::AddWaypoint(ns3::Waypoint const & waypoint) [member function] cls.add_method('AddWaypoint', 'void', [param('ns3::Waypoint const &', 'waypoint')]) ## waypoint-mobility-model.h (module 'mobility'): void ns3::WaypointMobilityModel::EndMobility() [member function] cls.add_method('EndMobility', 'void', []) ## waypoint-mobility-model.h (module 'mobility'): ns3::Waypoint ns3::WaypointMobilityModel::GetNextWaypoint() const [member function] cls.add_method('GetNextWaypoint', 'ns3::Waypoint', [], is_const=True) ## waypoint-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::WaypointMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## waypoint-mobility-model.h (module 'mobility'): uint32_t ns3::WaypointMobilityModel::WaypointsLeft() const [member function] cls.add_method('WaypointsLeft', 'uint32_t', [], is_const=True) ## waypoint-mobility-model.h (module 'mobility'): void ns3::WaypointMobilityModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::WaypointMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::WaypointMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## waypoint-mobility-model.h (module 'mobility'): void ns3::WaypointMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3WaypointValue_methods(root_module, cls): ## waypoint.h (module 'mobility'): ns3::WaypointValue::WaypointValue() [constructor] cls.add_constructor([]) ## waypoint.h (module 'mobility'): ns3::WaypointValue::WaypointValue(ns3::WaypointValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::WaypointValue const &', 'arg0')]) ## waypoint.h (module 'mobility'): ns3::WaypointValue::WaypointValue(ns3::Waypoint const & value) [constructor] cls.add_constructor([param('ns3::Waypoint const &', 'value')]) ## waypoint.h (module 'mobility'): ns3::Ptr<ns3::AttributeValue> ns3::WaypointValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## waypoint.h (module 'mobility'): bool ns3::WaypointValue::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) ## waypoint.h (module 'mobility'): ns3::Waypoint ns3::WaypointValue::Get() const [member function] cls.add_method('Get', 'ns3::Waypoint', [], is_const=True) ## waypoint.h (module 'mobility'): std::string ns3::WaypointValue::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) ## waypoint.h (module 'mobility'): void ns3::WaypointValue::Set(ns3::Waypoint const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Waypoint 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_Ns3ConstantAccelerationMobilityModel_methods(root_module, cls): ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::ConstantAccelerationMobilityModel::ConstantAccelerationMobilityModel(ns3::ConstantAccelerationMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantAccelerationMobilityModel const &', 'arg0')]) ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::ConstantAccelerationMobilityModel::ConstantAccelerationMobilityModel() [constructor] cls.add_constructor([]) ## constant-acceleration-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::ConstantAccelerationMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## constant-acceleration-mobility-model.h (module 'mobility'): void ns3::ConstantAccelerationMobilityModel::SetVelocityAndAcceleration(ns3::Vector const & velocity, ns3::Vector const & acceleration) [member function] cls.add_method('SetVelocityAndAcceleration', 'void', [param('ns3::Vector const &', 'velocity'), param('ns3::Vector const &', 'acceleration')]) ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantAccelerationMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantAccelerationMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-acceleration-mobility-model.h (module 'mobility'): void ns3::ConstantAccelerationMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3ConstantPositionMobilityModel_methods(root_module, cls): ## constant-position-mobility-model.h (module 'mobility'): ns3::ConstantPositionMobilityModel::ConstantPositionMobilityModel(ns3::ConstantPositionMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantPositionMobilityModel const &', 'arg0')]) ## constant-position-mobility-model.h (module 'mobility'): ns3::ConstantPositionMobilityModel::ConstantPositionMobilityModel() [constructor] cls.add_constructor([]) ## constant-position-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::ConstantPositionMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## constant-position-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantPositionMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-position-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantPositionMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-position-mobility-model.h (module 'mobility'): void ns3::ConstantPositionMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3ConstantVelocityMobilityModel_methods(root_module, cls): ## constant-velocity-mobility-model.h (module 'mobility'): ns3::ConstantVelocityMobilityModel::ConstantVelocityMobilityModel(ns3::ConstantVelocityMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantVelocityMobilityModel const &', 'arg0')]) ## constant-velocity-mobility-model.h (module 'mobility'): ns3::ConstantVelocityMobilityModel::ConstantVelocityMobilityModel() [constructor] cls.add_constructor([]) ## constant-velocity-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::ConstantVelocityMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## constant-velocity-mobility-model.h (module 'mobility'): void ns3::ConstantVelocityMobilityModel::SetVelocity(ns3::Vector const & speed) [member function] cls.add_method('SetVelocity', 'void', [param('ns3::Vector const &', 'speed')]) ## constant-velocity-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantVelocityMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-velocity-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantVelocityMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-velocity-mobility-model.h (module 'mobility'): void ns3::ConstantVelocityMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3GaussMarkovMobilityModel_methods(root_module, cls): ## gauss-markov-mobility-model.h (module 'mobility'): ns3::GaussMarkovMobilityModel::GaussMarkovMobilityModel(ns3::GaussMarkovMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::GaussMarkovMobilityModel const &', 'arg0')]) ## gauss-markov-mobility-model.h (module 'mobility'): ns3::GaussMarkovMobilityModel::GaussMarkovMobilityModel() [constructor] cls.add_constructor([]) ## gauss-markov-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::GaussMarkovMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## gauss-markov-mobility-model.h (module 'mobility'): int64_t ns3::GaussMarkovMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## gauss-markov-mobility-model.h (module 'mobility'): void ns3::GaussMarkovMobilityModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## gauss-markov-mobility-model.h (module 'mobility'): ns3::Vector ns3::GaussMarkovMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## gauss-markov-mobility-model.h (module 'mobility'): ns3::Vector ns3::GaussMarkovMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## gauss-markov-mobility-model.h (module 'mobility'): void ns3::GaussMarkovMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3HierarchicalMobilityModel_methods(root_module, cls): ## hierarchical-mobility-model.h (module 'mobility'): ns3::HierarchicalMobilityModel::HierarchicalMobilityModel(ns3::HierarchicalMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::HierarchicalMobilityModel const &', 'arg0')]) ## hierarchical-mobility-model.h (module 'mobility'): ns3::HierarchicalMobilityModel::HierarchicalMobilityModel() [constructor] cls.add_constructor([]) ## hierarchical-mobility-model.h (module 'mobility'): ns3::Ptr<ns3::MobilityModel> ns3::HierarchicalMobilityModel::GetChild() const [member function] cls.add_method('GetChild', 'ns3::Ptr< ns3::MobilityModel >', [], is_const=True) ## hierarchical-mobility-model.h (module 'mobility'): ns3::Ptr<ns3::MobilityModel> ns3::HierarchicalMobilityModel::GetParent() const [member function] cls.add_method('GetParent', 'ns3::Ptr< ns3::MobilityModel >', [], is_const=True) ## hierarchical-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::HierarchicalMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## hierarchical-mobility-model.h (module 'mobility'): void ns3::HierarchicalMobilityModel::SetChild(ns3::Ptr<ns3::MobilityModel> model) [member function] cls.add_method('SetChild', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'model')]) ## hierarchical-mobility-model.h (module 'mobility'): void ns3::HierarchicalMobilityModel::SetParent(ns3::Ptr<ns3::MobilityModel> model) [member function] cls.add_method('SetParent', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'model')]) ## hierarchical-mobility-model.h (module 'mobility'): ns3::Vector ns3::HierarchicalMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## hierarchical-mobility-model.h (module 'mobility'): ns3::Vector ns3::HierarchicalMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## hierarchical-mobility-model.h (module 'mobility'): void ns3::HierarchicalMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], 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 ## box.h (module 'mobility'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeBoxChecker() [free function] module.add_function('MakeBoxChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## rectangle.h (module 'mobility'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeRectangleChecker() [free function] module.add_function('MakeRectangleChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## waypoint.h (module 'mobility'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeWaypointChecker() [free function] module.add_function('MakeWaypointChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def 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
gvir/dailyreader
venv/Lib/site-packages/pip/_vendor/distlib/_backport/shutil.py
1002
25650
# -*- coding: utf-8 -*- # # Copyright (C) 2012 The Python Software Foundation. # See LICENSE.txt and CONTRIBUTORS.txt. # """Utility functions for copying and archiving files and directory trees. XXX The functions here don't copy the resource fork or other metadata on Mac. """ import os import sys import stat from os.path import abspath import fnmatch import collections import errno from . import tarfile try: import bz2 _BZ2_SUPPORTED = True except ImportError: _BZ2_SUPPORTED = False try: from pwd import getpwnam except ImportError: getpwnam = None try: from grp import getgrnam except ImportError: getgrnam = None __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2", "copytree", "move", "rmtree", "Error", "SpecialFileError", "ExecError", "make_archive", "get_archive_formats", "register_archive_format", "unregister_archive_format", "get_unpack_formats", "register_unpack_format", "unregister_unpack_format", "unpack_archive", "ignore_patterns"] class Error(EnvironmentError): pass class SpecialFileError(EnvironmentError): """Raised when trying to do a kind of operation (e.g. copying) which is not supported on a special file (e.g. a named pipe)""" class ExecError(EnvironmentError): """Raised when a command could not be executed""" class ReadError(EnvironmentError): """Raised when an archive cannot be read""" class RegistryError(Exception): """Raised when a registery operation with the archiving and unpacking registeries fails""" try: WindowsError except NameError: WindowsError = None def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf) def _samefile(src, dst): # Macintosh, Unix. if hasattr(os.path, 'samefile'): try: return os.path.samefile(src, dst) except OSError: return False # All other platforms: check for same pathname. return (os.path.normcase(os.path.abspath(src)) == os.path.normcase(os.path.abspath(dst))) def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass else: # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) with open(src, 'rb') as fsrc: with open(dst, 'wb') as fdst: copyfileobj(fsrc, fdst) def copymode(src, dst): """Copy mode bits from src to dst""" if hasattr(os, 'chmod'): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dst, mode) def copystat(src, dst): """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): try: os.chflags(dst, st.st_flags) except OSError as why: if (not hasattr(errno, 'EOPNOTSUPP') or why.errno != errno.EOPNOTSUPP): raise def copy(src, dst): """Copy data and mode bits ("cp src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copymode(src, dst) def copy2(src, dst): """Copy data and all stat info ("cp -p src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copystat(src, dst) def ignore_patterns(*patterns): """Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns that are used to exclude files""" def _ignore_patterns(path, names): ignored_names = [] for pattern in patterns: ignored_names.extend(fnmatch.filter(names, pattern)) return set(ignored_names) return _ignore_patterns def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False): """Recursively copy a directory tree. The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. If the file pointed by the symlink doesn't exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this has no effect on platforms that don't support os.symlink. The optional ignore argument is a callable. If given, it is called with the `src` parameter, which is the directory being visited by copytree(), and `names` which is the list of `src` contents, as returned by os.listdir(): callable(src, names) -> ignored_names Since copytree() is called recursively, the callable will be called once for each directory that is copied. It returns a list of names relative to the `src` directory that should not be copied. The optional copy_function argument is a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used. """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() os.makedirs(dst) errors = [] for name in names: if name in ignored_names: continue srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if os.path.islink(srcname): linkto = os.readlink(srcname) if symlinks: os.symlink(linkto, dstname) else: # ignore dangling symlink if the flag is on if not os.path.exists(linkto) and ignore_dangling_symlinks: continue # otherwise let the copy occurs. copy2 will raise an error copy_function(srcname, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks, ignore, copy_function) else: # Will raise a SpecialFileError for unsupported file types copy_function(srcname, dstname) # catch the Error from the recursive copytree so that we can # continue with other files except Error as err: errors.extend(err.args[0]) except EnvironmentError as why: errors.append((srcname, dstname, str(why))) try: copystat(src, dst) except OSError as why: if WindowsError is not None and isinstance(why, WindowsError): # Copying file access times may fail on Windows pass else: errors.extend((src, dst, str(why))) if errors: raise Error(errors) def rmtree(path, ignore_errors=False, onerror=None): """Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised. """ if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise try: if os.path.islink(path): # symlinks to directories are forbidden, see bug #1669 raise OSError("Cannot call rmtree on a symbolic link") except OSError: onerror(os.path.islink, path, sys.exc_info()) # can't continue even if onerror hook returns return names = [] try: names = os.listdir(path) except os.error: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) try: mode = os.lstat(fullname).st_mode except os.error: mode = 0 if stat.S_ISDIR(mode): rmtree(fullname, ignore_errors, onerror) else: try: os.remove(fullname) except os.error: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) except os.error: onerror(os.rmdir, path, sys.exc_info()) def _basename(path): # A basename() variant which first strips the trailing slash, if present. # Thus we always get the last component of the path, even for directories. return os.path.basename(path.rstrip(os.path.sep)) def move(src, dst): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. """ real_dst = dst if os.path.isdir(dst): if _samefile(src, dst): # We might be on a case insensitive filesystem, # perform the rename anyway. os.rename(src, dst) return real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error("Destination path '%s' already exists" % real_dst) try: os.rename(src, real_dst) except OSError: if os.path.isdir(src): if _destinsrc(src, dst): raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst)) copytree(src, real_dst, symlinks=True) rmtree(src) else: copy2(src, real_dst) os.unlink(src) def _destinsrc(src, dst): src = abspath(src) dst = abspath(dst) if not src.endswith(os.path.sep): src += os.path.sep if not dst.endswith(os.path.sep): dst += os.path.sep return dst.startswith(src) def _get_gid(name): """Returns a gid, given a group name.""" if getgrnam is None or name is None: return None try: result = getgrnam(name) except KeyError: result = None if result is not None: return result[2] return None def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", or None. 'owner' and 'group' can be used to define an owner and a group for the archive that is being built. If not provided, the current owner and group will be used. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", or ".bz2"). Returns the output filename. """ tar_compression = {'gzip': 'gz', None: ''} compress_ext = {'gzip': '.gz'} if _BZ2_SUPPORTED: tar_compression['bzip2'] = 'bz2' compress_ext['bzip2'] = '.bz2' # flags for compression program, each element of list will be an argument if compress is not None and compress not in compress_ext: raise ValueError("bad value for 'compress', or compression format not " "supported : {0}".format(compress)) archive_name = base_name + '.tar' + compress_ext.get(compress, '') archive_dir = os.path.dirname(archive_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # creating the tarball if logger is not None: logger.info('Creating tar archive') uid = _get_uid(owner) gid = _get_gid(group) def _set_uid_gid(tarinfo): if gid is not None: tarinfo.gid = gid tarinfo.gname = group if uid is not None: tarinfo.uid = uid tarinfo.uname = owner return tarinfo if not dry_run: tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress]) try: tar.add(base_dir, filter=_set_uid_gid) finally: tar.close() return archive_name def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False): # XXX see if we want to keep an external call here if verbose: zipoptions = "-r" else: zipoptions = "-rq" from distutils.errors import DistutilsExecError from distutils.spawn import spawn try: spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run) except DistutilsExecError: # XXX really should distinguish between "couldn't find # external 'zip' command" and "zip failed". raise ExecError("unable to create zip file '%s': " "could neither import the 'zipfile' module nor " "find a standalone zip utility") % zip_filename def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file. """ zip_filename = base_name + ".zip" archive_dir = os.path.dirname(base_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # If zipfile module is not available, try spawning an external 'zip' # command. try: import zipfile except ImportError: zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(base_dir): for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) if logger is not None: logger.info("adding '%s'", path) zip.close() return zip_filename _ARCHIVE_FORMATS = { 'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"), 'bztar': (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"), 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"), 'zip': (_make_zipfile, [], "ZIP file"), } if _BZ2_SUPPORTED: _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file") def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats def register_archive_format(name, function, extra_args=None, description=''): """Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_archive_formats() function. """ if extra_args is None: extra_args = [] if not isinstance(function, collections.Callable): raise TypeError('The %s object is not callable' % function) if not isinstance(extra_args, (tuple, list)): raise TypeError('extra_args needs to be a sequence') for element in extra_args: if not isinstance(element, (tuple, list)) or len(element) !=2: raise TypeError('extra_args elements are : (arg_name, value)') _ARCHIVE_FORMATS[name] = (function, extra_args, description) def unregister_archive_format(name): del _ARCHIVE_FORMATS[name] def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group. """ save_cwd = os.getcwd() if root_dir is not None: if logger is not None: logger.debug("changing into '%s'", root_dir) base_name = os.path.abspath(base_name) if not dry_run: os.chdir(root_dir) if base_dir is None: base_dir = os.curdir kwargs = {'dry_run': dry_run, 'logger': logger} try: format_info = _ARCHIVE_FORMATS[format] except KeyError: raise ValueError("unknown archive format '%s'" % format) func = format_info[0] for arg, val in format_info[1]: kwargs[arg] = val if format != 'zip': kwargs['owner'] = owner kwargs['group'] = group try: filename = func(base_name, base_dir, **kwargs) finally: if root_dir is not None: if logger is not None: logger.debug("changing back to '%s'", save_cwd) os.chdir(save_cwd) return filename def get_unpack_formats(): """Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description) """ formats = [(name, info[0], info[3]) for name, info in _UNPACK_FORMATS.items()] formats.sort() return formats def _check_unpack_options(extensions, function, extra_args): """Checks what gets registered as an unpacker.""" # first make sure no other unpacker is registered for this extension existing_extensions = {} for name, info in _UNPACK_FORMATS.items(): for ext in info[0]: existing_extensions[ext] = name for extension in extensions: if extension in existing_extensions: msg = '%s is already registered for "%s"' raise RegistryError(msg % (extension, existing_extensions[extension])) if not isinstance(function, collections.Callable): raise TypeError('The registered function must be a callable') def register_unpack_format(name, extensions, function, extra_args=None, description=''): """Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unpack archives. The callable will receive archives to unpack. If it's unable to handle an archive, it needs to raise a ReadError exception. If provided, `extra_args` is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_unpack_formats() function. """ if extra_args is None: extra_args = [] _check_unpack_options(extensions, function, extra_args) _UNPACK_FORMATS[name] = extensions, function, extra_args, description def unregister_unpack_format(name): """Removes the pack format from the registery.""" del _UNPACK_FORMATS[name] def _ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname) def _unpack_zipfile(filename, extract_dir): """Unpack zip `filename` to `extract_dir` """ try: import zipfile except ImportError: raise ReadError('zlib not supported, cannot unpack this archive.') if not zipfile.is_zipfile(filename): raise ReadError("%s is not a zip file" % filename) zip = zipfile.ZipFile(filename) try: for info in zip.infolist(): name = info.filename # don't extract absolute paths or ones with .. in them if name.startswith('/') or '..' in name: continue target = os.path.join(extract_dir, *name.split('/')) if not target: continue _ensure_directory(target) if not name.endswith('/'): # file data = zip.read(info.filename) f = open(target, 'wb') try: f.write(data) finally: f.close() del data finally: zip.close() def _unpack_tarfile(filename, extract_dir): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise ReadError( "%s is not a compressed or uncompressed tar file" % filename) try: tarobj.extractall(extract_dir) finally: tarobj.close() _UNPACK_FORMATS = { 'gztar': (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file"), 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"), 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file") } if _BZ2_SUPPORTED: _UNPACK_FORMATS['bztar'] = (['.bz2'], _unpack_tarfile, [], "bzip2'ed tar-file") def _find_unpack_format(filename): for name, info in _UNPACK_FORMATS.items(): for extension in info[0]: if filename.endswith(extension): return name return None def unpack_archive(filename, extract_dir=None, format=None): """Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", or "gztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. """ if extract_dir is None: extract_dir = os.getcwd() if format is not None: try: format_info = _UNPACK_FORMATS[format] except KeyError: raise ValueError("Unknown unpack format '{0}'".format(format)) func = format_info[1] func(filename, extract_dir, **dict(format_info[2])) else: # we need to look at the registered unpackers supported extensions format = _find_unpack_format(filename) if format is None: raise ReadError("Unknown archive format '{0}'".format(filename)) func = _UNPACK_FORMATS[format][1] kwargs = dict(_UNPACK_FORMATS[format][2]) func(filename, extract_dir, **kwargs)
mit
TeamRegular/android_kernel_lge_g4stylus
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Util.py
12527
1935
# Util.py - Python extension for perf script, miscellaneous utility code # # Copyright (C) 2010 by Tom Zanussi <[email protected]> # # This software may be distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. import errno, os FUTEX_WAIT = 0 FUTEX_WAKE = 1 FUTEX_PRIVATE_FLAG = 128 FUTEX_CLOCK_REALTIME = 256 FUTEX_CMD_MASK = ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME) NSECS_PER_SEC = 1000000000 def avg(total, n): return total / n def nsecs(secs, nsecs): return secs * NSECS_PER_SEC + nsecs def nsecs_secs(nsecs): return nsecs / NSECS_PER_SEC def nsecs_nsecs(nsecs): return nsecs % NSECS_PER_SEC def nsecs_str(nsecs): str = "%5u.%09u" % (nsecs_secs(nsecs), nsecs_nsecs(nsecs)), return str def add_stats(dict, key, value): if not dict.has_key(key): dict[key] = (value, value, value, 1) else: min, max, avg, count = dict[key] if value < min: min = value if value > max: max = value avg = (avg + value) / 2 dict[key] = (min, max, avg, count + 1) def clear_term(): print("\x1b[H\x1b[2J") audit_package_warned = False try: import audit machine_to_id = { 'x86_64': audit.MACH_86_64, 'alpha' : audit.MACH_ALPHA, 'ia64' : audit.MACH_IA64, 'ppc' : audit.MACH_PPC, 'ppc64' : audit.MACH_PPC64, 's390' : audit.MACH_S390, 's390x' : audit.MACH_S390X, 'i386' : audit.MACH_X86, 'i586' : audit.MACH_X86, 'i686' : audit.MACH_X86, } try: machine_to_id['armeb'] = audit.MACH_ARMEB except: pass machine_id = machine_to_id[os.uname()[4]] except: if not audit_package_warned: audit_package_warned = True print "Install the audit-libs-python package to get syscall names" def syscall_name(id): try: return audit.audit_syscall_to_name(id, machine_id) except: return str(id) def strerror(nr): try: return errno.errorcode[abs(nr)] except: return "Unknown %d errno" % nr
gpl-2.0
2013Commons/hue
desktop/libs/hadoop/src/hadoop/yarn/clients.py
1
2102
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import threading import time import urlparse import heapq from desktop.lib.rest.http_client import HttpClient from hadoop import cluster LOG = logging.getLogger(__name__) MAX_HEAP_SIZE = 20 _log_client_heap = [] _log_client_lock = threading.Lock() def get_log_client(log_link): global _log_client_queue global MAX_HEAP_SIZE _log_client_lock.acquire() try: components = urlparse.urlsplit(log_link) base_url = '%(scheme)s://%(netloc)s' % { 'scheme': components[0], 'netloc': components[1] } # Takes on form (epoch time, client object) # Least Recently Used algorithm. client_tuple = next((tup for tup in _log_client_heap if tup[1].base_url == base_url), None) if client_tuple is None: client = HttpClient(base_url, LOG) yarn_cluster = cluster.get_cluster_conf_for_job_submission() if yarn_cluster.SECURITY_ENABLED.get(): client.set_kerberos_auth() else: _log_client_heap.remove(client_tuple) client = client_tuple[1] new_client_tuple = (time.time(), client) if len(_log_client_heap) >= MAX_HEAP_SIZE: heapq.heapreplace(_log_client_heap, new_client_tuple) else: heapq.heappush(_log_client_heap, new_client_tuple) return client finally: _log_client_lock.release()
apache-2.0
sassoftware/conary
conary/repository/netrepos/reposlog.py
2
3924
# # Copyright (c) SAS Institute 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 cPickle, mmap, os, struct, time from conary.repository import calllog from conary.lib import log class RepositoryCallLogEntry: def __init__(self, info): self.revision = info[0] if (self.revision == 1): self.entKey = 'unknown' (self.serverName, self.timeStamp, self.remoteIp, (self.user, self.entClass), self.methodName, self.args, self.exceptionStr) = info[1:] elif (self.revision == 2): (self.serverName, self.timeStamp, self.remoteIp, (self.user, self.entClass, self.entKey), self.methodName, self.args, self.exceptionStr) = info[1:] elif (self.revision == 3): (self.serverName, self.timeStamp, self.remoteIp, (self.user, self.entitlements), self.methodName, self.args, self.exceptionStr) = info[1:] elif (self.revision == 4): (self.serverName, self.timeStamp, self.remoteIp, (self.user, self.entitlements), self.methodName, self.args, self.kwArgs, self.exceptionStr) = info[1:] elif (self.revision == 5): (self.serverName, self.timeStamp, self.remoteIp, (self.user, self.entitlements), self.methodName, self.args, self.kwArgs, self.exceptionStr, self.latency) = info[1:] elif (self.revision == 6): (self.serverName, self.timeStamp, self.remoteIp, (self.user, self.entitlements), self.methodName, self.args, self.kwArgs, self.exceptionStr, self.latency, self.systemId) = info[1:] else: assert(0) class RepositoryCallLogger(calllog.AbstractCallLogger): EntryClass = RepositoryCallLogEntry logFormatRevision = 6 def __init__(self, logPath, serverNameList, readOnly = False): self.serverNameList = serverNameList calllog.AbstractCallLogger.__init__(self, logPath, readOnly = readOnly) def log(self, remoteIp, authToken, methodName, args, kwArgs = {}, exception = None, latency = None, systemId = None): # lazy re-open the log file in case it was rotated from underneath us self.reopen() if exception: exception = str(exception) (user, entitlements) = authToken[0], authToken[2] logStr = cPickle.dumps((self.logFormatRevision, self.serverNameList, time.time(), remoteIp, (user, entitlements), methodName, args, kwArgs, exception, latency, systemId)) try: self.fobj.write(struct.pack("!I", len(logStr)) + logStr) self.fobj.flush() except IOError, e: log.warning("'%s' while logging call from (%s,%s) to %s\n", str(e), remoteIp, user, methodName) def __iter__(self): fd = os.open(self.path, os.O_RDONLY) size = os.fstat(fd).st_size if size == 0: raise StopIteration map = mmap.mmap(fd, size, access = mmap.ACCESS_READ) i = 0 while i < size: length = struct.unpack("!I", map[i: i + 4])[0] i += 4 yield self.EntryClass(cPickle.loads(map[i:i + length])) i += length os.close(fd)
apache-2.0
tectronics/mythbox
resources/lib/twisted/twisted/python/shortcut.py
81
2455
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """Creation of Windows shortcuts. Requires win32all. """ from win32com.shell import shell import pythoncom import os def open(filename): """Open an existing shortcut for reading. @return: The shortcut object @rtype: Shortcut """ sc=Shortcut() sc.load(filename) return sc class Shortcut: """A shortcut on Win32. >>> sc=Shortcut(path, arguments, description, workingdir, iconpath, iconidx) @param path: Location of the target @param arguments: If path points to an executable, optional arguments to pass @param description: Human-readable decription of target @param workingdir: Directory from which target is launched @param iconpath: Filename that contains an icon for the shortcut @param iconidx: If iconpath is set, optional index of the icon desired """ def __init__(self, path=None, arguments=None, description=None, workingdir=None, iconpath=None, iconidx=0): self._base = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink ) data = map(None, ['"%s"' % os.path.abspath(path), arguments, description, os.path.abspath(workingdir), os.path.abspath(iconpath)], ("SetPath", "SetArguments", "SetDescription", "SetWorkingDirectory") ) for value, function in data: if value and function: # call function on each non-null value getattr(self, function)(value) if iconpath: self.SetIconLocation(iconpath, iconidx) def load( self, filename ): """Read a shortcut file from disk.""" self._base.QueryInterface(pythoncom.IID_IPersistFile).Load(filename) def save( self, filename ): """Write the shortcut to disk. The file should be named something.lnk. """ self._base.QueryInterface(pythoncom.IID_IPersistFile).Save(filename, 0) def __getattr__( self, name ): if name != "_base": return getattr(self._base, name) raise AttributeError, "%s instance has no attribute %s" % \ (self.__class__.__name__, name)
gpl-2.0
endlessm/chromium-browser
third_party/catapult/tracing/tracing/mre/threaded_work_queue_unittest.py
4
1078
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from tracing.mre import threaded_work_queue class ThreadedWorkQueueTests(unittest.TestCase): def testSingleThreaded(self): wq = threaded_work_queue.ThreadedWorkQueue(num_threads=1) self._RunSimpleDecrementingTest(wq) def testMultiThreaded(self): wq = threaded_work_queue.ThreadedWorkQueue(num_threads=4) self._RunSimpleDecrementingTest(wq) def testSingleThreadedWithException(self): def Ex(): raise Exception("abort") wq = threaded_work_queue.ThreadedWorkQueue(num_threads=1) wq.PostAnyThreadTask(Ex) res = wq.Run() self.assertEquals(res, None) def _RunSimpleDecrementingTest(self, wq): remaining = [10] def Decrement(): remaining[0] -= 1 if remaining[0]: wq.PostMainThreadTask(Done) def Done(): wq.Stop(314) wq.PostAnyThreadTask(Decrement) res = wq.Run() self.assertEquals(res, 314)
bsd-3-clause
geometrybase/gensim
gensim/summarization/summarizer.py
33
7396
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html import logging from gensim.summarization.pagerank_weighted import pagerank_weighted as _pagerank from gensim.summarization.textcleaner import clean_text_by_sentences as _clean_text_by_sentences from gensim.summarization.commons import build_graph as _build_graph from gensim.summarization.commons import remove_unreachable_nodes as _remove_unreachable_nodes from gensim.summarization.bm25 import get_bm25_weights as _bm25_weights from gensim.corpora import Dictionary from scipy.sparse import csr_matrix from math import log10 as _log10 from six.moves import xrange INPUT_MIN_LENGTH = 10 logger = logging.getLogger(__name__) def _set_graph_edge_weights(graph): documents = graph.nodes() weights = _bm25_weights(documents) for i in xrange(len(documents)): for j in xrange(len(documents)): if i == j: continue sentence_1 = documents[i] sentence_2 = documents[j] edge_1 = (sentence_1, sentence_2) edge_2 = (sentence_2, sentence_1) if not graph.has_edge(edge_1): graph.add_edge(edge_1, weights[i][j]) if not graph.has_edge(edge_2): graph.add_edge(edge_2, weights[j][i]) # Handles the case in which all similarities are zero. # The resultant summary will consist of random sentences. if all(graph.edge_weight(edge) == 0 for edge in graph.edges()): _create_valid_graph(graph) def _create_valid_graph(graph): nodes = graph.nodes() for i in xrange(len(nodes)): for j in xrange(len(nodes)): if i == j: continue edge = (nodes[i], nodes[j]) if graph.has_edge(edge): graph.del_edge(edge) graph.add_edge(edge, 1) def _get_doc_length(doc): return sum([item[1] for item in doc]) def _get_similarity(doc1, doc2, vec1, vec2): numerator = vec1.dot(vec2.transpose()).toarray()[0][0] length_1 = _get_doc_length(doc1) length_2 = _get_doc_length(doc2) denominator = _log10(length_1) + _log10(length_2) if length_1 > 0 and length_2 > 0 else 0 return numerator / denominator if denominator != 0 else 0 def _build_corpus(sentences): split_tokens = [sentence.token.split() for sentence in sentences] dictionary = Dictionary(split_tokens) return [dictionary.doc2bow(token) for token in split_tokens] def _get_important_sentences(sentences, corpus, important_docs): hashable_corpus = _build_hasheable_corpus(corpus) sentences_by_corpus = dict(zip(hashable_corpus, sentences)) return [sentences_by_corpus[tuple(important_doc)] for important_doc in important_docs] def _get_sentences_with_word_count(sentences, word_count): """ Given a list of sentences, returns a list of sentences with a total word count similar to the word count provided.""" length = 0 selected_sentences = [] # Loops until the word count is reached. for sentence in sentences: words_in_sentence = len(sentence.text.split()) # Checks if the inclusion of the sentence gives a better approximation # to the word parameter. if abs(word_count - length - words_in_sentence) > abs(word_count - length): return selected_sentences selected_sentences.append(sentence) length += words_in_sentence return selected_sentences def _extract_important_sentences(sentences, corpus, important_docs, word_count): important_sentences = _get_important_sentences(sentences, corpus, important_docs) # If no "word_count" option is provided, the number of sentences is # reduced by the provided ratio. Else, the ratio is ignored. return important_sentences if word_count is None else _get_sentences_with_word_count(important_sentences, word_count) def _format_results(extracted_sentences, split): if split: return [sentence.text for sentence in extracted_sentences] return "\n".join([sentence.text for sentence in extracted_sentences]) def _build_hasheable_corpus(corpus): return [tuple(doc) for doc in corpus] def summarize_corpus(corpus, ratio=0.2): """ Returns a list of the most important documents of a corpus using a variation of the TextRank algorithm. The input must have at least INPUT_MIN_LENGTH documents for the summary to make sense. The length of the output can be specified using the ratio parameter, which determines how many documents will be chosen for the summary (defaults at 20% of the number of documents of the corpus). The most important documents are returned as a list sorted by the document score, highest first. """ hashable_corpus = _build_hasheable_corpus(corpus) # If the corpus is empty, the function ends. if len(corpus) == 0: logger.warning("Input corpus is empty.") return # Warns the user if there are too few documents. if len(corpus) < INPUT_MIN_LENGTH: logger.warning("Input corpus is expected to have at least " + str(INPUT_MIN_LENGTH) + " documents.") graph = _build_graph(hashable_corpus) _set_graph_edge_weights(graph) _remove_unreachable_nodes(graph) pagerank_scores = _pagerank(graph) hashable_corpus.sort(key=lambda doc: pagerank_scores.get(doc, 0), reverse=True) return [list(doc) for doc in hashable_corpus[:int(len(corpus) * ratio)]] def summarize(text, ratio=0.2, word_count=None, split=False): """ Returns a summarized version of the given text using a variation of the TextRank algorithm. The input must be longer than INPUT_MIN_LENGTH sentences for the summary to make sense and must be given as a string. The output summary will consist of the most representative sentences and will also be returned as a string, divided by newlines. If the split parameter is set to True, a list of sentences will be returned. The length of the output can be specified using the ratio and word_count parameters: ratio should be a number between 0 and 1 that determines the percentage of the number of sentences of the original text to be chosen for the summary (defaults at 0.2). word_count determines how many words will the output contain. If both parameters are provided, the ratio will be ignored. """ # Gets a list of processed sentences. sentences = _clean_text_by_sentences(text) # If no sentence could be identified, the function ends. if len(sentences) == 0: logger.warning("Input text is empty.") return # Warns if the text is too short. if len(sentences) < INPUT_MIN_LENGTH: logger.warning("Input text is expected to have at least " + str(INPUT_MIN_LENGTH) + " sentences.") corpus = _build_corpus(sentences) most_important_docs = summarize_corpus(corpus, ratio=ratio if word_count is None else 1) # Extracts the most important sentences with the selected criterion. extracted_sentences = _extract_important_sentences(sentences, corpus, most_important_docs, word_count) # Sorts the extracted sentences by apparition order in the original text. extracted_sentences.sort(key=lambda s: s.index) return _format_results(extracted_sentences, split)
gpl-3.0
aaronorosen/horizon-congress
horizon/test/tests/middleware.py
4
2488
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import time from django.conf import settings from django.http import HttpResponseRedirect # noqa from horizon import exceptions from horizon import middleware from horizon.test import helpers as test class MiddlewareTests(test.TestCase): def test_redirect_login_fail_to_login(self): url = settings.LOGIN_URL request = self.factory.post(url) mw = middleware.HorizonMiddleware() resp = mw.process_exception(request, exceptions.NotAuthorized()) resp.client = self.client self.assertRedirects(resp, url) def test_redirect_session_timeout(self): requested_url = '/project/instances/' response_url = '%s?next=%s' % (settings.LOGOUT_URL, requested_url) request = self.factory.get(requested_url) try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 request.session['last_activity'] = int(time.time()) - (timeout + 10) mw = middleware.HorizonMiddleware() resp = mw.process_request(request) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.get('Location'), response_url) def test_process_response_redirect_on_ajax_request(self): url = settings.LOGIN_URL mw = middleware.HorizonMiddleware() request = self.factory.post(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest') request.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' request.horizon = {'async_messages': [('error', 'error_msg', 'extra_tag')]} response = HttpResponseRedirect(url) response.client = self.client resp = mw.process_response(request, response) self.assertEqual(resp.status_code, 200) self.assertEqual(resp['X-Horizon-Location'], url)
apache-2.0
adsabs/mission-control
mc/tests/stubdata/github_commit_payload.py
3
2254
payload='''{ "sha": "d0e1b1f82ddd1f2c42afbe15f624b120db66fbb4", "url": "https://api.github.com/repos/adsabs/adsws/git/commits/d0e1b1f82ddd1f2c42afbe15f624b120db66fbb4", "html_url": "https://github.com/adsabs/adsws/commit/d0e1b1f82ddd1f2c42afbe15f624b120db66fbb4", "author": { "name": "Vladimir Sudilovsky", "email": "[email protected]", "date": "2015-07-23T19:10:34Z" }, "committer": { "name": "Vladimir Sudilovsky", "email": "[email protected]", "date": "2015-07-23T19:10:34Z" }, "tree": { "sha": "69b861ea3eaaac9ce895bfea6eca3ccd4ac0c35e", "url": "https://api.github.com/repos/adsabs/adsws/git/trees/69b861ea3eaaac9ce895bfea6eca3ccd4ac0c35e" }, "message": "Merge branch 'issue#72'", "parents": [ { "sha": "dc476fa3ec5557bee014943f6e40bb2ab7f87f36", "url": "https://api.github.com/repos/adsabs/adsws/git/commits/dc476fa3ec5557bee014943f6e40bb2ab7f87f36", "html_url": "https://github.com/adsabs/adsws/commit/dc476fa3ec5557bee014943f6e40bb2ab7f87f36" }, { "sha": "efd61c3a0422eef8e84755fb57e9e9f892a6e0b5", "url": "https://api.github.com/repos/adsabs/adsws/git/commits/efd61c3a0422eef8e84755fb57e9e9f892a6e0b5", "html_url": "https://github.com/adsabs/adsws/commit/efd61c3a0422eef8e84755fb57e9e9f892a6e0b5" } ] }''' payload_tag = '''{ "ref": "refs/tags/v1.0.0", "url": "https://api.github.com/repos/adsabs/adsws/git/refs/tags/v1.0.0", "object": { "sha": "unnitest-tag-commit", "type": "tag", "url": "https://api.github.com/repos/adsabs/adsws/git/tags/d0e1b1f82ddd1f2c42afbe15f624b120db66fbb4" } }''' payload_get_tag = '''{ "sha": "unnitest-tag-commit", "url": "https://api.github.com/repos/adsabs/governor/git/tags/unnitest-tag-commit", "tagger": { "name": "adsabs", "email": "[email protected]", "date": "2015-08-19T14:52:49Z" }, "object": { "sha": "unittest-commit", "type": "commit", "url": "https://api.github.com/repos/adsabs/governor/git/commits/2a047ead58a3a87b46388ac67fe08c944c3230e0" }, "tag": "v1.0.0", "message": "First version release 1.0.0" }''' payload_tag_fail = '''{ "message": "Not Found", "documentation_url": "https://developer.github.com/v3" }'''
mit
claws/AutobahnPython
examples/twisted/websocket/ping/client.py
16
1839
############################################################################### ## ## Copyright (C) 2011-2013 Tavendo GmbH ## ## 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 sys from twisted.internet import reactor from twisted.python import log from autobahn.twisted.websocket import WebSocketClientFactory, \ WebSocketClientProtocol, \ connectWS class PingClientProtocol(WebSocketClientProtocol): def onOpen(self): self.pingsReceived = 0 self.pongsSent = 0 def onClose(self, wasClean, code, reason): reactor.stop() def onPing(self, payload): self.pingsReceived += 1 print("Ping received from {} - {}".format(self.peer, self.pingsReceived) self.sendPong(payload) self.pongsSent += 1 print("Pong sent to {} - {}".format(self.peer, self.pongsSent) if __name__ == '__main__': log.startLogging(sys.stdout) if len(sys.argv) < 2: print("Need the WebSocket server address, i.e. ws://localhost:9000") sys.exit(1) factory = WebSocketClientFactory(sys.argv[1], debug = 'debug' in sys.argv) factory.protocol = PingClientProtocol connectWS(factory) reactor.run()
apache-2.0
futursolo/FutureFinity
examples/get_post_form.py
1
1404
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2016 Futur Solo # # 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 futurefinity.web import asyncio app = futurefinity.web.Application() @app.add_handler("/") class MainHandler(futurefinity.web.RequestHandler): async def get(self, *args, **kwargs): username = self.get_link_arg("username", default=None) if self.get_link_arg("username"): return "Hi, %s!" % username return ("<form method=\"post\">" "<input type=\"text\" name=\"username\">" "<input type=\"submit\" value=\"submit\">" "</form>") async def post(self, *args, **kwargs): username = self.get_body_arg("username") return "Hi, %s!" % username app.listen(23333) try: asyncio.get_event_loop().run_forever() except KeyboardInterrupt: pass
apache-2.0
watonyweng/horizon
openstack_dashboard/test/integration_tests/tests/test_sahara_job_binaries.py
50
3397
# 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 openstack_dashboard.test.integration_tests import helpers from openstack_dashboard.test.integration_tests.pages.project.data_processing\ import jobbinariespage from openstack_dashboard.test.integration_tests.tests import decorators JOB_BINARY_INTERNAL = { # Size of binary name is limited to 50 characters jobbinariespage.JobbinariesPage.BINARY_NAME: helpers.gen_random_resource_name(resource='jobbinary', timestamp=False)[0:50], jobbinariespage.JobbinariesPage.BINARY_STORAGE_TYPE: "Internal database", jobbinariespage.JobbinariesPage.BINARY_URL: None, jobbinariespage.JobbinariesPage.INTERNAL_BINARY: "*Create a script", jobbinariespage.JobbinariesPage.BINARY_PATH: None, jobbinariespage.JobbinariesPage.SCRIPT_NAME: helpers.gen_random_resource_name(resource='scriptname', timestamp=False), jobbinariespage.JobbinariesPage.SCRIPT_TEXT: "test_script_text", jobbinariespage.JobbinariesPage.USERNAME: None, jobbinariespage.JobbinariesPage.PASSWORD: None, jobbinariespage.JobbinariesPage.DESCRIPTION: "test description" } @decorators.services_required("sahara") class TestSaharaJobBinary(helpers.TestCase): def _sahara_create_delete_job_binary(self, job_binary_template): job_name = \ job_binary_template[jobbinariespage.JobbinariesPage.BINARY_NAME] # create job binary job_binary_pg = self.home_pg.go_to_dataprocessing_jobbinariespage() self.assertFalse(job_binary_pg.is_job_binary_present(job_name), "Job binary was present in the binaries table" " before its creation.") job_binary_pg.create_job_binary(**job_binary_template) # verify that job is created without problems self.assertFalse(job_binary_pg.is_error_message_present(), "Error message occurred during binary job creation.") self.assertTrue(job_binary_pg.is_job_binary_present(job_name), "Job binary is not in the binaries job table after" " its creation.") # delete binary job job_binary_pg.delete_job_binary(job_name) # verify that job was successfully deleted self.assertFalse(job_binary_pg.is_error_message_present(), "Error message occurred during binary job deletion.") self.assertFalse(job_binary_pg.is_job_binary_present(job_name), "Job binary was not removed from binaries job table.") def test_sahara_create_delete_job_binary_internaldb(self): """Test the creation of a Job Binary in the Internal DB.""" self._sahara_create_delete_job_binary(JOB_BINARY_INTERNAL)
apache-2.0
sebrandon1/neutron
neutron/extensions/segment.py
4
8943
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P. # # 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 abc import six from neutron_lib.api import converters from neutron_lib import constants from neutron.api import extensions from neutron.api.v2 import attributes from neutron.api.v2 import base from neutron.extensions import providernet from neutron import manager SEGMENT = 'segment' SEGMENTS = '%ss' % SEGMENT SEGMENT_ID = 'segment_id' NETWORK_TYPE = 'network_type' PHYSICAL_NETWORK = 'physical_network' SEGMENTATION_ID = 'segmentation_id' NAME_LEN = attributes.NAME_MAX_LEN DESC_LEN = attributes.DESCRIPTION_MAX_LEN # Attribute Map RESOURCE_ATTRIBUTE_MAP = { SEGMENTS: { 'id': {'allow_post': False, 'allow_put': False, 'validate': {'type:uuid': None}, 'is_visible': True, 'primary_key': True}, 'tenant_id': {'allow_post': True, 'allow_put': False, 'validate': {'type:string': attributes.TENANT_ID_MAX_LEN}, 'is_visible': False}, 'network_id': {'allow_post': True, 'allow_put': False, 'validate': {'type:uuid': None}, 'is_visible': True}, PHYSICAL_NETWORK: {'allow_post': True, 'allow_put': False, 'default': constants.ATTR_NOT_SPECIFIED, 'validate': {'type:string': providernet.PHYSICAL_NETWORK_MAX_LEN}, 'is_visible': True}, NETWORK_TYPE: {'allow_post': True, 'allow_put': False, 'validate': {'type:string': providernet.NETWORK_TYPE_MAX_LEN}, 'is_visible': True}, SEGMENTATION_ID: {'allow_post': True, 'allow_put': False, 'default': constants.ATTR_NOT_SPECIFIED, 'convert_to': converters.convert_to_int, 'is_visible': True}, 'name': {'allow_post': True, 'allow_put': True, 'default': constants.ATTR_NOT_SPECIFIED, 'validate': {'type:string_or_none': NAME_LEN}, 'is_visible': True}, 'description': {'allow_post': True, 'allow_put': True, 'default': constants.ATTR_NOT_SPECIFIED, 'validate': {'type:string_or_none': DESC_LEN}, 'is_visible': True}, }, attributes.SUBNETS: { SEGMENT_ID: {'allow_post': True, 'allow_put': False, 'default': None, 'validate': {'type:uuid_or_none': None}, 'is_visible': True, }, }, } class Segment(extensions.ExtensionDescriptor): """Extension class supporting Segments.""" @classmethod def get_name(cls): return "Segment" @classmethod def get_alias(cls): return "segment" @classmethod def get_description(cls): return "Segments extension." @classmethod def get_updated(cls): return "2016-02-24T17:00:00-00:00" @classmethod def get_resources(cls): """Returns Extended Resource for service type management.""" attributes.PLURALS[SEGMENTS] = SEGMENT resource_attributes = RESOURCE_ATTRIBUTE_MAP[SEGMENTS] controller = base.create_resource( SEGMENTS, SEGMENT, manager.NeutronManager.get_service_plugins()[SEGMENTS], resource_attributes) return [extensions.ResourceExtension(SEGMENTS, controller, attr_map=resource_attributes)] def get_extended_resources(self, version): if version == "2.0": return RESOURCE_ATTRIBUTE_MAP else: return {} @six.add_metaclass(abc.ABCMeta) class SegmentPluginBase(object): @abc.abstractmethod def create_segment(self, context, segment): """Create a segment. Create a segment, which represents an L2 segment of a network. :param context: neutron api request context :param segment: dictionary describing the segment, with keys as listed in the :obj:`RESOURCE_ATTRIBUTE_MAP` object in :file:`neutron/extensions/segment.py`. All keys will be populated. """ @abc.abstractmethod def update_segment(self, context, uuid, segment): """Update values of a segment. :param context: neutron api request context :param uuid: UUID representing the segment to update. :param segment: dictionary with keys indicating fields to update. valid keys are those that have a value of True for 'allow_put' as listed in the :obj:`RESOURCE_ATTRIBUTE_MAP` object in :file:`neutron/extensions/segment.py`. """ @abc.abstractmethod def get_segment(self, context, uuid, fields=None): """Retrieve a segment. :param context: neutron api request context :param uuid: UUID representing the segment to fetch. :param fields: a list of strings that are valid keys in a segment dictionary as listed in the :obj:`RESOURCE_ATTRIBUTE_MAP` object in :file:`neutron/extensions/segment.py`. Only these fields will be returned. """ @abc.abstractmethod def get_segments(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): """Retrieve a list of segments. The contents of the list depends on the identity of the user making the request (as indicated by the context) as well as any filters. :param context: neutron api request context :param filters: a dictionary with keys that are valid keys for a segment as listed in the :obj:`RESOURCE_ATTRIBUTE_MAP` object in :file:`neutron/extensions/segment.py`. Values in this dictionary are an iterable containing values that will be used for an exact match comparison for that value. Each result returned by this function will have matched one of the values for each key in filters. :param fields: a list of strings that are valid keys in a segment dictionary as listed in the :obj:`RESOURCE_ATTRIBUTE_MAP` object in :file:`neutron/extensions/segment.py`. Only these fields will be returned. """ @abc.abstractmethod def delete_segment(self, context, uuid): """Delete a segment. :param context: neutron api request context :param uuid: UUID representing the segment to delete. """ @abc.abstractmethod def get_segments_count(self, context, filters=None): """Return the number of segments. The result depends on the identity of the user making the request (as indicated by the context) as well as any filters. :param context: neutron api request context :param filters: a dictionary with keys that are valid keys for a segment as listed in the :obj:`RESOURCE_ATTRIBUTE_MAP` object in :file:`neutron/extensions/segment.py`. Values in this dictionary are an iterable containing values that will be used for an exact match comparison for that value. Each result returned by this function will have matched one of the values for each key in filters. """ def get_plugin_description(self): return "Network Segments" @classmethod def get_plugin_type(cls): return SEGMENTS
apache-2.0
typester/emacs
etc/emacs3.py
6
8537
""" Warning: This file is automatically generated from emacs2.py with the 2to3 script. Do not hand edit. """ """Definitions used by commands sent to inferior Python in python.el.""" # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc. # Author: Dave Love <[email protected]> # This file is part of GNU Emacs. # GNU Emacs 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. # GNU Emacs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. import os, sys, traceback, inspect, __main__ try: set except: from sets import Set as set __all__ = ["eexecfile", "eargs", "complete", "ehelp", "eimport", "modpath"] def format_exception (filename, should_remove_self): type, value, tb = sys.exc_info () sys.last_type = type sys.last_value = value sys.last_traceback = tb if type is SyntaxError: try: # parse the error message msg, (dummy_filename, lineno, offset, line) = value except: pass # Not the format we expect; leave it alone else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value res = traceback.format_exception_only (type, value) # There are some compilation errors which do not provide traceback so we # should not massage it. if should_remove_self: tblist = traceback.extract_tb (tb) del tblist[:1] res = traceback.format_list (tblist) if res: res.insert(0, "Traceback (most recent call last):\n") res[len(res):] = traceback.format_exception_only (type, value) # traceback.print_exception(type, value, tb) for line in res: print(line, end=' ') def eexecfile (file): """Execute FILE and then remove it. Execute the file within the __main__ namespace. If we get an exception, print a traceback with the top frame (ourselves) excluded.""" # We cannot use real execfile since it has a bug where the file stays # locked forever (under w32) if SyntaxError occurs. # --- code based on code.py and PyShell.py. try: try: source = open (file, "r").read() code = compile (source, file, "exec") # Other exceptions (shouldn't be any...) will (correctly) fall # through to "final". except (OverflowError, SyntaxError, ValueError): # FIXME: When can compile() raise anything else than # SyntaxError ???? format_exception (file, False) return try: exec(code, __main__.__dict__) except: format_exception (file, True) finally: os.remove (file) def eargs (name, imports): "Get arglist of NAME for Eldoc &c." try: if imports: exec(imports) parts = name.split ('.') if len (parts) > 1: exec('import ' + parts[0]) # might fail func = eval (name) if inspect.isbuiltin (func) or type(func) is type: doc = func.__doc__ if doc.find (' ->') != -1: print('_emacs_out', doc.split (' ->')[0]) else: print('_emacs_out', doc.split ('\n')[0]) return if inspect.ismethod (func): func = func.im_func if not inspect.isfunction (func): print('_emacs_out ') return (args, varargs, varkw, defaults) = inspect.getargspec (func) # No space between name and arglist for consistency with builtins. print('_emacs_out', \ func.__name__ + inspect.formatargspec (args, varargs, varkw, defaults)) except: print("_emacs_out ") def all_names (object): """Return (an approximation to) a list of all possible attribute names reachable via the attributes of OBJECT, i.e. roughly the leaves of the dictionary tree under it.""" def do_object (object, names): if inspect.ismodule (object): do_module (object, names) elif inspect.isclass (object): do_class (object, names) # Might have an object without its class in scope. elif hasattr (object, '__class__'): names.add ('__class__') do_class (object.__class__, names) # Probably not a good idea to try to enumerate arbitrary # dictionaries... return names def do_module (module, names): if hasattr (module, '__all__'): # limited export list names.update(module.__all__) for i in module.__all__: do_object (getattr (module, i), names) else: # use all names names.update(dir (module)) for i in dir (module): do_object (getattr (module, i), names) return names def do_class (object, names): ns = dir (object) names.update(ns) if hasattr (object, '__bases__'): # superclasses for i in object.__bases__: do_object (i, names) return names return do_object (object, set([])) def complete (name, imports): """Complete TEXT in NAMESPACE and print a Lisp list of completions. Exec IMPORTS first.""" import __main__, keyword def class_members(object): names = dir (object) if hasattr (object, '__bases__'): for super in object.__bases__: names = class_members (super) return names names = set([]) base = None try: dict = __main__.__dict__.copy() if imports: exec(imports, dict) l = len (name) if not "." in name: for src in [dir (__builtins__), keyword.kwlist, list(dict.keys())]: for elt in src: if elt[:l] == name: names.add(elt) else: base = name[:name.rfind ('.')] name = name[name.rfind('.')+1:] try: object = eval (base, dict) names = set(dir (object)) if hasattr (object, '__class__'): names.add('__class__') names.update(class_members (object)) except: names = all_names (dict) except: print(sys.exc_info()) names = [] l = len(name) print('_emacs_out (', end=' ') for n in names: if name == n[:l]: if base: print('"%s.%s"' % (base, n), end=' ') else: print('"%s"' % n, end=' ') print(')') def ehelp (name, imports): """Get help on string NAME. First try to eval name for, e.g. user definitions where we need the object. Otherwise try the string form.""" locls = {} if imports: try: exec(imports, locls) except: pass try: help (eval (name, globals(), locls)) except: help (name) def eimport (mod, dir): """Import module MOD with directory DIR at the head of the search path. NB doesn't load from DIR if MOD shadows a system module.""" from __main__ import __dict__ path0 = sys.path[0] sys.path[0] = dir try: try: if mod in __dict__ and inspect.ismodule (__dict__[mod]): reload (__dict__[mod]) else: __dict__[mod] = __import__ (mod) except: (type, value, tb) = sys.exc_info () print("Traceback (most recent call last):") traceback.print_exception (type, value, tb.tb_next) finally: sys.path[0] = path0 def modpath (module): """Return the source file for the given MODULE (or None). Assumes that MODULE.py and MODULE.pyc are in the same directory.""" try: path = __import__ (module).__file__ if path[-4:] == '.pyc' and os.path.exists (path[0:-1]): path = path[:-1] print("_emacs_out", path) except: print("_emacs_out ()") # print '_emacs_ok' # ready for input and can call continuation # arch-tag: 37bfed38-5f4a-4027-a2bf-d5f41819dd89
gpl-3.0